diff --git a/librarian.yaml b/librarian.yaml index 641dbe4c2006..7aa254eee58f 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.15.1-0.20260528141105-567c9bf1faa7 repo: googleapis/google-cloud-python sources: googleapis: - commit: 43731d5d22f8e3526ba7aa708da9d5de26043d0f - sha256: d146cfa257ffa00fc298ec7b6f73f9c7395a5a5ba050dcc553cfd78d6705bc3b + commit: dae2a496666e372c1ebf56ceb54fe7f467a2c10e + sha256: 867490e3ce7818a2011475a888ce5d77c68cb7a13764f47d9aec8cf3038320e0 default: output: packages tag_format: '{name}-v{version}' diff --git a/packages/google-ads-datamanager/google/ads/datamanager/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager/__init__.py index e722315dcb87..4c2ea0af79c2 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager/__init__.py @@ -57,6 +57,8 @@ from google.ads.datamanager_v1.types.age_range import AgeRange from google.ads.datamanager_v1.types.audience import ( AudienceMember, + CompositeData, + IpData, MobileData, PairData, PpidData, @@ -70,6 +72,7 @@ ProductAccount, ) from google.ads.datamanager_v1.types.device_info import DeviceInfo +from google.ads.datamanager_v1.types.encrypted_user_id import EncryptedUserId from google.ads.datamanager_v1.types.encryption_info import ( AwsWrappedKeyInfo, EncryptionInfo, @@ -212,6 +215,8 @@ "UserListServiceAsyncClient", "AgeRange", "AudienceMember", + "CompositeData", + "IpData", "MobileData", "PairData", "PpidData", @@ -225,6 +230,7 @@ "ProductAccount", "Product", "DeviceInfo", + "EncryptedUserId", "AwsWrappedKeyInfo", "EncryptionInfo", "GcpWrappedKeyInfo", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py index 2e45c6a0ee50..ada6908ff2af 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/__init__.py @@ -48,11 +48,20 @@ UserListServiceClient, ) from .types.age_range import AgeRange -from .types.audience import AudienceMember, MobileData, PairData, PpidData, UserIdData +from .types.audience import ( + AudienceMember, + CompositeData, + IpData, + MobileData, + PairData, + PpidData, + UserIdData, +) from .types.cart_data import CartData, Item, ItemCustomVariable from .types.consent import Consent, ConsentStatus from .types.destination import Destination, Product, ProductAccount from .types.device_info import DeviceInfo +from .types.encrypted_user_id import EncryptedUserId from .types.encryption_info import AwsWrappedKeyInfo, EncryptionInfo, GcpWrappedKeyInfo from .types.error import ErrorReason from .types.event import ( @@ -254,6 +263,7 @@ def _get_version(dependency_name): "AwsWrappedKeyInfo", "Baseline", "CartData", + "CompositeData", "Consent", "ConsentStatus", "ContactIdInfo", @@ -270,6 +280,7 @@ def _get_version(dependency_name): "Destination", "DeviceInfo", "Encoding", + "EncryptedUserId", "EncryptionInfo", "ErrorCount", "ErrorInfo", @@ -290,6 +301,7 @@ def _get_version(dependency_name): "IngestEventsResponse", "IngestedUserListInfo", "IngestionServiceClient", + "IpData", "Item", "ItemCustomVariable", "ItemParameter", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py index 85cd0e039d1e..2dfc20157877 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/__init__.py @@ -18,6 +18,8 @@ ) from .audience import ( AudienceMember, + CompositeData, + IpData, MobileData, PairData, PpidData, @@ -40,6 +42,9 @@ from .device_info import ( DeviceInfo, ) +from .encrypted_user_id import ( + EncryptedUserId, +) from .encryption_info import ( AwsWrappedKeyInfo, EncryptionInfo, @@ -180,6 +185,8 @@ __all__ = ( "AgeRange", "AudienceMember", + "CompositeData", + "IpData", "MobileData", "PairData", "PpidData", @@ -193,6 +200,7 @@ "ProductAccount", "Product", "DeviceInfo", + "EncryptedUserId", "AwsWrappedKeyInfo", "EncryptionInfo", "GcpWrappedKeyInfo", diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/audience.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/audience.py index 6d983c72d910..0cfb244c8b30 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/audience.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/audience.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore from google.ads.datamanager_v1.types import consent as gad_consent @@ -30,6 +31,8 @@ "MobileData", "UserIdData", "PpidData", + "CompositeData", + "IpData", }, ) @@ -74,6 +77,10 @@ class AudienceMember(proto.Message): identifiers. This feature is only available to data partners. + This field is a member of `oneof`_ ``data``. + composite_data (google.ads.datamanager_v1.types.CompositeData): + Group of multiple identifier types. + This field is a member of `oneof`_ ``data``. consent (google.ads.datamanager_v1.types.Consent): Optional. The consent setting for the user. @@ -113,6 +120,12 @@ class AudienceMember(proto.Message): oneof="data", message="PpidData", ) + composite_data: "CompositeData" = proto.Field( + proto.MESSAGE, + number=8, + oneof="data", + message="CompositeData", + ) consent: gad_consent.Consent = proto.Field( proto.MESSAGE, number=3, @@ -194,4 +207,63 @@ class PpidData(proto.Message): ) +class CompositeData(proto.Message): + r"""Composite data holding identifiers and associated data for a user. + At least one of ``user_data`` or ``ip_data`` is required. + + Attributes: + user_data (google.ads.datamanager_v1.types.UserData): + Optional. User-provided data that identifies + the user. + ip_data (MutableSequence[google.ads.datamanager_v1.types.IpData]): + Optional. IP address data representing + customer interaction used to build the audience. + """ + + user_data: gad_user_data.UserData = proto.Field( + proto.MESSAGE, + number=1, + message=gad_user_data.UserData, + ) + ip_data: MutableSequence["IpData"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="IpData", + ) + + +class IpData(proto.Message): + r"""IP address information for a user. We recommend including + observe_start_time and observe_end_time to help improve Customer + Match match rates. + + Attributes: + ip_address (str): + Required. IP address captured at the time of + customer interaction. Accepts standard string + formats for both IPv4 and IPv6. + observe_start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. First recorded interaction time + from this IP address in a session. + observe_end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Last recorded interaction time from + this IP address in a session. + """ + + ip_address: str = proto.Field( + proto.STRING, + number=1, + ) + observe_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + observe_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py index fb07cca831f3..7c9767b41b3a 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/destination.py @@ -156,6 +156,8 @@ class AccountType(proto.Enum): Google Analytics. GOOGLE_AD_MANAGER_AUDIENCE_LINK (6): Google Ad Manager audience link. + FLOODLIGHT_CONFIG (7): + Floodlight configuration. """ ACCOUNT_TYPE_UNSPECIFIED = 0 @@ -165,6 +167,7 @@ class AccountType(proto.Enum): DATA_PARTNER = 4 GOOGLE_ANALYTICS_PROPERTY = 5 GOOGLE_AD_MANAGER_AUDIENCE_LINK = 6 + FLOODLIGHT_CONFIG = 7 product: "Product" = proto.Field( proto.ENUM, diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/encrypted_user_id.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/encrypted_user_id.py new file mode 100644 index 000000000000..83957a60e444 --- /dev/null +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/encrypted_user_id.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ads.datamanager.v1", + manifest={ + "EncryptedUserId", + }, +) + + +class EncryptedUserId(proto.Message): + r"""A user identifier issued to be used for attribution. All + fields are required if this is used. + + Attributes: + encrypted_id (str): + Required. The alphanumeric encrypted id. + entity_type (google.ads.datamanager_v1.types.EncryptedUserId.EncryptionEntityType): + Required. The encryption entity type. This + should match the encryption configuration for ad + serving or Data Transfer. + entity_id (int): + Required. The encryption entity ID. This + should match the encryption configuration for ad + serving or Data Transfer. + source (google.ads.datamanager_v1.types.EncryptedUserId.EncryptionSource): + Required. Describes whether the encrypted + cookie was received from ad serving (the %m + macro) or from Data Transfer. + """ + + class EncryptionEntityType(proto.Enum): + r"""The encryption entity type. + + Values: + ENCRYPTION_ENTITY_TYPE_UNSPECIFIED (0): + Unspecified encryption entity type. + CAMPAIGN_MANAGER_ACCOUNT (1): + Campaign Manager 360 account. + CAMPAIGN_MANAGER_ADVERTISER (2): + Campaign Manager 360 advertiser. + DISPLAY_VIDEO_PARTNER (3): + Display & Video 360 partner. + DISPLAY_VIDEO_ADVERTISER (4): + Display & Video 360 advertiser. + GOOGLE_ADS_CUSTOMER (5): + Google Ads customer. + GOOGLE_AD_MANAGER_NETWORK_CODE (6): + Google Ad Manager network code. + """ + + ENCRYPTION_ENTITY_TYPE_UNSPECIFIED = 0 + CAMPAIGN_MANAGER_ACCOUNT = 1 + CAMPAIGN_MANAGER_ADVERTISER = 2 + DISPLAY_VIDEO_PARTNER = 3 + DISPLAY_VIDEO_ADVERTISER = 4 + GOOGLE_ADS_CUSTOMER = 5 + GOOGLE_AD_MANAGER_NETWORK_CODE = 6 + + class EncryptionSource(proto.Enum): + r"""The encryption source. + + Values: + ENCRYPTION_SOURCE_UNSPECIFIED (0): + Unspecified encryption source. + AD_SERVING (1): + Ad serving encryption source. + DATA_TRANSFER (2): + Data transfer encryption source. + """ + + ENCRYPTION_SOURCE_UNSPECIFIED = 0 + AD_SERVING = 1 + DATA_TRANSFER = 2 + + encrypted_id: str = proto.Field( + proto.STRING, + number=1, + ) + entity_type: EncryptionEntityType = proto.Field( + proto.ENUM, + number=2, + enum=EncryptionEntityType, + ) + entity_id: int = proto.Field( + proto.INT64, + number=3, + ) + source: EncryptionSource = proto.Field( + proto.ENUM, + number=4, + enum=EncryptionSource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py index 7319d31924d9..3a80492b6c88 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/error.py @@ -162,9 +162,13 @@ class ErrorReason(proto.Enum): An event had 2 or more Google Analytics destinations. FIELD_VALUE_TOO_LONG (50): - The field value is too long. + Length of the field value is too long. + FIELD_VALUE_TOO_SHORT (106): + Length of the field value is too short. TOO_MANY_ELEMENTS (51): Too many elements in a list in the request. + TOO_FEW_ELEMENTS (105): + Too few elements in a list in the request. ALREADY_EXISTS (52): The resource already exists. IMMUTABLE_FIELD_FOR_UPDATE (53): @@ -342,6 +346,13 @@ class ErrorReason(proto.Enum): CUSTOM_VARIABLE_NOT_FOUND (120): The destination does not have a custom variable with a name that matches the specified ``variable``. + BASELINE_LOCATION_AUTO_DETECTION_FAILED (122): + The + [location_auto_detection_enabled][google.ads.datamanager.v1.Baseline.location_auto_detection_enabled] + field of the request was set to ``true``, but auto detection + of baseline location failed. + INSIGHTS_MISSING_FOR_DIMENSION (123): + Insights missing for this dimension. """ ERROR_REASON_UNSPECIFIED = 0 @@ -395,7 +406,9 @@ class ErrorReason(proto.Enum): INVALID_REQUEST_ID = 48 MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT = 49 FIELD_VALUE_TOO_LONG = 50 + FIELD_VALUE_TOO_SHORT = 106 TOO_MANY_ELEMENTS = 51 + TOO_FEW_ELEMENTS = 105 ALREADY_EXISTS = 52 IMMUTABLE_FIELD_FOR_UPDATE = 53 INVALID_RESOURCE_NAME = 54 @@ -463,6 +476,8 @@ class ErrorReason(proto.Enum): CUSTOM_VARIABLE_NOT_ENABLED = 118 INVALID_CUSTOM_VARIABLE_VALUE = 119 CUSTOM_VARIABLE_NOT_FOUND = 120 + BASELINE_LOCATION_AUTO_DETECTION_FAILED = 122 + INSIGHTS_MISSING_FOR_DIMENSION = 123 __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py index a61ad69adb3f..f5c680a71166 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/event.py @@ -22,7 +22,11 @@ from google.ads.datamanager_v1.types import cart_data as gad_cart_data from google.ads.datamanager_v1.types import consent as gad_consent -from google.ads.datamanager_v1.types import device_info, experimental_field +from google.ads.datamanager_v1.types import ( + device_info, + encrypted_user_id, + experimental_field, +) from google.ads.datamanager_v1.types import user_data as gad_user_data from google.ads.datamanager_v1.types import user_properties as gad_user_properties @@ -112,6 +116,11 @@ class Event(proto.Message): with the event, for value-based conversions. This field is a member of `oneof`_ ``_conversion_value``. + conversion_count (float): + Optional. The conversion quantity associated + with the event, for counting-based conversions. + + This field is a member of `oneof`_ ``_conversion_count``. event_source (google.ads.datamanager_v1.types.EventSource): Optional. Signal for where the event happened (web, app, in-store, etc.). @@ -204,6 +213,11 @@ class Event(proto.Message): number=9, optional=True, ) + conversion_count: float = proto.Field( + proto.DOUBLE, + number=23, + optional=True, + ) event_source: "EventSource" = proto.Field( proto.ENUM, number=10, @@ -300,6 +314,17 @@ class AdIdentifiers(proto.Message): advertisers. This would be IDFA on iOS, AdID on Android, or other platforms’ identifiers for advertisers. + dclid (str): + Optional. The display click ID associated + with this event. + impression_id (str): + Optional. The impression ID associated with + this event. + match_id (str): + Optional. The match ID field used to join + this event with a previous event. + encrypted_user_ids (MutableSequence[google.ads.datamanager_v1.types.EncryptedUserId]): + Optional. Any number of encrypted user IDs. """ session_attributes: str = proto.Field( @@ -327,6 +352,25 @@ class AdIdentifiers(proto.Message): proto.STRING, number=6, ) + dclid: str = proto.Field( + proto.STRING, + number=7, + ) + impression_id: str = proto.Field( + proto.STRING, + number=8, + ) + match_id: str = proto.Field( + proto.STRING, + number=9, + ) + encrypted_user_ids: MutableSequence[encrypted_user_id.EncryptedUserId] = ( + proto.RepeatedField( + proto.MESSAGE, + number=10, + message=encrypted_user_id.EncryptedUserId, + ) + ) class CustomVariable(proto.Message): diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py index 8cfa63f65e7c..91cc441a9e06 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/processing_errors.py @@ -34,6 +34,7 @@ class ProcessingErrorReason(proto.Enum): r"""The processing error reason. + New reasons may be added in the future. Values: PROCESSING_ERROR_REASON_UNSPECIFIED (0): @@ -116,6 +117,45 @@ class ProcessingErrorReason(proto.Enum): PROCESSING_ERROR_REASON_ONE_PER_CLICK_CONVERSION_ACTION_NOT_PERMITTED_WITH_BRAID (28): One-per-click conversion actions cannot be used with BRAIDs. + PROCESSING_ERROR_REASON_MATCH_ID_NOT_FOUND (29): + The match ID can not be found. + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_MATCH_ID (30): + The user ID can not be found for the match + ID. + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_GCLID (31): + The user ID can not be found for the GCLID. + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_DCLID (32): + The user ID can not be found for the DCLID. + PROCESSING_ERROR_REASON_INVALID_AD_IDENTIFIERS (33): + There are ad identifiers that are invalid. + PROCESSING_ERROR_REASON_INVALID_MOBILE_ID_FORMAT (34): + The mobile ID format is invalid. + PROCESSING_ERROR_REASON_ORIGINAL_CONVERSIONS_NOT_FOUND (35): + The original conversions can't be found. + PROCESSING_ERROR_REASON_EVENT_ID_DECODE_ERROR (36): + The event ID (dclid or impression ID) cannot + be decoded. + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_IMPRESSION_ID (37): + The user ID cannot be found for the given + impression ID. + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND (38): + The user ID cannot be found. + PROCESSING_ERROR_REASON_CONVERSION_PRECEDES_CLICK (39): + The event timestamp on the event was earlier + than the associated click. + PROCESSING_ERROR_REASON_TOO_RECENT_CLICK (40): + The click occurred too recently. + PROCESSING_ERROR_REASON_INVALID_CLICK (41): + The event can't be attributed to a click + (GCLID). This may be because the click did not + come from a Google Ads campaign, for example. + PROCESSING_ERROR_REASON_INVALID_OPERATING_ACCOUNT_FOR_CLICK (42): + The click from the event isn't associated with the + [``operating_account``][google.ads.datamanager.v1.Destination.operating_account] + of the destination. + PROCESSING_ERROR_REASON_CLICK_NOT_FOUND (43): + A corresponding click can't be found that + matches the provided attributes. """ PROCESSING_ERROR_REASON_UNSPECIFIED = 0 @@ -149,6 +189,21 @@ class ProcessingErrorReason(proto.Enum): PROCESSING_ERROR_REASON_ONE_PER_CLICK_CONVERSION_ACTION_NOT_PERMITTED_WITH_BRAID = ( 28 ) + PROCESSING_ERROR_REASON_MATCH_ID_NOT_FOUND = 29 + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_MATCH_ID = 30 + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_GCLID = 31 + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_DCLID = 32 + PROCESSING_ERROR_REASON_INVALID_AD_IDENTIFIERS = 33 + PROCESSING_ERROR_REASON_INVALID_MOBILE_ID_FORMAT = 34 + PROCESSING_ERROR_REASON_ORIGINAL_CONVERSIONS_NOT_FOUND = 35 + PROCESSING_ERROR_REASON_EVENT_ID_DECODE_ERROR = 36 + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND_FOR_IMPRESSION_ID = 37 + PROCESSING_ERROR_REASON_USER_ID_NOT_FOUND = 38 + PROCESSING_ERROR_REASON_CONVERSION_PRECEDES_CLICK = 39 + PROCESSING_ERROR_REASON_TOO_RECENT_CLICK = 40 + PROCESSING_ERROR_REASON_INVALID_CLICK = 41 + PROCESSING_ERROR_REASON_INVALID_OPERATING_ACCOUNT_FOR_CLICK = 42 + PROCESSING_ERROR_REASON_CLICK_NOT_FOUND = 43 class ProcessingWarningReason(proto.Enum): diff --git a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py index 21dc6fee79bb..f88afce8db7d 100644 --- a/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py +++ b/packages/google-ads-datamanager/google/ads/datamanager_v1/types/request_status_per_destination.py @@ -114,6 +114,28 @@ class RequestStatus(proto.Enum): FAILED = 3 PARTIAL_SUCCESS = 4 + class DataType(proto.Enum): + r"""The type of data. + + Values: + DATA_TYPE_UNSPECIFIED (0): + The data type is unspecified. + EMAIL (1): + The data is an email address. + PHONE_NUMBER (2): + The data is a phone number. + ADDRESS (3): + The data is a physical address. + IP_ADDRESS (4): + The data is an IP address. + """ + + DATA_TYPE_UNSPECIFIED = 0 + EMAIL = 1 + PHONE_NUMBER = 2 + ADDRESS = 3 + IP_ADDRESS = 4 + class IngestAudienceMembersStatus(proto.Message): r"""The status of the ingest audience members request. @@ -149,6 +171,11 @@ class IngestAudienceMembersStatus(proto.Message): The status of the ppid data ingestion to the destination. + This field is a member of `oneof`_ ``status``. + composite_data_ingestion_status (google.ads.datamanager_v1.types.RequestStatusPerDestination.IngestCompositeDataStatus): + The status of the composite data ingestion to + the destination. + This field is a member of `oneof`_ ``status``. """ @@ -182,6 +209,12 @@ class IngestAudienceMembersStatus(proto.Message): oneof="status", message="RequestStatusPerDestination.IngestPpidDataStatus", ) + composite_data_ingestion_status: "RequestStatusPerDestination.IngestCompositeDataStatus" = proto.Field( + proto.MESSAGE, + number=6, + oneof="status", + message="RequestStatusPerDestination.IngestCompositeDataStatus", + ) class RemoveAudienceMembersStatus(proto.Message): r"""The status of the remove audience members request. @@ -218,6 +251,11 @@ class RemoveAudienceMembersStatus(proto.Message): The status of the ppid data removal from the destination. + This field is a member of `oneof`_ ``status``. + composite_data_removal_status (google.ads.datamanager_v1.types.RequestStatusPerDestination.RemoveCompositeDataStatus): + The status of the composite data removal from + the destination. + This field is a member of `oneof`_ ``status``. """ @@ -257,6 +295,12 @@ class RemoveAudienceMembersStatus(proto.Message): message="RequestStatusPerDestination.RemovePpidDataStatus", ) ) + composite_data_removal_status: "RequestStatusPerDestination.RemoveCompositeDataStatus" = proto.Field( + proto.MESSAGE, + number=6, + oneof="status", + message="RequestStatusPerDestination.RemoveCompositeDataStatus", + ) class IngestEventsStatus(proto.Message): r"""The status of the events ingestion to the destination. @@ -542,6 +586,94 @@ class RemovePpidDataStatus(proto.Message): number=2, ) + class IngestCompositeDataStatus(proto.Message): + r"""The status of the composite data ingestion to the destination + containing stats related to the ingestion. + + Attributes: + record_count (int): + The total count of audience members sent in + the upload request for the destination. Includes + all audience members in the request, regardless + of whether they were successfully ingested or + not. + data_type_counts (MutableSequence[google.ads.datamanager_v1.types.RequestStatusPerDestination.DataTypeCount]): + The total count of data types sent in the + upload request for the destination, broken down + by data type. Includes all data types in the + request, regardless of whether they were + successfully ingested or not. + upload_match_rate_range (google.ads.datamanager_v1.types.MatchRateRange): + The match rate range of the upload. + """ + + record_count: int = proto.Field( + proto.INT64, + number=1, + ) + data_type_counts: MutableSequence[ + "RequestStatusPerDestination.DataTypeCount" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="RequestStatusPerDestination.DataTypeCount", + ) + upload_match_rate_range: match_rate.MatchRateRange = proto.Field( + proto.ENUM, + number=3, + enum=match_rate.MatchRateRange, + ) + + class RemoveCompositeDataStatus(proto.Message): + r"""The status of the composite data removal from the + destination. + + Attributes: + record_count (int): + The total count of audience members sent in + the removal request. Includes all audience + members in the request, regardless of whether + they were successfully removed or not. + data_type_counts (MutableSequence[google.ads.datamanager_v1.types.RequestStatusPerDestination.DataTypeCount]): + The total count of data types sent in the + removal request, broken down by data type. + Includes all data types in the request, + regardless of whether they were successfully + removed or not. + """ + + record_count: int = proto.Field( + proto.INT64, + number=1, + ) + data_type_counts: MutableSequence[ + "RequestStatusPerDestination.DataTypeCount" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="RequestStatusPerDestination.DataTypeCount", + ) + + class DataTypeCount(proto.Message): + r"""The count for a specific data type. + + Attributes: + type_ (google.ads.datamanager_v1.types.RequestStatusPerDestination.DataType): + The type of data. + count (int): + The count for this data type. + """ + + type_: "RequestStatusPerDestination.DataType" = proto.Field( + proto.ENUM, + number=1, + enum="RequestStatusPerDestination.DataType", + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + destination: gad_destination.Destination = proto.Field( proto.MESSAGE, number=1, diff --git a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_ingestion_service.py b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_ingestion_service.py index 65de924c2591..dcd7752d8bd6 100644 --- a/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_ingestion_service.py +++ b/packages/google-ads-datamanager/tests/unit/gapic/datamanager_v1/test_ingestion_service.py @@ -64,6 +64,7 @@ consent, destination, device_info, + encrypted_user_id, encryption_info, event, experimental_field, diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py b/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py index 0b3e86714ef4..8f909159b0b6 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py @@ -71,9 +71,11 @@ CostManagementConfig, CreateClusterRequest, CreateNodePoolRequest, + CustomImageConfig, DailyMaintenanceWindow, DatabaseEncryption, DatapathProvider, + DataplaneV2Config, DefaultComputeClassConfig, DefaultSnatStatus, DeleteClusterRequest, @@ -400,10 +402,12 @@ def _get_version(dependency_name): "CostManagementConfig", "CreateClusterRequest", "CreateNodePoolRequest", + "CustomImageConfig", "DNSConfig", "DailyMaintenanceWindow", "DatabaseEncryption", "DatapathProvider", + "DataplaneV2Config", "DefaultComputeClassConfig", "DefaultSnatStatus", "DeleteClusterRequest", diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py b/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py index 91350c4b87d2..7fbbbe7f204e 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py @@ -60,9 +60,11 @@ CostManagementConfig, CreateClusterRequest, CreateNodePoolRequest, + CustomImageConfig, DailyMaintenanceWindow, DatabaseEncryption, DatapathProvider, + DataplaneV2Config, DefaultComputeClassConfig, DefaultSnatStatus, DeleteClusterRequest, @@ -304,8 +306,10 @@ "CostManagementConfig", "CreateClusterRequest", "CreateNodePoolRequest", + "CustomImageConfig", "DailyMaintenanceWindow", "DatabaseEncryption", + "DataplaneV2Config", "DefaultComputeClassConfig", "DefaultSnatStatus", "DeleteClusterRequest", diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py b/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py index e2c17ecc32d1..d53e3231fe72 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py @@ -51,6 +51,7 @@ "AdditionalNodeNetworkConfig", "AdditionalPodNetworkConfig", "ShieldedInstanceConfig", + "CustomImageConfig", "SandboxConfig", "EphemeralStorageConfig", "LocalNvmeSsdBlockConfig", @@ -248,6 +249,7 @@ "NodePoolLoggingConfig", "LoggingVariantConfig", "MonitoringComponentConfig", + "DataplaneV2Config", "PodAutoscaling", "Fleet", "ControlPlaneEndpointsConfig", @@ -441,7 +443,10 @@ class LinuxNodeConfig(proto.Message): net.core.netdev_max_backlog net.core.rmem_max net.core.rmem_default net.core.wmem_default net.core.wmem_max net.core.optmem_max net.core.somaxconn - net.ipv4.tcp_rmem net.ipv4.tcp_wmem net.ipv4.tcp_tw_reuse + net.ipv4.neigh.default.gc_thresh1 + net.ipv4.neigh.default.gc_thresh2 + net.ipv4.neigh.default.gc_thresh3 net.ipv4.tcp_rmem + net.ipv4.tcp_wmem net.ipv4.tcp_tw_reuse net.ipv4.tcp_mtu_probing net.ipv4.tcp_max_orphans net.ipv4.tcp_max_tw_buckets net.ipv4.tcp_syn_retries net.ipv4.tcp_ecn net.ipv4.tcp_congestion_control @@ -450,7 +455,8 @@ class LinuxNodeConfig(proto.Message): net.netfilter.nf_conntrack_tcp_timeout_close_wait net.netfilter.nf_conntrack_tcp_timeout_time_wait net.netfilter.nf_conntrack_tcp_timeout_established - net.netfilter.nf_conntrack_acct kernel.shmmni kernel.shmmax + net.netfilter.nf_conntrack_acct kernel.keys.maxkeys + kernel.keys.maxbytes kernel.shmmni kernel.shmmax kernel.shmall kernel.perf_event_paranoid kernel.sched_rt_runtime_us kernel.softlockup_panic kernel.yama.ptrace_scope kernel.kptr_restrict @@ -1746,6 +1752,10 @@ class NodeConfig(proto.Message): of it will be used. Please see https://cloud.google.com/kubernetes-engine/docs/concepts/node-images for available image types. + node_image_config (google.cloud.container_v1beta1.types.CustomImageConfig): + The node image configuration to use for this node pool. Note + that this is only applicable for node pools using + image_type=CUSTOM. labels (MutableMapping[str, str]): The Kubernetes labels (key/value pairs) to apply to each node. The values in this field are added to the set of @@ -2013,6 +2023,11 @@ class EffectiveCgroupMode(proto.Enum): proto.STRING, number=5, ) + node_image_config: "CustomImageConfig" = proto.Field( + proto.MESSAGE, + number=90, + message="CustomImageConfig", + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -2659,6 +2674,27 @@ class ShieldedInstanceConfig(proto.Message): ) +class CustomImageConfig(proto.Message): + r"""CustomImageConfig contains the information r + + Attributes: + image (str): + The name of the image to use for this node. + image_project (str): + The project containing the image to use for + this node. + """ + + image: str = proto.Field( + proto.STRING, + number=1, + ) + image_project: str = proto.Field( + proto.STRING, + number=3, + ) + + class SandboxConfig(proto.Message): r"""SandboxConfig contains configurations of the sandbox to use for the node. @@ -6709,6 +6745,14 @@ class ClusterUpdate(proto.Message): - "-": picks the default Kubernetes version desired_gcfs_config (google.cloud.container_v1beta1.types.GcfsConfig): The desired GCFS config for the cluster. + desired_image (str): + The desired name of the image to use for this + node. This is used to create clusters using a + custom image. + desired_image_project (str): + The project containing the desired image to + use for this node. This is used to create + clusters using a custom image. desired_database_encryption (google.cloud.container_v1beta1.types.DatabaseEncryption): Configuration of etcd encryption. desired_workload_identity_config (google.cloud.container_v1beta1.types.WorkloadIdentityConfig): @@ -7082,6 +7126,14 @@ class ClusterUpdate(proto.Message): number=109, message="GcfsConfig", ) + desired_image: str = proto.Field( + proto.STRING, + number=44, + ) + desired_image_project: str = proto.Field( + proto.STRING, + number=45, + ) desired_database_encryption: "DatabaseEncryption" = proto.Field( proto.MESSAGE, number=46, @@ -8157,6 +8209,14 @@ class UpdateNodePoolRequest(proto.Message): pool. Please see https://cloud.google.com/kubernetes-engine/docs/concepts/node-images for available image types. + image (str): + The desired name of the image name to use for + this node. This is used to create clusters using + a custom image. + image_project (str): + The project containing the desired image to + use for this node pool. This is used to create + clusters using a custom image. locations (MutableSequence[str]): The desired list of Google Compute Engine `zones `__ @@ -8318,6 +8378,14 @@ class UpdateNodePoolRequest(proto.Message): proto.STRING, number=6, ) + image: str = proto.Field( + proto.STRING, + number=10, + ) + image_project: str = proto.Field( + proto.STRING, + number=11, + ) locations: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=13, @@ -12150,6 +12218,11 @@ class NetworkConfig(proto.Message): [ClusterUpdate.desired_default_enable_private_nodes][google.container.v1beta1.ClusterUpdate.desired_default_enable_private_nodes] This field is a member of `oneof`_ ``_default_enable_private_nodes``. + dataplane_v2_config (google.cloud.container_v1beta1.types.DataplaneV2Config): + Optional. DataplaneV2Config specifies the + DPv2 configuration. + + This field is a member of `oneof`_ ``_dataplane_v2_config``. disable_l4_lb_firewall_reconciliation (bool): Disable L4 load balancer VPC firewalls to enable firewall policies. @@ -12267,6 +12340,12 @@ class Tier(proto.Enum): number=22, optional=True, ) + dataplane_v2_config: "DataplaneV2Config" = proto.Field( + proto.MESSAGE, + number=23, + optional=True, + message="DataplaneV2Config", + ) disable_l4_lb_firewall_reconciliation: bool = proto.Field( proto.BOOL, number=24, @@ -14655,6 +14734,42 @@ class Component(proto.Enum): ) +class DataplaneV2Config(proto.Message): + r"""DataplaneV2Config is the configuration for DPv2. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scalability_mode (google.cloud.container_v1beta1.types.DataplaneV2Config.ScalabilityMode): + Optional. Scalability mode for the cluster. + + This field is a member of `oneof`_ ``_scalability_mode``. + """ + + class ScalabilityMode(proto.Enum): + r"""Options on how to scale the cluster. + + Values: + SCALABILITY_MODE_UNSPECIFIED (0): + Default value. + DISABLED (3): + Disables the scale optimized mode for DPv2. + SCALE_OPTIMIZED (4): + Enables the scale optimized mode for DPv2. + """ + + SCALABILITY_MODE_UNSPECIFIED = 0 + DISABLED = 3 + SCALE_OPTIMIZED = 4 + + scalability_mode: ScalabilityMode = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=ScalabilityMode, + ) + + class PodAutoscaling(proto.Message): r"""PodAutoscaling is used for configuration of parameters for workload autoscaling. diff --git a/packages/google-cloud-container/tests/unit/gapic/container_v1beta1/test_cluster_manager.py b/packages/google-cloud-container/tests/unit/gapic/container_v1beta1/test_cluster_manager.py index b12b0d51ab50..e6e3b4f80933 100644 --- a/packages/google-cloud-container/tests/unit/gapic/container_v1beta1/test_cluster_manager.py +++ b/packages/google-cloud-container/tests/unit/gapic/container_v1beta1/test_cluster_manager.py @@ -3016,6 +3016,8 @@ def test_update_node_pool_non_empty_request_with_auto_populated_field(): node_pool_id="node_pool_id_value", node_version="node_version_value", image_type="image_type_value", + image="image_value", + image_project="image_project_value", name="name_value", etag="etag_value", machine_type="machine_type_value", @@ -3037,6 +3039,8 @@ def test_update_node_pool_non_empty_request_with_auto_populated_field(): node_pool_id="node_pool_id_value", node_version="node_version_value", image_type="image_type_value", + image="image_value", + image_project="image_project_value", name="name_value", etag="etag_value", machine_type="machine_type_value", diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex/__init__.py b/packages/google-cloud-dataplex/google/cloud/dataplex/__init__.py index db8678f0f395..a45538fba7b3 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex/__init__.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex/__init__.py @@ -71,6 +71,10 @@ MetadataServiceClient, ) from google.cloud.dataplex_v1.types.analyze import Content, Environment, Session +from google.cloud.dataplex_v1.types.approval_workflow import ( + ChangeRequest, + DataProductAccessRequest, +) from google.cloud.dataplex_v1.types.business_glossary import ( CreateGlossaryCategoryRequest, CreateGlossaryRequest, @@ -145,6 +149,7 @@ LookupEntryRequest, MetadataFeed, MetadataJob, + ModifyEntryRequest, SearchEntriesRequest, SearchEntriesResponse, SearchEntriesResult, @@ -186,6 +191,8 @@ ListDataAssetsResponse, ListDataProductsRequest, ListDataProductsResponse, + RequestDataProductAccessRequest, + RequestDataProductAccessResponse, UpdateDataAssetRequest, UpdateDataProductRequest, ) @@ -202,6 +209,9 @@ DataQualityRuleResult, DataQualitySpec, ) +from google.cloud.dataplex_v1.types.data_quality_rule_template import ( + DataQualityRuleTemplate, +) from google.cloud.dataplex_v1.types.data_taxonomy import ( CreateDataAttributeBindingRequest, CreateDataAttributeRequest, @@ -226,11 +236,14 @@ UpdateDataTaxonomyRequest, ) from google.cloud.dataplex_v1.types.datascans import ( + CancelDataScanJobRequest, + CancelDataScanJobResponse, CreateDataScanRequest, DataScan, DataScanJob, DataScanType, DeleteDataScanRequest, + ExecutionIdentity, GenerateDataQualityRulesRequest, GenerateDataQualityRulesResponse, GetDataScanJobRequest, @@ -346,6 +359,8 @@ "Content", "Environment", "Session", + "ChangeRequest", + "DataProductAccessRequest", "CreateGlossaryCategoryRequest", "CreateGlossaryRequest", "CreateGlossaryTermRequest", @@ -416,6 +431,7 @@ "LookupEntryRequest", "MetadataFeed", "MetadataJob", + "ModifyEntryRequest", "SearchEntriesRequest", "SearchEntriesResponse", "SearchEntriesResult", @@ -450,6 +466,8 @@ "ListDataAssetsResponse", "ListDataProductsRequest", "ListDataProductsResponse", + "RequestDataProductAccessRequest", + "RequestDataProductAccessResponse", "UpdateDataAssetRequest", "UpdateDataProductRequest", "DataProfileResult", @@ -461,6 +479,7 @@ "DataQualityRule", "DataQualityRuleResult", "DataQualitySpec", + "DataQualityRuleTemplate", "CreateDataAttributeBindingRequest", "CreateDataAttributeRequest", "CreateDataTaxonomyRequest", @@ -482,10 +501,13 @@ "UpdateDataAttributeBindingRequest", "UpdateDataAttributeRequest", "UpdateDataTaxonomyRequest", + "CancelDataScanJobRequest", + "CancelDataScanJobResponse", "CreateDataScanRequest", "DataScan", "DataScanJob", "DeleteDataScanRequest", + "ExecutionIdentity", "GenerateDataQualityRulesRequest", "GenerateDataQualityRulesResponse", "GetDataScanJobRequest", diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/__init__.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/__init__.py index 44a229f174d2..f57d85ad0fe3 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/__init__.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/__init__.py @@ -45,6 +45,7 @@ from .services.dataplex_service import DataplexServiceAsyncClient, DataplexServiceClient from .services.metadata_service import MetadataServiceAsyncClient, MetadataServiceClient from .types.analyze import Content, Environment, Session +from .types.approval_workflow import ChangeRequest, DataProductAccessRequest from .types.business_glossary import ( CreateGlossaryCategoryRequest, CreateGlossaryRequest, @@ -119,6 +120,7 @@ LookupEntryRequest, MetadataFeed, MetadataJob, + ModifyEntryRequest, SearchEntriesRequest, SearchEntriesResponse, SearchEntriesResult, @@ -154,6 +156,8 @@ ListDataAssetsResponse, ListDataProductsRequest, ListDataProductsResponse, + RequestDataProductAccessRequest, + RequestDataProductAccessResponse, UpdateDataAssetRequest, UpdateDataProductRequest, ) @@ -167,6 +171,7 @@ DataQualityRuleResult, DataQualitySpec, ) +from .types.data_quality_rule_template import DataQualityRuleTemplate from .types.data_taxonomy import ( CreateDataAttributeBindingRequest, CreateDataAttributeRequest, @@ -191,11 +196,14 @@ UpdateDataTaxonomyRequest, ) from .types.datascans import ( + CancelDataScanJobRequest, + CancelDataScanJobResponse, CreateDataScanRequest, DataScan, DataScanJob, DataScanType, DeleteDataScanRequest, + ExecutionIdentity, GenerateDataQualityRulesRequest, GenerateDataQualityRulesResponse, GetDataScanJobRequest, @@ -381,9 +389,12 @@ def _get_version(dependency_name): "AssetStatus", "BusinessGlossaryEvent", "BusinessGlossaryServiceClient", + "CancelDataScanJobRequest", + "CancelDataScanJobResponse", "CancelJobRequest", "CancelMetadataJobRequest", "CatalogServiceClient", + "ChangeRequest", "CmekServiceClient", "Content", "ContentServiceClient", @@ -419,6 +430,7 @@ def _get_version(dependency_name): "DataDocumentationResult", "DataDocumentationSpec", "DataProduct", + "DataProductAccessRequest", "DataProductServiceClient", "DataProfileResult", "DataProfileSpec", @@ -428,6 +440,7 @@ def _get_version(dependency_name): "DataQualityResult", "DataQualityRule", "DataQualityRuleResult", + "DataQualityRuleTemplate", "DataQualityScanRuleResult", "DataQualitySpec", "DataScan", @@ -473,6 +486,7 @@ def _get_version(dependency_name): "EntryType", "EntryView", "Environment", + "ExecutionIdentity", "GenerateDataQualityRulesRequest", "GenerateDataQualityRulesResponse", "GetAspectTypeRequest", @@ -568,8 +582,11 @@ def _get_version(dependency_name): "MetadataFeed", "MetadataJob", "MetadataServiceClient", + "ModifyEntryRequest", "OperationMetadata", "Partition", + "RequestDataProductAccessRequest", + "RequestDataProductAccessResponse", "ResourceAccessSpec", "RunDataScanRequest", "RunDataScanResponse", diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_metadata.json b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_metadata.json index 4a154332e95f..26b61c2695b2 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_metadata.json +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/gapic_metadata.json @@ -404,6 +404,11 @@ "lookup_entry_links" ] }, + "ModifyEntry": { + "methods": [ + "modify_entry" + ] + }, "SearchEntries": { "methods": [ "search_entries" @@ -594,6 +599,11 @@ "lookup_entry_links" ] }, + "ModifyEntry": { + "methods": [ + "modify_entry" + ] + }, "SearchEntries": { "methods": [ "search_entries" @@ -784,6 +794,11 @@ "lookup_entry_links" ] }, + "ModifyEntry": { + "methods": [ + "modify_entry" + ] + }, "SearchEntries": { "methods": [ "search_entries" @@ -975,6 +990,11 @@ "list_data_products" ] }, + "RequestDataProductAccess": { + "methods": [ + "request_data_product_access" + ] + }, "UpdateDataAsset": { "methods": [ "update_data_asset" @@ -1030,6 +1050,11 @@ "list_data_products" ] }, + "RequestDataProductAccess": { + "methods": [ + "request_data_product_access" + ] + }, "UpdateDataAsset": { "methods": [ "update_data_asset" @@ -1085,6 +1110,11 @@ "list_data_products" ] }, + "RequestDataProductAccess": { + "methods": [ + "request_data_product_access" + ] + }, "UpdateDataAsset": { "methods": [ "update_data_asset" @@ -1104,6 +1134,11 @@ "grpc": { "libraryClient": "DataScanServiceClient", "rpcs": { + "CancelDataScanJob": { + "methods": [ + "cancel_data_scan_job" + ] + }, "CreateDataScan": { "methods": [ "create_data_scan" @@ -1154,6 +1189,11 @@ "grpc-async": { "libraryClient": "DataScanServiceAsyncClient", "rpcs": { + "CancelDataScanJob": { + "methods": [ + "cancel_data_scan_job" + ] + }, "CreateDataScan": { "methods": [ "create_data_scan" @@ -1204,6 +1244,11 @@ "rest": { "libraryClient": "DataScanServiceClient", "rpcs": { + "CancelDataScanJob": { + "methods": [ + "cancel_data_scan_job" + ] + }, "CreateDataScan": { "methods": [ "create_data_scan" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/base.py index 4216a7253f64..af583b8ac8cb 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/base.py @@ -46,7 +46,12 @@ class BusinessGlossaryServiceTransport(abc.ABC): """Abstract transport class for BusinessGlossaryService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/rest_base.py index 46d0b2f4cfd3..8238df97bca1 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/business_glossary_service/transports/rest_base.py @@ -944,10 +944,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -1008,6 +1004,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -1049,11 +1049,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -1129,6 +1124,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -1175,11 +1175,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -1255,6 +1250,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/async_client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/async_client.py index aa17b23f80af..c49a0d21ab94 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/async_client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/async_client.py @@ -2990,6 +2990,98 @@ async def sample_lookup_entry(): # Done; return the response. return response + async def modify_entry( + self, + request: Optional[Union[catalog.ModifyEntryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> catalog.Entry: + r"""Modifies an entry using the permission on the source + system. + + .. 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 dataplex_v1 + + async def sample_modify_entry(): + # Create a client + client = dataplex_v1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + entry = dataplex_v1.Entry() + entry.entry_type = "entry_type_value" + + request = dataplex_v1.ModifyEntryRequest( + name="name_value", + entry=entry, + ) + + # Make the request + response = await client.modify_entry(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dataplex_v1.types.ModifyEntryRequest, dict]]): + The request object. Modify Entry request using + permissions in the source system. + 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.dataplex_v1.types.Entry: + An entry is a representation of a + data resource that can be described by + various metadata. + + """ + # 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, catalog.ModifyEntryRequest): + request = catalog.ModifyEntryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.modify_entry + ] + + # 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 search_entries( self, request: Optional[Union[catalog.SearchEntriesRequest, dict]] = None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py index 84c0f1d84c42..19242147d331 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/client.py @@ -3510,6 +3510,96 @@ def sample_lookup_entry(): # Done; return the response. return response + def modify_entry( + self, + request: Optional[Union[catalog.ModifyEntryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> catalog.Entry: + r"""Modifies an entry using the permission on the source + system. + + .. 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 dataplex_v1 + + def sample_modify_entry(): + # Create a client + client = dataplex_v1.CatalogServiceClient() + + # Initialize request argument(s) + entry = dataplex_v1.Entry() + entry.entry_type = "entry_type_value" + + request = dataplex_v1.ModifyEntryRequest( + name="name_value", + entry=entry, + ) + + # Make the request + response = client.modify_entry(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dataplex_v1.types.ModifyEntryRequest, dict]): + The request object. Modify Entry request using + permissions in the source system. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.dataplex_v1.types.Entry: + An entry is a representation of a + data resource that can be described by + various metadata. + + """ + # 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, catalog.ModifyEntryRequest): + request = catalog.ModifyEntryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_entry] + + # 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 search_entries( self, request: Optional[Union[catalog.SearchEntriesRequest, dict]] = None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/base.py index b1f708382cf4..450d507ba3be 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/base.py @@ -359,6 +359,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=20.0, client_info=client_info, ), + self.modify_entry: gapic_v1.method.wrap_method( + self.modify_entry, + default_timeout=None, + client_info=client_info, + ), self.search_entries: gapic_v1.method.wrap_method( self.search_entries, default_retry=retries.Retry( @@ -396,22 +401,42 @@ def _prep_wrapped_messages(self, client_info): ), self.create_entry_link: gapic_v1.method.wrap_method( self.create_entry_link, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_entry_link: gapic_v1.method.wrap_method( self.update_entry_link, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.delete_entry_link: gapic_v1.method.wrap_method( self.delete_entry_link, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.lookup_entry_links: gapic_v1.method.wrap_method( self.lookup_entry_links, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, client_info=client_info, ), self.lookup_context: gapic_v1.method.wrap_method( @@ -421,7 +446,17 @@ def _prep_wrapped_messages(self, client_info): ), self.get_entry_link: gapic_v1.method.wrap_method( self.get_entry_link, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, client_info=client_info, ), self.create_metadata_feed: gapic_v1.method.wrap_method( @@ -700,6 +735,14 @@ def lookup_entry( ]: raise NotImplementedError() + @property + def modify_entry( + self, + ) -> Callable[ + [catalog.ModifyEntryRequest], Union[catalog.Entry, Awaitable[catalog.Entry]] + ]: + raise NotImplementedError() + @property def search_entries( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc.py index 4574583b549b..44067d83adc6 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc.py @@ -891,6 +891,31 @@ def lookup_entry(self) -> Callable[[catalog.LookupEntryRequest], catalog.Entry]: ) return self._stubs["lookup_entry"] + @property + def modify_entry(self) -> Callable[[catalog.ModifyEntryRequest], catalog.Entry]: + r"""Return a callable for the modify entry method over gRPC. + + Modifies an entry using the permission on the source + system. + + Returns: + Callable[[~.ModifyEntryRequest], + ~.Entry]: + 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 "modify_entry" not in self._stubs: + self._stubs["modify_entry"] = self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.CatalogService/ModifyEntry", + request_serializer=catalog.ModifyEntryRequest.serialize, + response_deserializer=catalog.Entry.deserialize, + ) + return self._stubs["modify_entry"] + @property def search_entries( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc_asyncio.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc_asyncio.py index 4c7ebe87658d..562e6909dbca 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/grpc_asyncio.py @@ -933,6 +933,33 @@ def lookup_entry( ) return self._stubs["lookup_entry"] + @property + def modify_entry( + self, + ) -> Callable[[catalog.ModifyEntryRequest], Awaitable[catalog.Entry]]: + r"""Return a callable for the modify entry method over gRPC. + + Modifies an entry using the permission on the source + system. + + Returns: + Callable[[~.ModifyEntryRequest], + Awaitable[~.Entry]]: + 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 "modify_entry" not in self._stubs: + self._stubs["modify_entry"] = self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.CatalogService/ModifyEntry", + request_serializer=catalog.ModifyEntryRequest.serialize, + response_deserializer=catalog.Entry.deserialize, + ) + return self._stubs["modify_entry"] + @property def search_entries( self, @@ -1584,6 +1611,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=20.0, client_info=client_info, ), + self.modify_entry: self._wrap_method( + self.modify_entry, + default_timeout=None, + client_info=client_info, + ), self.search_entries: self._wrap_method( self.search_entries, default_retry=retries.AsyncRetry( @@ -1621,22 +1653,42 @@ def _prep_wrapped_messages(self, client_info): ), self.create_entry_link: self._wrap_method( self.create_entry_link, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.update_entry_link: self._wrap_method( self.update_entry_link, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.delete_entry_link: self._wrap_method( self.delete_entry_link, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.lookup_entry_links: self._wrap_method( self.lookup_entry_links, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, client_info=client_info, ), self.lookup_context: self._wrap_method( @@ -1646,7 +1698,17 @@ def _prep_wrapped_messages(self, client_info): ), self.get_entry_link: self._wrap_method( self.get_entry_link, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=20.0, + ), + default_timeout=20.0, client_info=client_info, ), self.create_metadata_feed: self._wrap_method( diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest.py index 2d727adf1500..6e0cb55a7fd3 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest.py @@ -315,6 +315,14 @@ def post_lookup_entry_links(self, response): logging.log(f"Received response: {response}") return response + def pre_modify_entry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_modify_entry(self, response): + logging.log(f"Received response: {response}") + return response + def pre_search_entries(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1727,6 +1735,48 @@ def post_lookup_entry_links_with_metadata( """ return response, metadata + def pre_modify_entry( + self, + request: catalog.ModifyEntryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[catalog.ModifyEntryRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for modify_entry + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_modify_entry(self, response: catalog.Entry) -> catalog.Entry: + """Post-rpc interceptor for modify_entry + + DEPRECATED. Please use the `post_modify_entry_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. This `post_modify_entry` interceptor runs + before the `post_modify_entry_with_metadata` interceptor. + """ + return response + + def post_modify_entry_with_metadata( + self, response: catalog.Entry, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[catalog.Entry, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for modify_entry + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CatalogService server but before it is returned to user code. + + We recommend only using this `post_modify_entry_with_metadata` + interceptor in new development instead of the `post_modify_entry` interceptor. + When both interceptors are used, this `post_modify_entry_with_metadata` interceptor runs after the + `post_modify_entry` interceptor. The (possibly modified) response returned by + `post_modify_entry` will be passed to + `post_modify_entry_with_metadata`. + """ + return response, metadata + def pre_search_entries( self, request: catalog.SearchEntriesRequest, @@ -6833,6 +6883,160 @@ def __call__( ) return resp + class _ModifyEntry( + _BaseCatalogServiceRestTransport._BaseModifyEntry, CatalogServiceRestStub + ): + def __hash__(self): + return hash("CatalogServiceRestTransport.ModifyEntry") + + @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: catalog.ModifyEntryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> catalog.Entry: + r"""Call the modify entry method over HTTP. + + Args: + request (~.catalog.ModifyEntryRequest): + The request object. Modify Entry request using + permissions in the source system. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.catalog.Entry: + An entry is a representation of a + data resource that can be described by + various metadata. + + """ + + http_options = ( + _BaseCatalogServiceRestTransport._BaseModifyEntry._get_http_options() + ) + + request, metadata = self._interceptor.pre_modify_entry(request, metadata) + transcoded_request = _BaseCatalogServiceRestTransport._BaseModifyEntry._get_transcoded_request( + http_options, request + ) + + body = _BaseCatalogServiceRestTransport._BaseModifyEntry._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCatalogServiceRestTransport._BaseModifyEntry._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.dataplex_v1.CatalogServiceClient.ModifyEntry", + extra={ + "serviceName": "google.cloud.dataplex.v1.CatalogService", + "rpcName": "ModifyEntry", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CatalogServiceRestTransport._ModifyEntry._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 = catalog.Entry() + pb_resp = catalog.Entry.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_modify_entry(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_modify_entry_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = catalog.Entry.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.dataplex_v1.CatalogServiceClient.modify_entry", + extra={ + "serviceName": "google.cloud.dataplex.v1.CatalogService", + "rpcName": "ModifyEntry", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _SearchEntries( _BaseCatalogServiceRestTransport._BaseSearchEntries, CatalogServiceRestStub ): @@ -8122,6 +8326,12 @@ def lookup_entry_links( # In C++ this would require a dynamic_cast return self._LookupEntryLinks(self._session, self._host, self._interceptor) # type: ignore + @property + def modify_entry(self) -> Callable[[catalog.ModifyEntryRequest], catalog.Entry]: + # 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._ModifyEntry(self._session, self._host, self._interceptor) # type: ignore + @property def search_entries( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest_base.py index 60a3bce143ec..ce2992c3a911 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/catalog_service/transports/rest_base.py @@ -1608,6 +1608,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseModifyEntry: + 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": "/v1/{name=projects/*/locations/*}:modifyEntry", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = catalog.ModifyEntryRequest.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( + _BaseCatalogServiceRestTransport._BaseModifyEntry._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseSearchEntries: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -2078,10 +2135,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -2142,6 +2195,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -2183,11 +2240,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -2263,6 +2315,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -2309,11 +2366,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -2389,6 +2441,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/base.py index 85c2d1e13312..d0c9cc1c4af6 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/base.py @@ -45,7 +45,10 @@ class CmekServiceTransport(abc.ABC): """Abstract transport class for CmekService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/rest_base.py index 88e6db26cd4d..c8d65b4b3a74 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/cmek_service/transports/rest_base.py @@ -423,10 +423,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -487,6 +483,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -528,11 +528,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -608,6 +603,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -654,11 +654,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -734,6 +729,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/transports/rest_base.py index 22d15e2d5dae..c1d433d6f6ad 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/content_service/transports/rest_base.py @@ -164,10 +164,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -228,6 +224,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -269,11 +269,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -349,6 +344,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -395,11 +395,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -475,6 +470,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/async_client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/async_client.py index fa6f239b2585..96d94ab51266 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/async_client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/async_client.py @@ -57,7 +57,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.cloud.dataplex_v1.services.data_product_service import pagers -from google.cloud.dataplex_v1.types import data_products, service +from google.cloud.dataplex_v1.types import approval_workflow, data_products, service from .client import DataProductServiceClient from .transports.base import DEFAULT_CLIENT_INFO, DataProductServiceTransport @@ -87,12 +87,36 @@ class DataProductServiceAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = DataProductServiceClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = DataProductServiceClient._DEFAULT_UNIVERSE + change_request_path = staticmethod(DataProductServiceClient.change_request_path) + parse_change_request_path = staticmethod( + DataProductServiceClient.parse_change_request_path + ) data_asset_path = staticmethod(DataProductServiceClient.data_asset_path) parse_data_asset_path = staticmethod(DataProductServiceClient.parse_data_asset_path) data_product_path = staticmethod(DataProductServiceClient.data_product_path) parse_data_product_path = staticmethod( DataProductServiceClient.parse_data_product_path ) + entry_path = staticmethod(DataProductServiceClient.entry_path) + parse_entry_path = staticmethod(DataProductServiceClient.parse_entry_path) + entry_group_path = staticmethod(DataProductServiceClient.entry_group_path) + parse_entry_group_path = staticmethod( + DataProductServiceClient.parse_entry_group_path + ) + entry_link_path = staticmethod(DataProductServiceClient.entry_link_path) + parse_entry_link_path = staticmethod(DataProductServiceClient.parse_entry_link_path) + glossary_path = staticmethod(DataProductServiceClient.glossary_path) + parse_glossary_path = staticmethod(DataProductServiceClient.parse_glossary_path) + glossary_category_path = staticmethod( + DataProductServiceClient.glossary_category_path + ) + parse_glossary_category_path = staticmethod( + DataProductServiceClient.parse_glossary_category_path + ) + glossary_term_path = staticmethod(DataProductServiceClient.glossary_term_path) + parse_glossary_term_path = staticmethod( + DataProductServiceClient.parse_glossary_term_path + ) common_billing_account_path = staticmethod( DataProductServiceClient.common_billing_account_path ) @@ -1002,6 +1026,138 @@ async def sample_update_data_product(): # Done; return the response. return response + async def request_data_product_access( + self, + request: Optional[ + Union[data_products.RequestDataProductAccessRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + change_request: Optional[approval_workflow.ChangeRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_products.RequestDataProductAccessResponse: + r"""Requests access to a data product. This will trigger + an access approval workflow, and the requester will need + to wait for the approval to be granted before they will + be able to access the data product assets. + + .. 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 dataplex_v1 + + async def sample_request_data_product_access(): + # Create a client + client = dataplex_v1.DataProductServiceAsyncClient() + + # Initialize request argument(s) + change_request = dataplex_v1.ChangeRequest() + change_request.create_entry.parent = "parent_value" + change_request.create_entry.entry_id = "entry_id_value" + change_request.create_entry.entry.entry_type = "entry_type_value" + + request = dataplex_v1.RequestDataProductAccessRequest( + parent="parent_value", + change_request=change_request, + ) + + # Make the request + response = await client.request_data_product_access(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dataplex_v1.types.RequestDataProductAccessRequest, dict]]): + The request object. Message for requesting access to a + Data Product. + parent (:class:`str`): + Required. The resource name of the data product. Format: + projects/{project_number}/locations/{location_id}/dataProducts/{data_product_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + change_request (:class:`google.cloud.dataplex_v1.types.ChangeRequest`): + Required. The change request for the + data product access request. + + This corresponds to the ``change_request`` 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.dataplex_v1.types.RequestDataProductAccessResponse: + Response message for requesting + access to a Data Product. + + """ + # 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, change_request] + 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, data_products.RequestDataProductAccessRequest): + request = data_products.RequestDataProductAccessRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if change_request is not None: + request.change_request = change_request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.request_data_product_access + ] + + # 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 create_data_asset( self, request: Optional[Union[data_products.CreateDataAssetRequest, dict]] = None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/client.py index 49136905286d..2c993b92455e 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/client.py @@ -74,7 +74,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.cloud.dataplex_v1.services.data_product_service import pagers -from google.cloud.dataplex_v1.types import data_products, service +from google.cloud.dataplex_v1.types import approval_workflow, data_products, service from .transports.base import DEFAULT_CLIENT_INFO, DataProductServiceTransport from .transports.grpc import DataProductServiceGrpcTransport @@ -240,6 +240,28 @@ def transport(self) -> DataProductServiceTransport: """ return self._transport + @staticmethod + def change_request_path( + project: str, + location: str, + change_request: str, + ) -> str: + """Returns a fully-qualified change_request string.""" + return "projects/{project}/locations/{location}/changeRequests/{change_request}".format( + project=project, + location=location, + change_request=change_request, + ) + + @staticmethod + def parse_change_request_path(path: str) -> Dict[str, str]: + """Parses a change_request path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/changeRequests/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_asset_path( project: str, @@ -286,6 +308,148 @@ def parse_data_product_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def entry_path( + project: str, + location: str, + entry_group: str, + entry: str, + ) -> str: + """Returns a fully-qualified entry string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format( + project=project, + location=location, + entry_group=entry_group, + entry=entry, + ) + + @staticmethod + def parse_entry_path(path: str) -> Dict[str, str]: + """Parses a entry path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def entry_group_path( + project: str, + location: str, + entry_group: str, + ) -> str: + """Returns a fully-qualified entry_group string.""" + return ( + "projects/{project}/locations/{location}/entryGroups/{entry_group}".format( + project=project, + location=location, + entry_group=entry_group, + ) + ) + + @staticmethod + def parse_entry_group_path(path: str) -> Dict[str, str]: + """Parses a entry_group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def entry_link_path( + project: str, + location: str, + entry_group: str, + entry_link: str, + ) -> str: + """Returns a fully-qualified entry_link string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entryLinks/{entry_link}".format( + project=project, + location=location, + entry_group=entry_group, + entry_link=entry_link, + ) + + @staticmethod + def parse_entry_link_path(path: str) -> Dict[str, str]: + """Parses a entry_link path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entryLinks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def glossary_path( + project: str, + location: str, + glossary: str, + ) -> str: + """Returns a fully-qualified glossary string.""" + return "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, + location=location, + glossary=glossary, + ) + + @staticmethod + def parse_glossary_path(path: str) -> Dict[str, str]: + """Parses a glossary path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def glossary_category_path( + project: str, + location: str, + glossary: str, + glossary_category: str, + ) -> str: + """Returns a fully-qualified glossary_category string.""" + return "projects/{project}/locations/{location}/glossaries/{glossary}/categories/{glossary_category}".format( + project=project, + location=location, + glossary=glossary, + glossary_category=glossary_category, + ) + + @staticmethod + def parse_glossary_category_path(path: str) -> Dict[str, str]: + """Parses a glossary_category path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)/categories/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def glossary_term_path( + project: str, + location: str, + glossary: str, + glossary_term: str, + ) -> str: + """Returns a fully-qualified glossary_term string.""" + return "projects/{project}/locations/{location}/glossaries/{glossary}/terms/{glossary_term}".format( + project=project, + location=location, + glossary=glossary, + glossary_term=glossary_term, + ) + + @staticmethod + def parse_glossary_term_path(path: str) -> Dict[str, str]: + """Parses a glossary_term path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/glossaries/(?P.+?)/terms/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -1440,6 +1604,137 @@ def sample_update_data_product(): # Done; return the response. return response + def request_data_product_access( + self, + request: Optional[ + Union[data_products.RequestDataProductAccessRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + change_request: Optional[approval_workflow.ChangeRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_products.RequestDataProductAccessResponse: + r"""Requests access to a data product. This will trigger + an access approval workflow, and the requester will need + to wait for the approval to be granted before they will + be able to access the data product assets. + + .. 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 dataplex_v1 + + def sample_request_data_product_access(): + # Create a client + client = dataplex_v1.DataProductServiceClient() + + # Initialize request argument(s) + change_request = dataplex_v1.ChangeRequest() + change_request.create_entry.parent = "parent_value" + change_request.create_entry.entry_id = "entry_id_value" + change_request.create_entry.entry.entry_type = "entry_type_value" + + request = dataplex_v1.RequestDataProductAccessRequest( + parent="parent_value", + change_request=change_request, + ) + + # Make the request + response = client.request_data_product_access(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dataplex_v1.types.RequestDataProductAccessRequest, dict]): + The request object. Message for requesting access to a + Data Product. + parent (str): + Required. The resource name of the data product. Format: + projects/{project_number}/locations/{location_id}/dataProducts/{data_product_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + change_request (google.cloud.dataplex_v1.types.ChangeRequest): + Required. The change request for the + data product access request. + + This corresponds to the ``change_request`` 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.dataplex_v1.types.RequestDataProductAccessResponse: + Response message for requesting + access to a Data Product. + + """ + # 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, change_request] + 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, data_products.RequestDataProductAccessRequest): + request = data_products.RequestDataProductAccessRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if change_request is not None: + request.change_request = change_request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.request_data_product_access + ] + + # 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 create_data_asset( self, request: Optional[Union[data_products.CreateDataAssetRequest, dict]] = None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/base.py index 7ba5792c18e5..61df4fc228b6 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/base.py @@ -45,7 +45,12 @@ class DataProductServiceTransport(abc.ABC): """Abstract transport class for DataProductService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" @@ -173,6 +178,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.request_data_product_access: gapic_v1.method.wrap_method( + self.request_data_product_access, + default_timeout=None, + client_info=client_info, + ), self.create_data_asset: gapic_v1.method.wrap_method( self.create_data_asset, default_timeout=None, @@ -307,6 +317,18 @@ def update_data_product( ]: raise NotImplementedError() + @property + def request_data_product_access( + self, + ) -> Callable[ + [data_products.RequestDataProductAccessRequest], + Union[ + data_products.RequestDataProductAccessResponse, + Awaitable[data_products.RequestDataProductAccessResponse], + ], + ]: + raise NotImplementedError() + @property def create_data_asset( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc.py index efe36ce69556..b1c1883d7826 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc.py @@ -483,6 +483,40 @@ def update_data_product( ) return self._stubs["update_data_product"] + @property + def request_data_product_access( + self, + ) -> Callable[ + [data_products.RequestDataProductAccessRequest], + data_products.RequestDataProductAccessResponse, + ]: + r"""Return a callable for the request data product access method over gRPC. + + Requests access to a data product. This will trigger + an access approval workflow, and the requester will need + to wait for the approval to be granted before they will + be able to access the data product assets. + + Returns: + Callable[[~.RequestDataProductAccessRequest], + ~.RequestDataProductAccessResponse]: + 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 "request_data_product_access" not in self._stubs: + self._stubs["request_data_product_access"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.DataProductService/RequestDataProductAccess", + request_serializer=data_products.RequestDataProductAccessRequest.serialize, + response_deserializer=data_products.RequestDataProductAccessResponse.deserialize, + ) + ) + return self._stubs["request_data_product_access"] + @property def create_data_asset( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc_asyncio.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc_asyncio.py index 6376bda8e8ac..c2ea0972a9d7 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/grpc_asyncio.py @@ -500,6 +500,40 @@ def update_data_product( ) return self._stubs["update_data_product"] + @property + def request_data_product_access( + self, + ) -> Callable[ + [data_products.RequestDataProductAccessRequest], + Awaitable[data_products.RequestDataProductAccessResponse], + ]: + r"""Return a callable for the request data product access method over gRPC. + + Requests access to a data product. This will trigger + an access approval workflow, and the requester will need + to wait for the approval to be granted before they will + be able to access the data product assets. + + Returns: + Callable[[~.RequestDataProductAccessRequest], + Awaitable[~.RequestDataProductAccessResponse]]: + 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 "request_data_product_access" not in self._stubs: + self._stubs["request_data_product_access"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.DataProductService/RequestDataProductAccess", + request_serializer=data_products.RequestDataProductAccessRequest.serialize, + response_deserializer=data_products.RequestDataProductAccessResponse.deserialize, + ) + ) + return self._stubs["request_data_product_access"] + @property def create_data_asset( self, @@ -669,6 +703,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.request_data_product_access: self._wrap_method( + self.request_data_product_access, + default_timeout=None, + client_info=client_info, + ), self.create_data_asset: self._wrap_method( self.create_data_asset, default_timeout=None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest.py index 7f209f86bb02..dedfad27a1b6 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest.py @@ -142,6 +142,14 @@ def post_list_data_products(self, response): logging.log(f"Received response: {response}") return response + def pre_request_data_product_access(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_request_data_product_access(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_data_asset(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -552,6 +560,58 @@ def post_list_data_products_with_metadata( """ return response, metadata + def pre_request_data_product_access( + self, + request: data_products.RequestDataProductAccessRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_products.RequestDataProductAccessRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for request_data_product_access + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataProductService server. + """ + return request, metadata + + def post_request_data_product_access( + self, response: data_products.RequestDataProductAccessResponse + ) -> data_products.RequestDataProductAccessResponse: + """Post-rpc interceptor for request_data_product_access + + DEPRECATED. Please use the `post_request_data_product_access_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataProductService server but before + it is returned to user code. This `post_request_data_product_access` interceptor runs + before the `post_request_data_product_access_with_metadata` interceptor. + """ + return response + + def post_request_data_product_access_with_metadata( + self, + response: data_products.RequestDataProductAccessResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_products.RequestDataProductAccessResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for request_data_product_access + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataProductService server but before it is returned to user code. + + We recommend only using this `post_request_data_product_access_with_metadata` + interceptor in new development instead of the `post_request_data_product_access` interceptor. + When both interceptors are used, this `post_request_data_product_access_with_metadata` interceptor runs after the + `post_request_data_product_access` interceptor. The (possibly modified) response returned by + `post_request_data_product_access` will be passed to + `post_request_data_product_access_with_metadata`. + """ + return response, metadata + def pre_update_data_asset( self, request: data_products.UpdateDataAssetRequest, @@ -2230,6 +2290,165 @@ def __call__( ) return resp + class _RequestDataProductAccess( + _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess, + DataProductServiceRestStub, + ): + def __hash__(self): + return hash("DataProductServiceRestTransport.RequestDataProductAccess") + + @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_products.RequestDataProductAccessRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_products.RequestDataProductAccessResponse: + r"""Call the request data product + access method over HTTP. + + Args: + request (~.data_products.RequestDataProductAccessRequest): + The request object. Message for requesting access to a + Data Product. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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_products.RequestDataProductAccessResponse: + Response message for requesting + access to a Data Product. + + """ + + http_options = _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess._get_http_options() + + request, metadata = self._interceptor.pre_request_data_product_access( + request, metadata + ) + transcoded_request = _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess._get_transcoded_request( + http_options, request + ) + + body = _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess._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.dataplex_v1.DataProductServiceClient.RequestDataProductAccess", + extra={ + "serviceName": "google.cloud.dataplex.v1.DataProductService", + "rpcName": "RequestDataProductAccess", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataProductServiceRestTransport._RequestDataProductAccess._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_products.RequestDataProductAccessResponse() + pb_resp = data_products.RequestDataProductAccessResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_request_data_product_access(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_request_data_product_access_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + data_products.RequestDataProductAccessResponse.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.dataplex_v1.DataProductServiceClient.request_data_product_access", + extra={ + "serviceName": "google.cloud.dataplex.v1.DataProductService", + "rpcName": "RequestDataProductAccess", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateDataAsset( _BaseDataProductServiceRestTransport._BaseUpdateDataAsset, DataProductServiceRestStub, @@ -2604,6 +2823,19 @@ def list_data_products( # In C++ this would require a dynamic_cast return self._ListDataProducts(self._session, self._host, self._interceptor) # type: ignore + @property + def request_data_product_access( + self, + ) -> Callable[ + [data_products.RequestDataProductAccessRequest], + data_products.RequestDataProductAccessResponse, + ]: + # 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._RequestDataProductAccess( + self._session, self._host, self._interceptor + ) # type: ignore + @property def update_data_asset( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest_base.py index a59bde23f19a..a84707c5f433 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_product_service/transports/rest_base.py @@ -489,6 +489,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseRequestDataProductAccess: + 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": "/v1/{parent=projects/*/locations/*/dataProducts/*}:requestAccess", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = data_products.RequestDataProductAccessRequest.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( + _BaseDataProductServiceRestTransport._BaseRequestDataProductAccess._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateDataAsset: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -676,10 +733,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -740,6 +793,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -781,11 +838,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -861,6 +913,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -907,11 +964,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -987,6 +1039,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/async_client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/async_client.py index c30cce1a95d4..441bf4884909 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/async_client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/async_client.py @@ -110,6 +110,8 @@ class DataScanServiceAsyncClient: parse_dataset_path = staticmethod(DataScanServiceClient.parse_dataset_path) entity_path = staticmethod(DataScanServiceClient.entity_path) parse_entity_path = staticmethod(DataScanServiceClient.parse_entity_path) + entry_path = staticmethod(DataScanServiceClient.entry_path) + parse_entry_path = staticmethod(DataScanServiceClient.parse_entry_path) common_billing_account_path = staticmethod( DataScanServiceClient.common_billing_account_path ) @@ -365,7 +367,6 @@ async def sample_create_data_scan(): request = dataplex_v1.CreateDataScanRequest( parent="parent_value", data_scan=data_scan, - data_scan_id="data_scan_id_value", ) # Make the request @@ -396,7 +397,8 @@ async def sample_create_data_scan(): on the ``request`` instance; if ``request`` is provided, this should not be set. data_scan_id (:class:`str`): - Required. DataScan identifier. + Optional. DataScan identifier. If not provided, a unique + ID will be generated with the prefix "data-scan-". - Must contain only lowercase letters, numbers and hyphens. @@ -441,12 +443,14 @@ async def sample_create_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -604,12 +608,14 @@ async def sample_update_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -889,12 +895,14 @@ async def sample_get_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -1427,6 +1435,117 @@ async def sample_list_data_scan_jobs(): # Done; return the response. return response + async def cancel_data_scan_job( + self, + request: Optional[Union[datascans.CancelDataScanJobRequest, 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]]] = (), + ) -> datascans.CancelDataScanJobResponse: + r"""Cancels a running/pending DataScan job. + + .. 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 dataplex_v1 + + async def sample_cancel_data_scan_job(): + # Create a client + client = dataplex_v1.DataScanServiceAsyncClient() + + # Initialize request argument(s) + request = dataplex_v1.CancelDataScanJobRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_data_scan_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dataplex_v1.types.CancelDataScanJobRequest, dict]]): + The request object. Request message for the ``CancelDataScanJob`` method. + name (:class:`str`): + Required. The resource name of the DataScanJob: + ``projects/{project_id_or_number}/locations/{location_id}/dataScans/{data_scan_id}/jobs/{data_scan_job_id}`` + where ``project_id_or_number`` refers to a *project_id* + or *project_number* and ``location_id`` refers to a + Google Cloud region. + + 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.dataplex_v1.types.CancelDataScanJobResponse: + Response message for the CancelDataScanJob method. + """ + # 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, datascans.CancelDataScanJobRequest): + request = datascans.CancelDataScanJobRequest(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.cancel_data_scan_job + ] + + # 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 generate_data_quality_rules( self, request: Optional[ diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py index 4e2f0ab8f8de..8446275af689 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/client.py @@ -364,6 +364,30 @@ def parse_entity_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def entry_path( + project: str, + location: str, + entry_group: str, + entry: str, + ) -> str: + """Returns a fully-qualified entry string.""" + return "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format( + project=project, + location=location, + entry_group=entry_group, + entry=entry, + ) + + @staticmethod + def parse_entry_path(path: str) -> Dict[str, str]: + """Parses a entry path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/entryGroups/(?P.+?)/entries/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -880,7 +904,6 @@ def sample_create_data_scan(): request = dataplex_v1.CreateDataScanRequest( parent="parent_value", data_scan=data_scan, - data_scan_id="data_scan_id_value", ) # Make the request @@ -911,7 +934,8 @@ def sample_create_data_scan(): on the ``request`` instance; if ``request`` is provided, this should not be set. data_scan_id (str): - Required. DataScan identifier. + Optional. DataScan identifier. If not provided, a unique + ID will be generated with the prefix "data-scan-". - Must contain only lowercase letters, numbers and hyphens. @@ -956,12 +980,14 @@ def sample_create_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -1116,12 +1142,14 @@ def sample_update_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -1395,12 +1423,14 @@ def sample_get_data_scan(): information, see [Discover and catalog Cloud Storage data](https://cloud.google.com/bigquery/docs/automatic-discovery). - - \* Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - [Generate data insights in - BigQuery](https://cloud.google.com/bigquery/docs/data-insights). + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, + insights include descriptions and sample SQL + queries. For datasets, insights include + descriptions, schema relationships and sample SQL + queries. For more information, see [Generate data + insights in + BigQuery](https://cloud.google.com/bigquery/docs/data-insights). """ # Create or coerce a protobuf request object. @@ -1918,6 +1948,114 @@ def sample_list_data_scan_jobs(): # Done; return the response. return response + def cancel_data_scan_job( + self, + request: Optional[Union[datascans.CancelDataScanJobRequest, 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]]] = (), + ) -> datascans.CancelDataScanJobResponse: + r"""Cancels a running/pending DataScan job. + + .. 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 dataplex_v1 + + def sample_cancel_data_scan_job(): + # Create a client + client = dataplex_v1.DataScanServiceClient() + + # Initialize request argument(s) + request = dataplex_v1.CancelDataScanJobRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_data_scan_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dataplex_v1.types.CancelDataScanJobRequest, dict]): + The request object. Request message for the ``CancelDataScanJob`` method. + name (str): + Required. The resource name of the DataScanJob: + ``projects/{project_id_or_number}/locations/{location_id}/dataScans/{data_scan_id}/jobs/{data_scan_job_id}`` + where ``project_id_or_number`` refers to a *project_id* + or *project_number* and ``location_id`` refers to a + Google Cloud region. + + 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.dataplex_v1.types.CancelDataScanJobResponse: + Response message for the CancelDataScanJob method. + """ + # 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, datascans.CancelDataScanJobRequest): + request = datascans.CancelDataScanJobRequest(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.cancel_data_scan_job] + + # 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 generate_data_quality_rules( self, request: Optional[ diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/base.py index 0db92ccbb2b6..8e02d9bf2856 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/base.py @@ -45,7 +45,12 @@ class DataScanServiceTransport(abc.ABC): """Abstract transport class for DataScanService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" @@ -188,6 +193,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.cancel_data_scan_job: gapic_v1.method.wrap_method( + self.cancel_data_scan_job, + default_timeout=None, + client_info=client_info, + ), self.generate_data_quality_rules: gapic_v1.method.wrap_method( self.generate_data_quality_rules, default_timeout=None, @@ -331,6 +341,18 @@ def list_data_scan_jobs( ]: raise NotImplementedError() + @property + def cancel_data_scan_job( + self, + ) -> Callable[ + [datascans.CancelDataScanJobRequest], + Union[ + datascans.CancelDataScanJobResponse, + Awaitable[datascans.CancelDataScanJobResponse], + ], + ]: + raise NotImplementedError() + @property def generate_data_quality_rules( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc.py index c652d563dd79..76ef15b4cb1a 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc.py @@ -561,6 +561,34 @@ def list_data_scan_jobs( ) return self._stubs["list_data_scan_jobs"] + @property + def cancel_data_scan_job( + self, + ) -> Callable[ + [datascans.CancelDataScanJobRequest], datascans.CancelDataScanJobResponse + ]: + r"""Return a callable for the cancel data scan job method over gRPC. + + Cancels a running/pending DataScan job. + + Returns: + Callable[[~.CancelDataScanJobRequest], + ~.CancelDataScanJobResponse]: + 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 "cancel_data_scan_job" not in self._stubs: + self._stubs["cancel_data_scan_job"] = self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.DataScanService/CancelDataScanJob", + request_serializer=datascans.CancelDataScanJobRequest.serialize, + response_deserializer=datascans.CancelDataScanJobResponse.deserialize, + ) + return self._stubs["cancel_data_scan_job"] + @property def generate_data_quality_rules( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc_asyncio.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc_asyncio.py index 0a31b1d5fc6d..d2dbc3e19ccf 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/grpc_asyncio.py @@ -580,6 +580,35 @@ def list_data_scan_jobs( ) return self._stubs["list_data_scan_jobs"] + @property + def cancel_data_scan_job( + self, + ) -> Callable[ + [datascans.CancelDataScanJobRequest], + Awaitable[datascans.CancelDataScanJobResponse], + ]: + r"""Return a callable for the cancel data scan job method over gRPC. + + Cancels a running/pending DataScan job. + + Returns: + Callable[[~.CancelDataScanJobRequest], + Awaitable[~.CancelDataScanJobResponse]]: + 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 "cancel_data_scan_job" not in self._stubs: + self._stubs["cancel_data_scan_job"] = self._logged_channel.unary_unary( + "/google.cloud.dataplex.v1.DataScanService/CancelDataScanJob", + request_serializer=datascans.CancelDataScanJobRequest.serialize, + response_deserializer=datascans.CancelDataScanJobResponse.deserialize, + ) + return self._stubs["cancel_data_scan_job"] + @property def generate_data_quality_rules( self, @@ -658,6 +687,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.cancel_data_scan_job: self._wrap_method( + self.cancel_data_scan_job, + default_timeout=None, + client_info=client_info, + ), self.generate_data_quality_rules: self._wrap_method( self.generate_data_quality_rules, default_timeout=None, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest.py index ad6a9b22dd64..59eacec37602 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest.py @@ -78,6 +78,14 @@ class DataScanServiceRestInterceptor: .. code-block:: python class MyCustomDataScanServiceInterceptor(DataScanServiceRestInterceptor): + def pre_cancel_data_scan_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_data_scan_job(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_data_scan(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -156,6 +164,56 @@ def post_update_data_scan(self, response): """ + def pre_cancel_data_scan_job( + self, + request: datascans.CancelDataScanJobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datascans.CancelDataScanJobRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_data_scan_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataScanService server. + """ + return request, metadata + + def post_cancel_data_scan_job( + self, response: datascans.CancelDataScanJobResponse + ) -> datascans.CancelDataScanJobResponse: + """Post-rpc interceptor for cancel_data_scan_job + + DEPRECATED. Please use the `post_cancel_data_scan_job_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataScanService server but before + it is returned to user code. This `post_cancel_data_scan_job` interceptor runs + before the `post_cancel_data_scan_job_with_metadata` interceptor. + """ + return response + + def post_cancel_data_scan_job_with_metadata( + self, + response: datascans.CancelDataScanJobResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + datascans.CancelDataScanJobResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for cancel_data_scan_job + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataScanService server but before it is returned to user code. + + We recommend only using this `post_cancel_data_scan_job_with_metadata` + interceptor in new development instead of the `post_cancel_data_scan_job` interceptor. + When both interceptors are used, this `post_cancel_data_scan_job_with_metadata` interceptor runs after the + `post_cancel_data_scan_job` interceptor. The (possibly modified) response returned by + `post_cancel_data_scan_job` will be passed to + `post_cancel_data_scan_job_with_metadata`. + """ + return response, metadata + def pre_create_data_scan( self, request: datascans.CreateDataScanRequest, @@ -974,6 +1032,159 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client + class _CancelDataScanJob( + _BaseDataScanServiceRestTransport._BaseCancelDataScanJob, + DataScanServiceRestStub, + ): + def __hash__(self): + return hash("DataScanServiceRestTransport.CancelDataScanJob") + + @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: datascans.CancelDataScanJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datascans.CancelDataScanJobResponse: + r"""Call the cancel data scan job method over HTTP. + + Args: + request (~.datascans.CancelDataScanJobRequest): + The request object. Request message for the ``CancelDataScanJob`` 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: + ~.datascans.CancelDataScanJobResponse: + Response message for the ``CancelDataScanJob`` method. + """ + + http_options = _BaseDataScanServiceRestTransport._BaseCancelDataScanJob._get_http_options() + + request, metadata = self._interceptor.pre_cancel_data_scan_job( + request, metadata + ) + transcoded_request = _BaseDataScanServiceRestTransport._BaseCancelDataScanJob._get_transcoded_request( + http_options, request + ) + + body = _BaseDataScanServiceRestTransport._BaseCancelDataScanJob._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseDataScanServiceRestTransport._BaseCancelDataScanJob._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.dataplex_v1.DataScanServiceClient.CancelDataScanJob", + extra={ + "serviceName": "google.cloud.dataplex.v1.DataScanService", + "rpcName": "CancelDataScanJob", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataScanServiceRestTransport._CancelDataScanJob._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 = datascans.CancelDataScanJobResponse() + pb_resp = datascans.CancelDataScanJobResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel_data_scan_job(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_data_scan_job_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datascans.CancelDataScanJobResponse.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.dataplex_v1.DataScanServiceClient.cancel_data_scan_job", + extra={ + "serviceName": "google.cloud.dataplex.v1.DataScanService", + "rpcName": "CancelDataScanJob", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateDataScan( _BaseDataScanServiceRestTransport._BaseCreateDataScan, DataScanServiceRestStub ): @@ -1499,10 +1710,12 @@ def __call__( extract and then catalog metadata. For more information, see `Discover and catalog Cloud Storage data `__. - - Data documentation: analyzes the table details and - generates insights including descriptions and sample - SQL queries for the table. For more information, see - `Generate data insights in + - Data documentation: analyzes the table or dataset + metadata and generates insights. For tables, insights + include descriptions and sample SQL queries. For + datasets, insights include descriptions, schema + relationships and sample SQL queries. For more + information, see `Generate data insights in BigQuery `__. """ @@ -2334,6 +2547,16 @@ def __call__( ) return resp + @property + def cancel_data_scan_job( + self, + ) -> Callable[ + [datascans.CancelDataScanJobRequest], datascans.CancelDataScanJobResponse + ]: + # 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._CancelDataScanJob(self._session, self._host, self._interceptor) # type: ignore + @property def create_data_scan( self, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest_base.py index 9e3391001662..ad30318faf1c 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_scan_service/transports/rest_base.py @@ -93,13 +93,68 @@ def __init__( api_audience=api_audience, ) + class _BaseCancelDataScanJob: + 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": "/v1/{name=projects/*/locations/*/dataScans/*/jobs/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = datascans.CancelDataScanJobRequest.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( + _BaseDataScanServiceRestTransport._BaseCancelDataScanJob._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateDataScan: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "dataScanId": "", - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -636,10 +691,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -700,6 +751,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -741,11 +796,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -821,6 +871,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -867,11 +922,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -947,6 +997,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/base.py index fe281d2b4406..58f9a8376aa2 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/base.py @@ -46,7 +46,10 @@ class DataTaxonomyServiceTransport(abc.ABC): """Abstract transport class for DataTaxonomyService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/rest_base.py index 42891eccb5ee..311a83444111 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/data_taxonomy_service/transports/rest_base.py @@ -946,10 +946,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -1010,6 +1006,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -1051,11 +1051,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -1131,6 +1126,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -1177,11 +1177,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -1257,6 +1252,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/base.py index 57d316a72217..318ae57ade09 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/base.py @@ -46,7 +46,12 @@ class DataplexServiceTransport(abc.ABC): """Abstract transport class for DataplexService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/rest_base.py index 1081adcd4142..41dfcc284283 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/dataplex_service/transports/rest_base.py @@ -1552,10 +1552,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -1616,6 +1612,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -1657,11 +1657,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -1737,6 +1732,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -1783,11 +1783,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -1863,6 +1858,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/base.py index d9fb92c908fa..7bf04f50ca3b 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/base.py @@ -46,7 +46,10 @@ class MetadataServiceTransport(abc.ABC): """Abstract transport class for MetadataService.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ) DEFAULT_HOST: str = "dataplex.googleapis.com" diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/rest_base.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/rest_base.py index 7aa29b0833aa..6e21748f8e5a 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/rest_base.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/services/metadata_service/transports/rest_base.py @@ -624,10 +624,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:getIamPolicy", @@ -688,6 +684,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=organizations/*/locations/*/encryptionConfigs/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:getIamPolicy", + }, ] return http_options @@ -729,11 +729,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:setIamPolicy", @@ -809,6 +804,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:setIamPolicy", + "body": "*", + }, ] return http_options @@ -855,11 +855,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/lakes/*/tasks/*}:testIamPermissions", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/lakes/*/environments/*}:testIamPermissions", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/dataScans/*}:testIamPermissions", @@ -935,6 +930,11 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/dataProducts/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/dataDomains/*}:testIamPermissions", + "body": "*", + }, ] return http_options diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/__init__.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/__init__.py index b1f0ec01641a..8ef0c6717e00 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/__init__.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/__init__.py @@ -18,6 +18,10 @@ Environment, Session, ) +from .approval_workflow import ( + ChangeRequest, + DataProductAccessRequest, +) from .business_glossary import ( CreateGlossaryCategoryRequest, CreateGlossaryRequest, @@ -92,6 +96,7 @@ LookupEntryRequest, MetadataFeed, MetadataJob, + ModifyEntryRequest, SearchEntriesRequest, SearchEntriesResponse, SearchEntriesResult, @@ -133,6 +138,8 @@ ListDataAssetsResponse, ListDataProductsRequest, ListDataProductsResponse, + RequestDataProductAccessRequest, + RequestDataProductAccessResponse, UpdateDataAssetRequest, UpdateDataProductRequest, ) @@ -149,6 +156,9 @@ DataQualityRuleResult, DataQualitySpec, ) +from .data_quality_rule_template import ( + DataQualityRuleTemplate, +) from .data_taxonomy import ( CreateDataAttributeBindingRequest, CreateDataAttributeRequest, @@ -173,11 +183,14 @@ UpdateDataTaxonomyRequest, ) from .datascans import ( + CancelDataScanJobRequest, + CancelDataScanJobResponse, CreateDataScanRequest, DataScan, DataScanJob, DataScanType, DeleteDataScanRequest, + ExecutionIdentity, GenerateDataQualityRulesRequest, GenerateDataQualityRulesResponse, GetDataScanJobRequest, @@ -285,6 +298,8 @@ "Content", "Environment", "Session", + "ChangeRequest", + "DataProductAccessRequest", "CreateGlossaryCategoryRequest", "CreateGlossaryRequest", "CreateGlossaryTermRequest", @@ -355,6 +370,7 @@ "LookupEntryRequest", "MetadataFeed", "MetadataJob", + "ModifyEntryRequest", "SearchEntriesRequest", "SearchEntriesResponse", "SearchEntriesResult", @@ -389,6 +405,8 @@ "ListDataAssetsResponse", "ListDataProductsRequest", "ListDataProductsResponse", + "RequestDataProductAccessRequest", + "RequestDataProductAccessResponse", "UpdateDataAssetRequest", "UpdateDataProductRequest", "DataProfileResult", @@ -400,6 +418,7 @@ "DataQualityRule", "DataQualityRuleResult", "DataQualitySpec", + "DataQualityRuleTemplate", "CreateDataAttributeBindingRequest", "CreateDataAttributeRequest", "CreateDataTaxonomyRequest", @@ -421,10 +440,13 @@ "UpdateDataAttributeBindingRequest", "UpdateDataAttributeRequest", "UpdateDataTaxonomyRequest", + "CancelDataScanJobRequest", + "CancelDataScanJobResponse", "CreateDataScanRequest", "DataScan", "DataScanJob", "DeleteDataScanRequest", + "ExecutionIdentity", "GenerateDataQualityRulesRequest", "GenerateDataQualityRulesResponse", "GetDataScanJobRequest", diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/approval_workflow.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/approval_workflow.py new file mode 100644 index 000000000000..03fb04e4ddba --- /dev/null +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/approval_workflow.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.dataplex_v1.types import business_glossary, catalog + +__protobuf__ = proto.module( + package="google.cloud.dataplex.v1", + manifest={ + "ChangeRequest", + "DataProductAccessRequest", + }, +) + + +class ChangeRequest(proto.Message): + r"""Represents a proposed change to a metadata resource. + + 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): + Identifier. The relative resource name of the ChangeRequest, + of the form: + projects/{project_number}/locations/{location_id}/changeRequests/{change_request_id} + uid (str): + Output only. System generated globally unique + ID for the ChangeRequest. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ChangeRequest + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the ChangeRequest + was last updated. + justification (str): + Optional. Justification of the ChangeRequest. This should + explain *why* the change is needed or why it should be + approved. + labels (MutableMapping[str, str]): + Optional. User-defined labels for the + ChangeRequest. + author (str): + Output only. The email address of the user + who created the ChangeRequest. + state (google.cloud.dataplex_v1.types.ChangeRequest.State): + Output only. The current state of the + ChangeRequest. + resource (str): + Output only. The full resource name of the + target resource to be modified. Example: + + //dataplex.googleapis.com/projects/my-project/locations/us-central1/entryGroups/my-group/entries/my-entry + create_entry (google.cloud.dataplex_v1.types.CreateEntryRequest): + Payload for creating an Entry. + + This field is a member of `oneof`_ ``change_payload``. + update_entry (google.cloud.dataplex_v1.types.UpdateEntryRequest): + Payload for updating an Entry. + + This field is a member of `oneof`_ ``change_payload``. + delete_entry (google.cloud.dataplex_v1.types.DeleteEntryRequest): + Payload for deleting an Entry. + + This field is a member of `oneof`_ ``change_payload``. + create_entry_link (google.cloud.dataplex_v1.types.CreateEntryLinkRequest): + Payload for creating an EntryLink. + + This field is a member of `oneof`_ ``change_payload``. + delete_entry_link (google.cloud.dataplex_v1.types.DeleteEntryLinkRequest): + Payload for deleting an EntryLink. + + This field is a member of `oneof`_ ``change_payload``. + create_glossary (google.cloud.dataplex_v1.types.CreateGlossaryRequest): + Payload for creating a Glossary. + + This field is a member of `oneof`_ ``change_payload``. + update_glossary (google.cloud.dataplex_v1.types.UpdateGlossaryRequest): + Payload for updating a Glossary. + + This field is a member of `oneof`_ ``change_payload``. + delete_glossary (google.cloud.dataplex_v1.types.DeleteGlossaryRequest): + Payload for deleting a Glossary. + + This field is a member of `oneof`_ ``change_payload``. + create_glossary_category (google.cloud.dataplex_v1.types.CreateGlossaryCategoryRequest): + Payload for creating a GlossaryCategory. + + This field is a member of `oneof`_ ``change_payload``. + update_glossary_category (google.cloud.dataplex_v1.types.UpdateGlossaryCategoryRequest): + Payload for updating a GlossaryCategory. + + This field is a member of `oneof`_ ``change_payload``. + delete_glossary_category (google.cloud.dataplex_v1.types.DeleteGlossaryCategoryRequest): + Payload for deleting a GlossaryCategory. + + This field is a member of `oneof`_ ``change_payload``. + create_glossary_term (google.cloud.dataplex_v1.types.CreateGlossaryTermRequest): + Payload for creating a GlossaryTerm. + + This field is a member of `oneof`_ ``change_payload``. + update_glossary_term (google.cloud.dataplex_v1.types.UpdateGlossaryTermRequest): + Payload for updating a GlossaryTerm. + + This field is a member of `oneof`_ ``change_payload``. + delete_glossary_term (google.cloud.dataplex_v1.types.DeleteGlossaryTermRequest): + Payload for deleting a GlossaryTerm. + + This field is a member of `oneof`_ ``change_payload``. + data_product_access_request (google.cloud.dataplex_v1.types.DataProductAccessRequest): + Payload for Data Product access request. + + This field is a member of `oneof`_ ``change_payload``. + change_type (google.cloud.dataplex_v1.types.ChangeRequest.ChangeType): + Output only. The type of change represented by the + change_payload. This field is derived from the populated + field in the change_payload oneof. + rejection_comment (str): + Output only. The reason provided for + rejecting the ChangeRequest. + approver (str): + Output only. The email address of the user + who approved/rejected the ChangeRequest. + etag (str): + Optional. This checksum is computed by the + service. It can be sent on update and delete + requests to ensure the client has an up-to-date + value before proceeding. + """ + + class State(proto.Enum): + r"""Possible states of a ChangeRequest. + + Values: + STATE_UNSPECIFIED (0): + State unspecified. + NEW (1): + The change is proposed and new. + APPROVED (2): + The change has been approved. + REJECTED (3): + The change has been rejected. + EXPIRED (4): + The change request has expired. + REVOKED (5): + The approved change has been revoked. + """ + + STATE_UNSPECIFIED = 0 + NEW = 1 + APPROVED = 2 + REJECTED = 3 + EXPIRED = 4 + REVOKED = 5 + + class ChangeType(proto.Enum): + r"""Enum representing the type of change in the payload. + + Values: + CHANGE_TYPE_UNSPECIFIED (0): + State unspecified. + CREATE_ENTRY (1): + Request to create an Entry. + UPDATE_ENTRY (2): + Request to update an Entry. + DELETE_ENTRY (3): + Request to delete an Entry. + CREATE_ENTRY_LINK (4): + Request to create an EntryLink. + DELETE_ENTRY_LINK (5): + Request to delete an EntryLink. + CREATE_GLOSSARY (7): + Request to create a Glossary. + UPDATE_GLOSSARY (8): + Request to update a Glossary. + DELETE_GLOSSARY (9): + Request to delete a Glossary. + CREATE_GLOSSARY_CATEGORY (10): + Request to create a GlossaryCategory. + UPDATE_GLOSSARY_CATEGORY (11): + Request to update a GlossaryCategory. + DELETE_GLOSSARY_CATEGORY (13): + Request to delete a GlossaryCategory. + CREATE_GLOSSARY_TERM (14): + Request to create a GlossaryTerm. + UPDATE_GLOSSARY_TERM (15): + Request to update a GlossaryTerm. + DELETE_GLOSSARY_TERM (17): + Request to delete a GlossaryTerm. + REQUEST_DATA_PRODUCT_ACCESS (33): + Request to request Data Product access. + """ + + CHANGE_TYPE_UNSPECIFIED = 0 + CREATE_ENTRY = 1 + UPDATE_ENTRY = 2 + DELETE_ENTRY = 3 + CREATE_ENTRY_LINK = 4 + DELETE_ENTRY_LINK = 5 + CREATE_GLOSSARY = 7 + UPDATE_GLOSSARY = 8 + DELETE_GLOSSARY = 9 + CREATE_GLOSSARY_CATEGORY = 10 + UPDATE_GLOSSARY_CATEGORY = 11 + DELETE_GLOSSARY_CATEGORY = 13 + CREATE_GLOSSARY_TERM = 14 + UPDATE_GLOSSARY_TERM = 15 + DELETE_GLOSSARY_TERM = 17 + REQUEST_DATA_PRODUCT_ACCESS = 33 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + justification: str = proto.Field( + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + author: str = proto.Field( + proto.STRING, + number=7, + ) + state: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + resource: str = proto.Field( + proto.STRING, + number=9, + ) + create_entry: catalog.CreateEntryRequest = proto.Field( + proto.MESSAGE, + number=10, + oneof="change_payload", + message=catalog.CreateEntryRequest, + ) + update_entry: catalog.UpdateEntryRequest = proto.Field( + proto.MESSAGE, + number=11, + oneof="change_payload", + message=catalog.UpdateEntryRequest, + ) + delete_entry: catalog.DeleteEntryRequest = proto.Field( + proto.MESSAGE, + number=12, + oneof="change_payload", + message=catalog.DeleteEntryRequest, + ) + create_entry_link: catalog.CreateEntryLinkRequest = proto.Field( + proto.MESSAGE, + number=13, + oneof="change_payload", + message=catalog.CreateEntryLinkRequest, + ) + delete_entry_link: catalog.DeleteEntryLinkRequest = proto.Field( + proto.MESSAGE, + number=14, + oneof="change_payload", + message=catalog.DeleteEntryLinkRequest, + ) + create_glossary: business_glossary.CreateGlossaryRequest = proto.Field( + proto.MESSAGE, + number=20, + oneof="change_payload", + message=business_glossary.CreateGlossaryRequest, + ) + update_glossary: business_glossary.UpdateGlossaryRequest = proto.Field( + proto.MESSAGE, + number=21, + oneof="change_payload", + message=business_glossary.UpdateGlossaryRequest, + ) + delete_glossary: business_glossary.DeleteGlossaryRequest = proto.Field( + proto.MESSAGE, + number=22, + oneof="change_payload", + message=business_glossary.DeleteGlossaryRequest, + ) + create_glossary_category: business_glossary.CreateGlossaryCategoryRequest = ( + proto.Field( + proto.MESSAGE, + number=23, + oneof="change_payload", + message=business_glossary.CreateGlossaryCategoryRequest, + ) + ) + update_glossary_category: business_glossary.UpdateGlossaryCategoryRequest = ( + proto.Field( + proto.MESSAGE, + number=24, + oneof="change_payload", + message=business_glossary.UpdateGlossaryCategoryRequest, + ) + ) + delete_glossary_category: business_glossary.DeleteGlossaryCategoryRequest = ( + proto.Field( + proto.MESSAGE, + number=26, + oneof="change_payload", + message=business_glossary.DeleteGlossaryCategoryRequest, + ) + ) + create_glossary_term: business_glossary.CreateGlossaryTermRequest = proto.Field( + proto.MESSAGE, + number=27, + oneof="change_payload", + message=business_glossary.CreateGlossaryTermRequest, + ) + update_glossary_term: business_glossary.UpdateGlossaryTermRequest = proto.Field( + proto.MESSAGE, + number=28, + oneof="change_payload", + message=business_glossary.UpdateGlossaryTermRequest, + ) + delete_glossary_term: business_glossary.DeleteGlossaryTermRequest = proto.Field( + proto.MESSAGE, + number=30, + oneof="change_payload", + message=business_glossary.DeleteGlossaryTermRequest, + ) + data_product_access_request: "DataProductAccessRequest" = proto.Field( + proto.MESSAGE, + number=32, + oneof="change_payload", + message="DataProductAccessRequest", + ) + change_type: ChangeType = proto.Field( + proto.ENUM, + number=19, + enum=ChangeType, + ) + rejection_comment: str = proto.Field( + proto.STRING, + number=16, + ) + approver: str = proto.Field( + proto.STRING, + number=17, + ) + etag: str = proto.Field( + proto.STRING, + number=18, + ) + + +class DataProductAccessRequest(proto.Message): + r"""Message for requesting access to a Data Product. This will be used + to create a ChangeRequest of type REQUEST_DATA_PRODUCT_ACCESS. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The resource name of the data product. Format: + projects/{project_number}/locations/{location_id}/dataProducts/{data_product_id} + access_group_id (str): + Required. The ID of the access group for + which access is being requested. This + corresponds to the unique identifier of the + AccessGroup defined in the Data Product. + access_group_display_name (str): + Output only. The display name of the access + group defined in the Data Product for which + access is being requested. + requested_principal (str): + Optional. The principal for which access is being requested + in IAM format. If not specified, the requestor's principal + will be used. Example: + ``serviceAccount:my-sa@my-project.iam.gserviceaccount.com``. + Only service account principals are currently supported. + https://cloud.google.com/iam/docs/principal-identifiers + + This field is a member of `oneof`_ ``_requested_principal``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + access_group_id: str = proto.Field( + proto.STRING, + number=2, + ) + access_group_display_name: str = proto.Field( + proto.STRING, + number=4, + ) + requested_principal: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/catalog.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/catalog.py index 76e91398533e..3ffa5406d94c 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/catalog.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/catalog.py @@ -60,6 +60,7 @@ "GetEntryRequest", "LookupEntryRequest", "LookupContextRequest", + "ModifyEntryRequest", "LookupContextResponse", "SearchEntriesRequest", "SearchEntriesResult", @@ -726,7 +727,8 @@ class Authorization(proto.Message): class Aspect(proto.Message): - r"""An aspect is a single piece of metadata describing an entry. + r"""Represents a single piece of metadata describing an entry or + entry link. Attributes: aspect_type (str): @@ -1822,8 +1824,10 @@ class GetEntryRequest(proto.Message): Required. The resource name of the Entry: ``projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}``. view (google.cloud.dataplex_v1.types.EntryView): - Optional. View to control which parts of an - entry the service should return. + Optional. View to control which parts of an entry the + service should return. **Please check the limitations on + returned aspects in the Entry view documentation. Amount of + returned aspects depends on the selected Entry View.** aspect_types (MutableSequence[str]): Optional. Limits the aspects returned to the provided aspect types. It only works for CUSTOM @@ -1862,8 +1866,10 @@ class LookupEntryRequest(proto.Message): attributed in the following form: ``projects/{project}/locations/{location}``. view (google.cloud.dataplex_v1.types.EntryView): - Optional. View to control which parts of an - entry the service should return. + Optional. View to control which parts of an entry the + service should return. **Please check the limitations on + returned aspects in the Entry view documentation. Amount of + returned aspects depends on the selected Entry View.** aspect_types (MutableSequence[str]): Optional. Limits the aspects returned to the provided aspect types. It only works for CUSTOM @@ -1909,15 +1915,28 @@ class LookupContextRequest(proto.Message): attributed in the following form: ``projects/{project}/locations/{location}``. resources (MutableSequence[str]): - Required. The entry names to lookup context for. The request - should have max 10 of those. + Required. The entry names to look up the context for. The + maximum number of resources for a request is limited to 10. Examples: --------- - projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry} + ``projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}`` + context (str): + Optional. The text representing contextual + information for which metadata context is being + requested. options (MutableMapping[str, str]): Optional. Allows to configure the context. + + Supported options: + + - ``format`` - The format of the context (one of ``yaml``, + ``xml``, ``json``, default is ``yaml``). + - ``context_budget`` - If provided, the output will be + intelligently truncated on a best-effort basis to contain + approximately the desired amount of characters. There is + no guarantee to achieve the specific amount. """ name: str = proto.Field( @@ -1928,6 +1947,10 @@ class LookupContextRequest(proto.Message): proto.STRING, number=2, ) + context: str = proto.Field( + proto.STRING, + number=3, + ) options: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -1935,12 +1958,80 @@ class LookupContextRequest(proto.Message): ) +class ModifyEntryRequest(proto.Message): + r"""Modify Entry request using permissions in the source system. + + Attributes: + name (str): + Required. The project to which the request should be + attributed in the following form: + ``projects/{project}/locations/{location}``. + entry (google.cloud.dataplex_v1.types.Entry): + Required. The entry to modify. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Mask of fields to update. To update Aspects, the + update_mask must contain the value "aspects". + + If the update_mask is empty, the service will update all + modifiable fields present in the request. + delete_missing_aspects (bool): + Optional. If set to true, any aspects not + specified in the request will be deleted. The + default is false. + aspect_keys (MutableSequence[str]): + Optional. The aspect keys which the service should modify. + It supports the following syntaxes: + + - ```` - matches an aspect of the + given type and empty path. + - ``@path`` - matches an aspect of + the given type and specified path. For example, to attach + an aspect to a field that is specified by the ``schema`` + aspect, the path should have the format + ``Schema.``. + - ``@*`` - matches aspects of the + given type for all paths. + - ``*@path`` - matches aspects of all types on the given + path. + + The service will not remove existing aspects matching the + syntax unless ``delete_missing_aspects`` is set to true. + + If this field is left empty, the service treats it as + specifying exactly those Aspects present in the request. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + entry: "Entry" = proto.Field( + proto.MESSAGE, + number=2, + message="Entry", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + delete_missing_aspects: bool = proto.Field( + proto.BOOL, + number=4, + ) + aspect_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + class LookupContextResponse(proto.Message): r"""Lookup Context response. Attributes: context (str): - LLM generated context for the resources. + Pre-formatted block of text containing the + context for the requested resources. """ context: str = proto.Field( diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_discovery.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_discovery.py index 22186759160f..7de08f0ec982 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_discovery.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_discovery.py @@ -155,6 +155,9 @@ class StorageConfig(proto.Message): Optional. Configuration for CSV data. json_options (google.cloud.dataplex_v1.types.DataDiscoverySpec.StorageConfig.JsonOptions): Optional. Configuration for JSON data. + unstructured_data_options (google.cloud.dataplex_v1.types.DataDiscoverySpec.StorageConfig.UnstructuredDataOptions): + Optional. Specifies configuration for + unstructured data discovery. """ class CsvOptions(proto.Message): @@ -226,6 +229,21 @@ class JsonOptions(proto.Message): number=2, ) + class UnstructuredDataOptions(proto.Message): + r"""Describes options for unstructured data discovery. + + Attributes: + semantic_inference_enabled (bool): + Optional. Specifies whether deeper semantic + inference over the objects' contents using GenAI + is enabled. + """ + + semantic_inference_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + include_patterns: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, @@ -244,6 +262,11 @@ class JsonOptions(proto.Message): number=4, message="DataDiscoverySpec.StorageConfig.JsonOptions", ) + unstructured_data_options: "DataDiscoverySpec.StorageConfig.UnstructuredDataOptions" = proto.Field( + proto.MESSAGE, + number=5, + message="DataDiscoverySpec.StorageConfig.UnstructuredDataOptions", + ) bigquery_publishing_config: BigQueryPublishingConfig = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_products.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_products.py index 4861661dea5e..c232868095ef 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_products.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_products.py @@ -21,6 +21,8 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.dataplex_v1.types import approval_workflow + __protobuf__ = proto.module( package="google.cloud.dataplex.v1", manifest={ @@ -32,6 +34,8 @@ "ListDataProductsRequest", "ListDataProductsResponse", "UpdateDataProductRequest", + "RequestDataProductAccessRequest", + "RequestDataProductAccessResponse", "CreateDataAssetRequest", "UpdateDataAssetRequest", "DeleteDataAssetRequest", @@ -47,6 +51,9 @@ class DataProduct(proto.Message): packaged to address specific use cases. It's a way to manage and share data in a more organized, product-like manner. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Identifier. Resource name of the data product. Format: @@ -119,6 +126,11 @@ class DataProduct(proto.Message): } } } + access_approval_config (google.cloud.dataplex_v1.types.DataProduct.AccessApprovalConfig): + Optional. Configuration for access approval + for the data product. + + This field is a member of `oneof`_ ``_access_approval_config``. """ class Principal(proto.Message): @@ -135,6 +147,12 @@ class Principal(proto.Message): https://cloud.google.com/iam/docs/principals-overview#google-group. This field is a member of `oneof`_ ``type``. + service_account (str): + Optional. Specifies the email of the producer + service account, as per + https://cloud.google.com/iam/docs/principals-overview#service-account. + + This field is a member of `oneof`_ ``_service_account``. """ google_group: str = proto.Field( @@ -142,6 +160,11 @@ class Principal(proto.Message): number=1, oneof="type", ) + service_account: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) class AccessGroup(proto.Message): r"""Custom user defined access groups at the data product level. @@ -181,6 +204,23 @@ class AccessGroup(proto.Message): message="DataProduct.Principal", ) + class AccessApprovalConfig(proto.Message): + r"""Configuration for access approval for the data product. + + Attributes: + approver_emails (MutableSequence[str]): + Optional. Specifies the email addresses of + users who are potential approvers and are + notified when an access request is made for the + data product. The maximum number of emails + allowed is 10. + """ + + approver_emails: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -234,6 +274,12 @@ class AccessGroup(proto.Message): number=14, message=AccessGroup, ) + access_approval_config: AccessApprovalConfig = proto.Field( + proto.MESSAGE, + number=15, + optional=True, + message=AccessApprovalConfig, + ) class DataAsset(proto.Message): @@ -594,6 +640,52 @@ class UpdateDataProductRequest(proto.Message): ) +class RequestDataProductAccessRequest(proto.Message): + r"""Message for requesting access to a Data Product. + + Attributes: + parent (str): + Required. The resource name of the data product. Format: + projects/{project_number}/locations/{location_id}/dataProducts/{data_product_id} + change_request (google.cloud.dataplex_v1.types.ChangeRequest): + Required. The change request for the data + product access request. + validate_only (bool): + Optional. Validates the request without + actually creating the access change request. + Defaults to false. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + change_request: approval_workflow.ChangeRequest = proto.Field( + proto.MESSAGE, + number=2, + message=approval_workflow.ChangeRequest, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class RequestDataProductAccessResponse(proto.Message): + r"""Response message for requesting access to a Data Product. + + Attributes: + change_request_name (str): + The resource name of the created ChangeRequest. Format: + projects/{project_number}/locations/{location_id}/changeRequests/{change_request_id} + """ + + change_request_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class CreateDataAssetRequest(proto.Message): r"""Request message for creating a data asset. diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_profile.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_profile.py index 482bbf14e679..2d5729766476 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_profile.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_profile.py @@ -68,8 +68,35 @@ class DataProfileSpec(proto.Message): Optional. If set, the latest DataScan job result will be published as Dataplex Universal Catalog metadata. + mode (google.cloud.dataplex_v1.types.DataProfileSpec.Mode): + Optional. The execution mode for the profile + scan. """ + class Mode(proto.Enum): + r"""Defines the execution mode for the profile scan. + + Values: + MODE_UNSPECIFIED (0): + Default value. This value is unused. + STANDARD (1): + Performs standard profiling. The behavior is controlled by + other fields such as ``sampling_percent``, ``row_filter``, + and column filters. This mode allows for full scans or + custom sampling. + LIGHTWEIGHT (2): + Specifies lightweight profiling mode. This mode is optimized + for low-latency, low-fidelity profiling. + + When this mode is selected, the following fields must not be + set: ``sampling_percent``, ``row_filter``, + ``include_fields``, and ``exclude_fields``. + """ + + MODE_UNSPECIFIED = 0 + STANDARD = 1 + LIGHTWEIGHT = 2 + class PostScanActions(proto.Message): r"""The configuration of post scan actions of DataProfileScan job. @@ -149,6 +176,11 @@ class SelectedFields(proto.Message): proto.BOOL, number=8, ) + mode: Mode = proto.Field( + proto.ENUM, + number=9, + enum=Mode, + ) class DataProfileResult(proto.Message): diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality.py index 13ffb0da69cb..c2aafa2aa286 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality.py @@ -19,7 +19,11 @@ import proto # type: ignore -from google.cloud.dataplex_v1.types import datascans_common, processing +from google.cloud.dataplex_v1.types import ( + data_quality_rule_template, + datascans_common, + processing, +) __protobuf__ = proto.module( package="google.cloud.dataplex.v1", @@ -67,6 +71,34 @@ class DataQualitySpec(proto.Message): Optional. If set, the latest DataScan job result will be published as Dataplex Universal Catalog metadata. + enable_catalog_based_rules (bool): + Optional. If enabled, the data scan will + retrieve rules defined in the + dataplex-types.global.data-rules aspect on all + paths of the catalog entry corresponding to the + BigQuery table resource and all attached + glossary terms. The path that data-rules aspect + is attached on the table entry defines the + column that the rule will be evaluated against. + For glossary terms, the path that the terms are + attached on the table entry defines the column + that the rule will be evaluated against. At the + start of scan execution, the rules reflect the + latest state retrieved from the catalog entry + and any updates on the rules thereafter are + ignored for that execution. The updates will be + reflected from the next execution. Rules defined + in the datascan must be empty if this field is + enabled. + filter (str): + Optional. Filter for selectively running a subset of rules. + You can filter the request by the name or attribute + key-value pairs defined on the rule. If not specified, all + rules are run. The filter is applicable to both, the rules + retrieved from catalog and explicitly defined rules in the + scan. Please see `filter + syntax `__ + for more details. """ class PostScanActions(proto.Message): @@ -216,6 +248,14 @@ class NotificationReport(proto.Message): proto.BOOL, number=8, ) + enable_catalog_based_rules: bool = proto.Field( + proto.BOOL, + number=10, + ) + filter: str = proto.Field( + proto.STRING, + number=11, + ) class DataQualityResult(proto.Message): @@ -675,6 +715,13 @@ class DataQualityRule(proto.Message): rows returned for the provided statement. If any rows are returned, this rule fails. + This field is a member of `oneof`_ ``rule_type``. + template_reference (google.cloud.dataplex_v1.types.DataQualityRule.TemplateReference): + Aggregate rule which references a rule + template and provides the parameters to be + substituted in the template. If any rows are + returned, this rule fails. + This field is a member of `oneof`_ ``rule_type``. column (str): Optional. The unnested column which this rule @@ -718,6 +765,16 @@ class DataQualityRule(proto.Message): suspended (bool): Optional. Whether the Rule is active or suspended. Default is false. + attributes (MutableMapping[str, str]): + Optional. Map of attribute name and value + linked to the rule. The rules to evaluate can be + filtered based on attributes provided here and a + filter expression provided in the + DataQualitySpec.filter field. + rule_source (google.cloud.dataplex_v1.types.DataQualityRule.RuleSource): + Output only. Contains information about the + source of the rule and its relationship with the + BigQuery table, where applicable. debug_queries (MutableSequence[google.cloud.dataplex_v1.types.DataQualityRule.DebugQuery]): Optional. Specifies the debug queries for this rule. Currently, only one query is @@ -947,6 +1004,185 @@ class SqlAssertion(proto.Message): number=1, ) + class TemplateReference(proto.Message): + r"""A rule that constructs a SQL statement to evaluate using a + rule template and parameter values. If the constructed statement + returns any rows, this rule fails + + Attributes: + name (str): + Required. The template entry name. Entry must be of + EntryType + ``projects/dataplex-types/locations/global/entryTypes/data-quality-rule-template`` + and contains top-level aspect of AspectType + ``projects/dataplex-types/locations/global/aspectTypes/data-quality-rule-template``. + The format is: + ``projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}`` + values (MutableMapping[str, google.cloud.dataplex_v1.types.DataQualityRule.TemplateReference.ParameterValue]): + Optional. Provides the map of parameter name + and value. The maximum size of the field is + 120KB (encoded as UTF-8). + resolved_sql (str): + Output only. The resolved SQL statement + generated from the template with parameters + substituted. It is only populated in the result. + rule_template (google.cloud.dataplex_v1.types.DataQualityRuleTemplate): + Output only. The rule template used to + resolve the rule. It is only populated in the + result. + """ + + class ParameterValue(proto.Message): + r"""Represents a parameter value. + + Attributes: + value (str): + Required. Represents the string value of the + parameter. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableMapping[ + str, "DataQualityRule.TemplateReference.ParameterValue" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message="DataQualityRule.TemplateReference.ParameterValue", + ) + resolved_sql: str = proto.Field( + proto.STRING, + number=3, + ) + rule_template: data_quality_rule_template.DataQualityRuleTemplate = proto.Field( + proto.MESSAGE, + number=4, + message=data_quality_rule_template.DataQualityRuleTemplate, + ) + + class RuleSource(proto.Message): + r"""Represents the rule source information from Catalog. + + Attributes: + rule_path_elements (MutableSequence[google.cloud.dataplex_v1.types.DataQualityRule.RuleSource.RulePathElement]): + Output only. Rule path elements represent + information about the individual items in the + relationship path between the scan resource and + rule origin in that order. + """ + + class RulePathElement(proto.Message): + r"""Path Element represents the direct relationship between the + rule origin (aspects) to the BigQuery Entry. Ordering of the + rule relationship will be maintained such that the first entry + in the list is the closest ancestor (BigQuery table itself). A + blank source denotes that the rule is derived directly from the + DataScan itself. + + 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: + entry_source (google.cloud.dataplex_v1.types.DataQualityRule.RuleSource.RulePathElement.EntrySource): + Output only. Entry source represents + information about the related source entry. + + This field is a member of `oneof`_ ``source_type``. + entry_link_source (google.cloud.dataplex_v1.types.DataQualityRule.RuleSource.RulePathElement.EntryLinkSource): + Output only. Entry link source represents + information about the entry link. + + This field is a member of `oneof`_ ``source_type``. + """ + + class EntrySource(proto.Message): + r"""Entry source represents information about the related source + entry. + + Attributes: + entry_type (str): + Output only. The entry type to represent the current + characteristics of the entry in the form of: + ``projects/{project_id_or_number}/locations/{location_id}/entryTypes/{entry-type-id}``. + entry (str): + Output only. The entry name in the form of: + ``projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}`` + display_name (str): + Output only. The display name of the entry. + """ + + entry_type: str = proto.Field( + proto.STRING, + number=1, + ) + entry: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + class EntryLinkSource(proto.Message): + r"""Entry link source represents information about the entry + link. + + Attributes: + entry_link_type (str): + Output only. The entry link type to represent the current + relationship between the entry and the next entry in the + path. In the form of: + ``projects/{project_id_or_number}/locations/{location_id}/entryLinkTypes/{entry_link_type_id}`` + entry_link (str): + Output only. The entry link name in the form of: + ``projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}/entryLinks/{entry_link_id}`` + """ + + entry_link_type: str = proto.Field( + proto.STRING, + number=1, + ) + entry_link: str = proto.Field( + proto.STRING, + number=2, + ) + + entry_source: "DataQualityRule.RuleSource.RulePathElement.EntrySource" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="source_type", + message="DataQualityRule.RuleSource.RulePathElement.EntrySource", + ) + ) + entry_link_source: "DataQualityRule.RuleSource.RulePathElement.EntryLinkSource" = proto.Field( + proto.MESSAGE, + number=2, + oneof="source_type", + message="DataQualityRule.RuleSource.RulePathElement.EntryLinkSource", + ) + + rule_path_elements: MutableSequence[ + "DataQualityRule.RuleSource.RulePathElement" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataQualityRule.RuleSource.RulePathElement", + ) + class DebugQuery(proto.Message): r"""Specifies a SQL statement that is evaluated to return up to 10 scalar values that are used to debug rules. If the rule fails, the @@ -1043,6 +1279,12 @@ class DebugQuery(proto.Message): oneof="rule_type", message=SqlAssertion, ) + template_reference: TemplateReference = proto.Field( + proto.MESSAGE, + number=5, + oneof="rule_type", + message=TemplateReference, + ) column: str = proto.Field( proto.STRING, number=500, @@ -1071,6 +1313,16 @@ class DebugQuery(proto.Message): proto.BOOL, number=506, ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=507, + ) + rule_source: RuleSource = proto.Field( + proto.MESSAGE, + number=508, + message=RuleSource, + ) debug_queries: MutableSequence[DebugQuery] = proto.RepeatedField( proto.MESSAGE, number=510, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality_rule_template.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality_rule_template.py new file mode 100644 index 000000000000..d65210eae5a5 --- /dev/null +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/data_quality_rule_template.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dataplex.v1", + manifest={ + "DataQualityRuleTemplate", + }, +) + + +class DataQualityRuleTemplate(proto.Message): + r"""DataQualityRuleTemplate represents a template which can be + reused across multiple data quality rules. + + Attributes: + name (str): + Output only. The name of the rule template in the format: + ``projects/{project_id_or_number}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}`` + dimension (str): + Output only. The dimension a rule template + belongs to. Rule level results are also + aggregated at the dimension level. + sql_collection (MutableSequence[google.cloud.dataplex_v1.types.DataQualityRuleTemplate.Sql]): + Output only. Collection of SQLs for data + quality rules. Currently only one SQL is + supported. + input_parameters (MutableMapping[str, google.cloud.dataplex_v1.types.DataQualityRuleTemplate.ParameterDescription]): + Output only. Description for input parameters + capabilities (MutableSequence[str]): + Output only. A list of features or properties + supported by this rule template. + """ + + class Sql(proto.Message): + r"""Templatized SQL query for data quality rules. It can have + parameters that can be substituted with values when a rule is + created using this template. + + Attributes: + query (str): + Output only. Templatized SQL query for data + quality rules. + """ + + query: str = proto.Field( + proto.STRING, + number=1, + ) + + class ParameterDescription(proto.Message): + r"""Description of the input parameter. It can include the + type(s) supported by the parameter and intended usage. It is for + information purposes only and does not affect the behavior of + the rule template. + + Attributes: + description (str): + Output only. Description of the input + parameter. It can include the type(s) supported + by the parameter and intended usage. It is for + information purposes only and does not affect + the behavior of the rule template. + default_value (str): + Output only. The default value for the + parameter if no value is provided. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + default_value: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + dimension: str = proto.Field( + proto.STRING, + number=2, + ) + sql_collection: MutableSequence[Sql] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Sql, + ) + input_parameters: MutableMapping[str, ParameterDescription] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=ParameterDescription, + ) + capabilities: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/datascans.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/datascans.py index 12c69a925dda..54a597d7bc9c 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/datascans.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/datascans.py @@ -45,9 +45,12 @@ "GetDataScanJobRequest", "ListDataScanJobsRequest", "ListDataScanJobsResponse", + "CancelDataScanJobRequest", + "CancelDataScanJobResponse", "GenerateDataQualityRulesRequest", "GenerateDataQualityRulesResponse", "DataScan", + "ExecutionIdentity", "DataScanJob", }, ) @@ -88,7 +91,8 @@ class CreateDataScanRequest(proto.Message): data_scan (google.cloud.dataplex_v1.types.DataScan): Required. DataScan resource. data_scan_id (str): - Required. DataScan identifier. + Optional. DataScan identifier. If not provided, a unique ID + will be generated with the prefix "data-scan-". - Must contain only lowercase letters, numbers and hyphens. - Must start with a letter. @@ -469,6 +473,28 @@ def raw_page(self): ) +class CancelDataScanJobRequest(proto.Message): + r"""Request message for the ``CancelDataScanJob`` method. + + Attributes: + name (str): + Required. The resource name of the DataScanJob: + ``projects/{project_id_or_number}/locations/{location_id}/dataScans/{data_scan_id}/jobs/{data_scan_job_id}`` + where ``project_id_or_number`` refers to a *project_id* or + *project_number* and ``location_id`` refers to a Google + Cloud region. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CancelDataScanJobResponse(proto.Message): + r"""Response message for the ``CancelDataScanJob`` method.""" + + class GenerateDataQualityRulesRequest(proto.Message): r"""Request details for generating data quality rule recommendations. @@ -525,9 +551,11 @@ class DataScan(proto.Message): then catalog metadata. For more information, see `Discover and catalog Cloud Storage data `__. - - Data documentation: analyzes the table details and generates - insights including descriptions and sample SQL queries for the - table. For more information, see `Generate data insights in + - Data documentation: analyzes the table or dataset metadata and + generates insights. For tables, insights include descriptions and + sample SQL queries. For datasets, insights include descriptions, + schema relationships and sample SQL queries. For more information, + see `Generate data insights in BigQuery `__. This message has `oneof`_ fields (mutually exclusive fields). @@ -616,6 +644,10 @@ class DataScan(proto.Message): documentation scan. This field is a member of `oneof`_ ``result``. + execution_identity (google.cloud.dataplex_v1.types.ExecutionIdentity): + Optional. Immutable. The identity to run the + datascan. If not specified, defaults to the + Dataplex Service Agent. """ class ExecutionSpec(proto.Message): @@ -788,6 +820,87 @@ class ExecutionStatus(proto.Message): oneof="result", message=data_documentation.DataDocumentationResult, ) + execution_identity: "ExecutionIdentity" = proto.Field( + proto.MESSAGE, + number=300, + message="ExecutionIdentity", + ) + + +class ExecutionIdentity(proto.Message): + r"""The identity to run the datascan. + + 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: + dataplex_service_agent (google.cloud.dataplex_v1.types.ExecutionIdentity.DataplexServiceAgent): + Optional. The Dataplex service agent + associated with the user's project. + + This field is a member of `oneof`_ ``identity``. + user_credential (google.cloud.dataplex_v1.types.ExecutionIdentity.UserCredential): + Optional. The credential of the calling user. Supports only + ONE_TIME trigger type. + + This field is a member of `oneof`_ ``identity``. + service_account (google.cloud.dataplex_v1.types.ExecutionIdentity.ServiceAccount): + Optional. The provided service account. + + This field is a member of `oneof`_ ``identity``. + """ + + class DataplexServiceAgent(proto.Message): + r"""The Dataplex service agent associated with the user's + project. + + """ + + class UserCredential(proto.Message): + r"""The credential of the calling user.""" + + class ServiceAccount(proto.Message): + r"""The service account + + Attributes: + email (str): + Required. Service account email. The datascan + will execute with this service account's + credentials. The user calling this API must have + permissions to act as this service account. + Dataplex service agent must be granted + iam.serviceAccounts.getAccessToken permission on + this service account, for example, through the + iam.serviceAccountTokenCreator role . + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + dataplex_service_agent: DataplexServiceAgent = proto.Field( + proto.MESSAGE, + number=1, + oneof="identity", + message=DataplexServiceAgent, + ) + user_credential: UserCredential = proto.Field( + proto.MESSAGE, + number=2, + oneof="identity", + message=UserCredential, + ) + service_account: ServiceAccount = proto.Field( + proto.MESSAGE, + number=3, + oneof="identity", + message=ServiceAccount, + ) class DataScanJob(proto.Message): @@ -814,6 +927,9 @@ class DataScanJob(proto.Message): create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time when the DataScanJob was created. + partial_failure_message (str): + Output only. A message indicating partial + failure details. start_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time when the DataScanJob was started. @@ -890,6 +1006,8 @@ class State(proto.Enum): PENDING (7): The DataScanJob has been created but not started to run yet. + SUCCEEDED_WITH_ERRORS (8): + The DataScanJob succeeded with errors. """ STATE_UNSPECIFIED = 0 @@ -899,6 +1017,7 @@ class State(proto.Enum): SUCCEEDED = 4 FAILED = 5 PENDING = 7 + SUCCEEDED_WITH_ERRORS = 8 name: str = proto.Field( proto.STRING, @@ -913,6 +1032,10 @@ class State(proto.Enum): number=8, message=timestamp_pb2.Timestamp, ) + partial_failure_message: str = proto.Field( + proto.STRING, + number=9, + ) start_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/logs.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/logs.py index 6e31d725a088..72e173519546 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/logs.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/logs.py @@ -1290,6 +1290,9 @@ class RuleType(proto.Enum): SQL_ASSERTION (9): See [DataQualityRule.SqlAssertion][google.cloud.dataplex.v1.DataQualityRule.SqlAssertion]. + TEMPLATE_REFERENCE (10): + See + [DataQualityRule.TemplateReference][google.cloud.dataplex.v1.DataQualityRule.TemplateReference]. """ RULE_TYPE_UNSPECIFIED = 0 @@ -1302,6 +1305,7 @@ class RuleType(proto.Enum): TABLE_CONDITION_EXPECTATION = 7 UNIQUENESS_EXPECTATION = 8 SQL_ASSERTION = 9 + TEMPLATE_REFERENCE = 10 class EvaluationType(proto.Enum): r"""The evaluation type of the data quality rule. diff --git a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/processing.py b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/processing.py index 508e6821cd06..2a518ab4c7fb 100644 --- a/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/processing.py +++ b/packages/google-cloud-dataplex/google/cloud/dataplex_v1/types/processing.py @@ -152,6 +152,8 @@ class DataSource(proto.Message): DataProfileScan/DataQualityScan/DataDocumentationScan Format: //bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID + or BigQuery dataset for DataDocumentationScan only Format: + //bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID This field is a member of `oneof`_ ``source``. """ diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_async.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_async.py new file mode 100644 index 000000000000..91033df23edc --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModifyEntry +# 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-dataplex + + +# [START dataplex_v1_generated_CatalogService_ModifyEntry_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 dataplex_v1 + + +async def sample_modify_entry(): + # Create a client + client = dataplex_v1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + entry = dataplex_v1.Entry() + entry.entry_type = "entry_type_value" + + request = dataplex_v1.ModifyEntryRequest( + name="name_value", + entry=entry, + ) + + # Make the request + response = await client.modify_entry(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_CatalogService_ModifyEntry_async] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_sync.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_sync.py new file mode 100644 index 000000000000..95bfa76119e7 --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_catalog_service_modify_entry_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ModifyEntry +# 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-dataplex + + +# [START dataplex_v1_generated_CatalogService_ModifyEntry_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 dataplex_v1 + + +def sample_modify_entry(): + # Create a client + client = dataplex_v1.CatalogServiceClient() + + # Initialize request argument(s) + entry = dataplex_v1.Entry() + entry.entry_type = "entry_type_value" + + request = dataplex_v1.ModifyEntryRequest( + name="name_value", + entry=entry, + ) + + # Make the request + response = client.modify_entry(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_CatalogService_ModifyEntry_sync] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_async.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_async.py new file mode 100644 index 000000000000..47beab1766de --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestDataProductAccess +# 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-dataplex + + +# [START dataplex_v1_generated_DataProductService_RequestDataProductAccess_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 dataplex_v1 + + +async def sample_request_data_product_access(): + # Create a client + client = dataplex_v1.DataProductServiceAsyncClient() + + # Initialize request argument(s) + change_request = dataplex_v1.ChangeRequest() + change_request.create_entry.parent = "parent_value" + change_request.create_entry.entry_id = "entry_id_value" + change_request.create_entry.entry.entry_type = "entry_type_value" + + request = dataplex_v1.RequestDataProductAccessRequest( + parent="parent_value", + change_request=change_request, + ) + + # Make the request + response = await client.request_data_product_access(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_DataProductService_RequestDataProductAccess_async] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_sync.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_sync.py new file mode 100644 index 000000000000..3b5c6b65524a --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_product_service_request_data_product_access_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestDataProductAccess +# 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-dataplex + + +# [START dataplex_v1_generated_DataProductService_RequestDataProductAccess_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 dataplex_v1 + + +def sample_request_data_product_access(): + # Create a client + client = dataplex_v1.DataProductServiceClient() + + # Initialize request argument(s) + change_request = dataplex_v1.ChangeRequest() + change_request.create_entry.parent = "parent_value" + change_request.create_entry.entry_id = "entry_id_value" + change_request.create_entry.entry.entry_type = "entry_type_value" + + request = dataplex_v1.RequestDataProductAccessRequest( + parent="parent_value", + change_request=change_request, + ) + + # Make the request + response = client.request_data_product_access(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_DataProductService_RequestDataProductAccess_sync] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_async.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_async.py new file mode 100644 index 000000000000..d202c03086cc --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CancelDataScanJob +# 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-dataplex + + +# [START dataplex_v1_generated_DataScanService_CancelDataScanJob_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 dataplex_v1 + + +async def sample_cancel_data_scan_job(): + # Create a client + client = dataplex_v1.DataScanServiceAsyncClient() + + # Initialize request argument(s) + request = dataplex_v1.CancelDataScanJobRequest( + name="name_value", + ) + + # Make the request + response = await client.cancel_data_scan_job(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_DataScanService_CancelDataScanJob_async] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_sync.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_sync.py new file mode 100644 index 000000000000..443299c9597a --- /dev/null +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_cancel_data_scan_job_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CancelDataScanJob +# 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-dataplex + + +# [START dataplex_v1_generated_DataScanService_CancelDataScanJob_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 dataplex_v1 + + +def sample_cancel_data_scan_job(): + # Create a client + client = dataplex_v1.DataScanServiceClient() + + # Initialize request argument(s) + request = dataplex_v1.CancelDataScanJobRequest( + name="name_value", + ) + + # Make the request + response = client.cancel_data_scan_job(request=request) + + # Handle the response + print(response) + + +# [END dataplex_v1_generated_DataScanService_CancelDataScanJob_sync] diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_async.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_async.py index 76a1ef6cba94..3e6c23644ad5 100644 --- a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_async.py +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_async.py @@ -45,7 +45,6 @@ async def sample_create_data_scan(): request = dataplex_v1.CreateDataScanRequest( parent="parent_value", data_scan=data_scan, - data_scan_id="data_scan_id_value", ) # Make the request diff --git a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_sync.py b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_sync.py index d02a5f8a6b45..222f9d825222 100644 --- a/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_sync.py +++ b/packages/google-cloud-dataplex/samples/generated_samples/dataplex_v1_generated_data_scan_service_create_data_scan_sync.py @@ -45,7 +45,6 @@ def sample_create_data_scan(): request = dataplex_v1.CreateDataScanRequest( parent="parent_value", data_scan=data_scan, - data_scan_id="data_scan_id_value", ) # Make the request diff --git a/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json b/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json index 75827b0afdfa..a5f5e30f98a8 100644 --- a/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json +++ b/packages/google-cloud-dataplex/samples/generated_samples/snippet_metadata_google.cloud.dataplex.v1.json @@ -7398,6 +7398,159 @@ ], "title": "dataplex_v1_generated_catalog_service_lookup_entry_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataplex_v1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.dataplex_v1.CatalogServiceAsyncClient.modify_entry", + "method": { + "fullName": "google.cloud.dataplex.v1.CatalogService.ModifyEntry", + "service": { + "fullName": "google.cloud.dataplex.v1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ModifyEntry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.ModifyEntryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataplex_v1.types.Entry", + "shortName": "modify_entry" + }, + "description": "Sample for ModifyEntry", + "file": "dataplex_v1_generated_catalog_service_modify_entry_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_CatalogService_ModifyEntry_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": "dataplex_v1_generated_catalog_service_modify_entry_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataplex_v1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.dataplex_v1.CatalogServiceClient.modify_entry", + "method": { + "fullName": "google.cloud.dataplex.v1.CatalogService.ModifyEntry", + "service": { + "fullName": "google.cloud.dataplex.v1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ModifyEntry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.ModifyEntryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataplex_v1.types.Entry", + "shortName": "modify_entry" + }, + "description": "Sample for ModifyEntry", + "file": "dataplex_v1_generated_catalog_service_modify_entry_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_CatalogService_ModifyEntry_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": "dataplex_v1_generated_catalog_service_modify_entry_sync.py" + }, { "canonical": true, "clientMethod": { @@ -10722,6 +10875,175 @@ ], "title": "dataplex_v1_generated_data_product_service_list_data_products_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataplex_v1.DataProductServiceAsyncClient", + "shortName": "DataProductServiceAsyncClient" + }, + "fullName": "google.cloud.dataplex_v1.DataProductServiceAsyncClient.request_data_product_access", + "method": { + "fullName": "google.cloud.dataplex.v1.DataProductService.RequestDataProductAccess", + "service": { + "fullName": "google.cloud.dataplex.v1.DataProductService", + "shortName": "DataProductService" + }, + "shortName": "RequestDataProductAccess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.RequestDataProductAccessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "change_request", + "type": "google.cloud.dataplex_v1.types.ChangeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataplex_v1.types.RequestDataProductAccessResponse", + "shortName": "request_data_product_access" + }, + "description": "Sample for RequestDataProductAccess", + "file": "dataplex_v1_generated_data_product_service_request_data_product_access_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_DataProductService_RequestDataProductAccess_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataplex_v1_generated_data_product_service_request_data_product_access_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataplex_v1.DataProductServiceClient", + "shortName": "DataProductServiceClient" + }, + "fullName": "google.cloud.dataplex_v1.DataProductServiceClient.request_data_product_access", + "method": { + "fullName": "google.cloud.dataplex.v1.DataProductService.RequestDataProductAccess", + "service": { + "fullName": "google.cloud.dataplex.v1.DataProductService", + "shortName": "DataProductService" + }, + "shortName": "RequestDataProductAccess" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.RequestDataProductAccessRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "change_request", + "type": "google.cloud.dataplex_v1.types.ChangeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataplex_v1.types.RequestDataProductAccessResponse", + "shortName": "request_data_product_access" + }, + "description": "Sample for RequestDataProductAccess", + "file": "dataplex_v1_generated_data_product_service_request_data_product_access_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_DataProductService_RequestDataProductAccess_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataplex_v1_generated_data_product_service_request_data_product_access_sync.py" + }, { "canonical": true, "clientMethod": { @@ -11060,6 +11382,167 @@ ], "title": "dataplex_v1_generated_data_product_service_update_data_product_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataplex_v1.DataScanServiceAsyncClient", + "shortName": "DataScanServiceAsyncClient" + }, + "fullName": "google.cloud.dataplex_v1.DataScanServiceAsyncClient.cancel_data_scan_job", + "method": { + "fullName": "google.cloud.dataplex.v1.DataScanService.CancelDataScanJob", + "service": { + "fullName": "google.cloud.dataplex.v1.DataScanService", + "shortName": "DataScanService" + }, + "shortName": "CancelDataScanJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.CancelDataScanJobRequest" + }, + { + "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.dataplex_v1.types.CancelDataScanJobResponse", + "shortName": "cancel_data_scan_job" + }, + "description": "Sample for CancelDataScanJob", + "file": "dataplex_v1_generated_data_scan_service_cancel_data_scan_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_DataScanService_CancelDataScanJob_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": "dataplex_v1_generated_data_scan_service_cancel_data_scan_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataplex_v1.DataScanServiceClient", + "shortName": "DataScanServiceClient" + }, + "fullName": "google.cloud.dataplex_v1.DataScanServiceClient.cancel_data_scan_job", + "method": { + "fullName": "google.cloud.dataplex.v1.DataScanService.CancelDataScanJob", + "service": { + "fullName": "google.cloud.dataplex.v1.DataScanService", + "shortName": "DataScanService" + }, + "shortName": "CancelDataScanJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataplex_v1.types.CancelDataScanJobRequest" + }, + { + "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.dataplex_v1.types.CancelDataScanJobResponse", + "shortName": "cancel_data_scan_job" + }, + "description": "Sample for CancelDataScanJob", + "file": "dataplex_v1_generated_data_scan_service_cancel_data_scan_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataplex_v1_generated_DataScanService_CancelDataScanJob_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": "dataplex_v1_generated_data_scan_service_cancel_data_scan_job_sync.py" + }, { "canonical": true, "clientMethod": { @@ -11117,12 +11600,12 @@ "regionTag": "dataplex_v1_generated_DataScanService_CreateDataScan_async", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -11132,18 +11615,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], @@ -11205,12 +11688,12 @@ "regionTag": "dataplex_v1_generated_DataScanService_CreateDataScan_sync", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -11220,18 +11703,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_business_glossary_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_business_glossary_service.py index 6edf7d146e89..af365745fb16 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_business_glossary_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_business_glossary_service.py @@ -1392,7 +1392,12 @@ def test_business_glossary_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -14772,7 +14777,12 @@ def test_business_glossary_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -14798,7 +14808,12 @@ def test_business_glossary_service_auth_adc(): BusinessGlossaryServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id=None, ) @@ -14818,7 +14833,12 @@ def test_business_glossary_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -14873,7 +14893,12 @@ def test_business_glossary_service_transport_create_channel( credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py index 1bf2e8835b44..efa52f8ce686 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_catalog_service.py @@ -9327,6 +9327,258 @@ async def test_lookup_entry_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + catalog.ModifyEntryRequest(), + {}, + ], +) +def test_modify_entry(request_type, transport: str = "grpc"): + client = CatalogServiceClient( + 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.modify_entry), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.Entry( + name="name_value", + entry_type="entry_type_value", + parent_entry="parent_entry_value", + fully_qualified_name="fully_qualified_name_value", + ) + response = client.modify_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = catalog.ModifyEntryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.Entry) + assert response.name == "name_value" + assert response.entry_type == "entry_type_value" + assert response.parent_entry == "parent_entry_value" + assert response.fully_qualified_name == "fully_qualified_name_value" + + +def test_modify_entry_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 = CatalogServiceClient( + 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 = catalog.ModifyEntryRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.modify_entry(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog.ModifyEntryRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_modify_entry_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 = CatalogServiceClient( + 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.modify_entry 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.modify_entry] = mock_rpc + request = {} + client.modify_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.modify_entry(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_modify_entry_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 = CatalogServiceAsyncClient( + 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.modify_entry + 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.modify_entry + ] = mock_rpc + + request = {} + await client.modify_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.modify_entry(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 +@pytest.mark.parametrize( + "request_type", + [ + catalog.ModifyEntryRequest(), + {}, + ], +) +async def test_modify_entry_async(request_type, transport: str = "grpc_asyncio"): + client = CatalogServiceAsyncClient( + 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.modify_entry), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.Entry( + name="name_value", + entry_type="entry_type_value", + parent_entry="parent_entry_value", + fully_qualified_name="fully_qualified_name_value", + ) + ) + response = await client.modify_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = catalog.ModifyEntryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.Entry) + assert response.name == "name_value" + assert response.entry_type == "entry_type_value" + assert response.parent_entry == "parent_entry_value" + assert response.fully_qualified_name == "fully_qualified_name_value" + + +def test_modify_entry_field_headers(): + client = CatalogServiceClient( + 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 = catalog.ModifyEntryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + call.return_value = catalog.Entry() + client.modify_entry(request) + + # Establish that the 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_modify_entry_field_headers_async(): + client = CatalogServiceAsyncClient( + 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 = catalog.ModifyEntryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.Entry()) + await client.modify_entry(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"] + + @pytest.mark.parametrize( "request_type", [ @@ -12990,6 +13242,7 @@ def test_lookup_context_non_empty_request_with_auto_populated_field(): # if they meet the requirements of AIP 4235. request = catalog.LookupContextRequest( name="name_value", + context="context_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -13002,6 +13255,7 @@ def test_lookup_context_non_empty_request_with_auto_populated_field(): _, args, _ = call.mock_calls[0] request_msg = catalog.LookupContextRequest( name="name_value", + context="context_value", ) assert args[0] == request_msg @@ -19626,22 +19880,177 @@ def test_get_entry_rest_flattened(): ) -def test_get_entry_rest_flattened_error(transport: str = "rest"): - client = CatalogServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_get_entry_rest_flattened_error(transport: str = "rest"): + client = CatalogServiceClient( + 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_entry( + catalog.GetEntryRequest(), + name="name_value", + ) + + +def test_lookup_entry_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 = CatalogServiceClient( + 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.lookup_entry 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.lookup_entry] = mock_rpc + + request = {} + client.lookup_entry(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.lookup_entry(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_lookup_entry_rest_required_fields(request_type=catalog.LookupEntryRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["entry"] = "" + 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 + assert "entry" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).lookup_entry._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "entry" in jsonified_request + assert jsonified_request["entry"] == request_init["entry"] + + jsonified_request["name"] = "name_value" + jsonified_request["entry"] = "entry_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).lookup_entry._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "aspect_types", + "entry", + "paths", + "view", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "entry" in jsonified_request + assert jsonified_request["entry"] == "entry_value" + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = catalog.Entry() + # 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 = catalog.Entry.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.lookup_entry(request) + + expected_params = [ + ( + "entry", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_lookup_entry_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport( + 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_entry( - catalog.GetEntryRequest(), - name="name_value", + unset_fields = transport.lookup_entry._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "aspectTypes", + "entry", + "paths", + "view", + ) + ) + & set( + ( + "name", + "entry", + ) ) + ) -def test_lookup_entry_rest_use_cached_wrapped_rpc(): +def test_modify_entry_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: @@ -19655,34 +20064,33 @@ def test_lookup_entry_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.lookup_entry in client._transport._wrapped_methods + assert client._transport.modify_entry 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.lookup_entry] = mock_rpc + client._transport._wrapped_methods[client._transport.modify_entry] = mock_rpc request = {} - client.lookup_entry(request) + client.modify_entry(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.lookup_entry(request) + client.modify_entry(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_lookup_entry_rest_required_fields(request_type=catalog.LookupEntryRequest): +def test_modify_entry_rest_required_fields(request_type=catalog.ModifyEntryRequest): transport_class = transports.CatalogServiceRestTransport request_init = {} request_init["name"] = "" - request_init["entry"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19690,39 +20098,24 @@ def test_lookup_entry_rest_required_fields(request_type=catalog.LookupEntryReque ) # verify fields with default values are dropped - assert "entry" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).lookup_entry._get_unset_required_fields(jsonified_request) + ).modify_entry._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "entry" in jsonified_request - assert jsonified_request["entry"] == request_init["entry"] jsonified_request["name"] = "name_value" - jsonified_request["entry"] = "entry_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).lookup_entry._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "aspect_types", - "entry", - "paths", - "view", - ) - ) + ).modify_entry._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" - assert "entry" in jsonified_request - assert jsonified_request["entry"] == "entry_value" client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19743,9 +20136,10 @@ def test_lookup_entry_rest_required_fields(request_type=catalog.LookupEntryReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -19759,34 +20153,21 @@ def test_lookup_entry_rest_required_fields(request_type=catalog.LookupEntryReque req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.lookup_entry(request) + response = client.modify_entry(request) - expected_params = [ - ( - "entry", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_lookup_entry_rest_unset_required_fields(): +def test_modify_entry_rest_unset_required_fields(): transport = transports.CatalogServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.lookup_entry._get_unset_required_fields({}) + unset_fields = transport.modify_entry._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "aspectTypes", - "entry", - "paths", - "view", - ) - ) + set(()) & set( ( "name", @@ -23606,6 +23987,26 @@ def test_lookup_entry_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_modify_entry_empty_call_grpc(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + call.return_value = catalog.Entry() + client.modify_entry(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog.ModifyEntryRequest() + assert args[0] == request_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_search_entries_empty_call_grpc(): @@ -24550,6 +24951,35 @@ async def test_lookup_entry_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_modify_entry_empty_call_grpc_asyncio(): + client = CatalogServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + catalog.Entry( + name="name_value", + entry_type="entry_type_value", + parent_entry="parent_entry_value", + fully_qualified_name="fully_qualified_name_value", + ) + ) + await client.modify_entry(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog.ModifyEntryRequest() + assert args[0] == request_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 @@ -28465,6 +28895,138 @@ def test_lookup_entry_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_modify_entry_rest_bad_request(request_type=catalog.ModifyEntryRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "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.modify_entry(request) + + +@pytest.mark.parametrize( + "request_type", + [ + catalog.ModifyEntryRequest, + dict, + ], +) +def test_modify_entry_rest_call_success(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + 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(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = catalog.Entry( + name="name_value", + entry_type="entry_type_value", + parent_entry="parent_entry_value", + fully_qualified_name="fully_qualified_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 = catalog.Entry.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.modify_entry(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.Entry) + assert response.name == "name_value" + assert response.entry_type == "entry_type_value" + assert response.parent_entry == "parent_entry_value" + assert response.fully_qualified_name == "fully_qualified_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_modify_entry_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(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.CatalogServiceRestInterceptor, "post_modify_entry" + ) as post, + mock.patch.object( + transports.CatalogServiceRestInterceptor, "post_modify_entry_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.CatalogServiceRestInterceptor, "pre_modify_entry" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = catalog.ModifyEntryRequest.pb(catalog.ModifyEntryRequest()) + 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 = catalog.Entry.to_json(catalog.Entry()) + req.return_value.content = return_value + + request = catalog.ModifyEntryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.Entry() + post_with_metadata.return_value = catalog.Entry(), metadata + + client.modify_entry( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_search_entries_rest_bad_request(request_type=catalog.SearchEntriesRequest): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -31991,6 +32553,25 @@ def test_lookup_entry_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_modify_entry_empty_call_rest(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.modify_entry), "__call__") as call: + client.modify_entry(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = catalog.ModifyEntryRequest() + assert args[0] == request_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_search_entries_empty_call_rest(): @@ -32390,6 +32971,7 @@ def test_catalog_service_base_transport(): "list_entries", "get_entry", "lookup_entry", + "modify_entry", "search_entries", "create_metadata_job", "get_metadata_job", @@ -32768,6 +33350,9 @@ def test_catalog_service_client_transport_session_collision(transport_name): session1 = client1.transport.lookup_entry._session session2 = client2.transport.lookup_entry._session assert session1 != session2 + session1 = client1.transport.modify_entry._session + session2 = client2.transport.modify_entry._session + assert session1 != session2 session1 = client1.transport.search_entries._session session2 = client2.transport.search_entries._session assert session1 != session2 diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_cmek_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_cmek_service.py index c4d4f70c12fa..79450c538913 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_cmek_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_cmek_service.py @@ -1288,7 +1288,10 @@ def test_cmek_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -6303,7 +6306,10 @@ def test_cmek_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -6329,7 +6335,10 @@ def test_cmek_service_auth_adc(): CmekServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id=None, ) @@ -6349,7 +6358,10 @@ def test_cmek_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -6402,7 +6414,10 @@ def test_cmek_service_transport_create_channel(transport_class, grpc_helpers): credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_product_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_product_service.py index 92edc17e2e25..7254c907b05c 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_product_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_product_service.py @@ -42,6 +42,7 @@ import google.auth import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.api_core import ( client_options, @@ -72,7 +73,13 @@ pagers, transports, ) -from google.cloud.dataplex_v1.types import data_products, service +from google.cloud.dataplex_v1.types import ( + approval_workflow, + business_glossary, + catalog, + data_products, + service, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1368,7 +1375,12 @@ def test_data_product_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -3354,11 +3366,11 @@ async def test_update_data_product_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - data_products.CreateDataAssetRequest(), + data_products.RequestDataProductAccessRequest(), {}, ], ) -def test_create_data_asset(request_type, transport: str = "grpc"): +def test_request_data_product_access(request_type, transport: str = "grpc"): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3370,23 +3382,26 @@ def test_create_data_asset(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_data_asset(request) + call.return_value = data_products.RequestDataProductAccessResponse( + change_request_name="change_request_name_value", + ) + response = client.request_data_product_access(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = data_products.CreateDataAssetRequest() + request = data_products.RequestDataProductAccessRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, data_products.RequestDataProductAccessResponse) + assert response.change_request_name == "change_request_name_value" -def test_create_data_asset_non_empty_request_with_auto_populated_field(): +def test_request_data_product_access_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 = DataProductServiceClient( @@ -3397,29 +3412,27 @@ def test_create_data_asset_non_empty_request_with_auto_populated_field(): # 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_products.CreateDataAssetRequest( + request = data_products.RequestDataProductAccessRequest( parent="parent_value", - data_asset_id="data_asset_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_data_asset(request=request) + client.request_data_product_access(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = data_products.CreateDataAssetRequest( + request_msg = data_products.RequestDataProductAccessRequest( parent="parent_value", - data_asset_id="data_asset_id_value", ) assert args[0] == request_msg -def test_create_data_asset_use_cached_wrapped_rpc(): +def test_request_data_product_access_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: @@ -3433,28 +3446,26 @@ def test_create_data_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_data_asset in client._transport._wrapped_methods + assert ( + client._transport.request_data_product_access + 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_data_asset] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.request_data_product_access + ] = mock_rpc request = {} - client.create_data_asset(request) + client.request_data_product_access(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_data_asset(request) + client.request_data_product_access(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3462,7 +3473,7 @@ def test_create_data_asset_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_data_asset_async_use_cached_wrapped_rpc( +async def test_request_data_product_access_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3479,7 +3490,7 @@ async def test_create_data_asset_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_data_asset + client._client._transport.request_data_product_access in client._client._transport._wrapped_methods ) @@ -3487,21 +3498,16 @@ async def test_create_data_asset_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_data_asset + client._client._transport.request_data_product_access ] = mock_rpc request = {} - await client.create_data_asset(request) + await client.request_data_product_access(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_data_asset(request) + await client.request_data_product_access(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3512,11 +3518,13 @@ async def test_create_data_asset_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - data_products.CreateDataAssetRequest(), + data_products.RequestDataProductAccessRequest(), {}, ], ) -async def test_create_data_asset_async(request_type, transport: str = "grpc_asyncio"): +async def test_request_data_product_access_async( + request_type, transport: str = "grpc_asyncio" +): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3528,41 +3536,44 @@ async def test_create_data_asset_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + data_products.RequestDataProductAccessResponse( + change_request_name="change_request_name_value", + ) ) - response = await client.create_data_asset(request) + response = await client.request_data_product_access(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = data_products.CreateDataAssetRequest() + request = data_products.RequestDataProductAccessRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, data_products.RequestDataProductAccessResponse) + assert response.change_request_name == "change_request_name_value" -def test_create_data_asset_field_headers(): +def test_request_data_product_access_field_headers(): client = DataProductServiceClient( 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_products.CreateDataAssetRequest() + request = data_products.RequestDataProductAccessRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_data_asset(request) + call.return_value = data_products.RequestDataProductAccessResponse() + client.request_data_product_access(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3578,25 +3589,25 @@ def test_create_data_asset_field_headers(): @pytest.mark.asyncio -async def test_create_data_asset_field_headers_async(): +async def test_request_data_product_access_field_headers_async(): client = DataProductServiceAsyncClient( 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_products.CreateDataAssetRequest() + request = data_products.RequestDataProductAccessRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + data_products.RequestDataProductAccessResponse() ) - await client.create_data_asset(request) + await client.request_data_product_access(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3611,23 +3622,22 @@ async def test_create_data_asset_field_headers_async(): ) in kw["metadata"] -def test_create_data_asset_flattened(): +def test_request_data_product_access_flattened(): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = data_products.RequestDataProductAccessResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_data_asset( + client.request_data_product_access( parent="parent_value", - data_asset=data_products.DataAsset(name="name_value"), - data_asset_id="data_asset_id_value", + change_request=approval_workflow.ChangeRequest(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -3637,15 +3647,12 @@ def test_create_data_asset_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].data_asset - mock_val = data_products.DataAsset(name="name_value") - assert arg == mock_val - arg = args[0].data_asset_id - mock_val = "data_asset_id_value" + arg = args[0].change_request + mock_val = approval_workflow.ChangeRequest(name="name_value") assert arg == mock_val -def test_create_data_asset_flattened_error(): +def test_request_data_product_access_flattened_error(): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3653,36 +3660,34 @@ def test_create_data_asset_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_asset( - data_products.CreateDataAssetRequest(), + client.request_data_product_access( + data_products.RequestDataProductAccessRequest(), parent="parent_value", - data_asset=data_products.DataAsset(name="name_value"), - data_asset_id="data_asset_id_value", + change_request=approval_workflow.ChangeRequest(name="name_value"), ) @pytest.mark.asyncio -async def test_create_data_asset_flattened_async(): +async def test_request_data_product_access_flattened_async(): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_asset), "__call__" + type(client.transport.request_data_product_access), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = data_products.RequestDataProductAccessResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + data_products.RequestDataProductAccessResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_data_asset( + response = await client.request_data_product_access( parent="parent_value", - data_asset=data_products.DataAsset(name="name_value"), - data_asset_id="data_asset_id_value", + change_request=approval_workflow.ChangeRequest(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -3692,16 +3697,13 @@ async def test_create_data_asset_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].data_asset - mock_val = data_products.DataAsset(name="name_value") - assert arg == mock_val - arg = args[0].data_asset_id - mock_val = "data_asset_id_value" + arg = args[0].change_request + mock_val = approval_workflow.ChangeRequest(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_create_data_asset_flattened_error_async(): +async def test_request_data_product_access_flattened_error_async(): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3709,22 +3711,21 @@ async def test_create_data_asset_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_data_asset( - data_products.CreateDataAssetRequest(), + await client.request_data_product_access( + data_products.RequestDataProductAccessRequest(), parent="parent_value", - data_asset=data_products.DataAsset(name="name_value"), - data_asset_id="data_asset_id_value", + change_request=approval_workflow.ChangeRequest(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - data_products.UpdateDataAssetRequest(), + data_products.CreateDataAssetRequest(), {}, ], ) -def test_update_data_asset(request_type, transport: str = "grpc"): +def test_create_data_asset(request_type, transport: str = "grpc"): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3736,23 +3737,23 @@ def test_update_data_asset(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_data_asset(request) + response = client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = data_products.UpdateDataAssetRequest() + request = data_products.CreateDataAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_data_asset_non_empty_request_with_auto_populated_field(): +def test_create_data_asset_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 = DataProductServiceClient( @@ -3763,23 +3764,29 @@ def test_update_data_asset_non_empty_request_with_auto_populated_field(): # 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_products.UpdateDataAssetRequest() + request = data_products.CreateDataAssetRequest( + parent="parent_value", + data_asset_id="data_asset_id_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_asset(request=request) + client.create_data_asset(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = data_products.UpdateDataAssetRequest() + request_msg = data_products.CreateDataAssetRequest( + parent="parent_value", + data_asset_id="data_asset_id_value", + ) assert args[0] == request_msg -def test_update_data_asset_use_cached_wrapped_rpc(): +def test_create_data_asset_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: @@ -3793,18 +3800,18 @@ def test_update_data_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_data_asset in client._transport._wrapped_methods + assert client._transport.create_data_asset 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_data_asset] = ( + client._transport._wrapped_methods[client._transport.create_data_asset] = ( mock_rpc ) request = {} - client.update_data_asset(request) + client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3814,7 +3821,7 @@ def test_update_data_asset_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_data_asset(request) + client.create_data_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3822,7 +3829,7 @@ def test_update_data_asset_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_data_asset_async_use_cached_wrapped_rpc( +async def test_create_data_asset_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3839,7 +3846,7 @@ async def test_update_data_asset_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_data_asset + client._client._transport.create_data_asset in client._client._transport._wrapped_methods ) @@ -3847,11 +3854,11 @@ async def test_update_data_asset_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_data_asset + client._client._transport.create_data_asset ] = mock_rpc request = {} - await client.update_data_asset(request) + await client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3861,7 +3868,7 @@ async def test_update_data_asset_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_data_asset(request) + await client.create_data_asset(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3872,11 +3879,11 @@ async def test_update_data_asset_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - data_products.UpdateDataAssetRequest(), + data_products.CreateDataAssetRequest(), {}, ], ) -async def test_update_data_asset_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_data_asset_async(request_type, transport: str = "grpc_asyncio"): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3888,41 +3895,41 @@ async def test_update_data_asset_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__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.update_data_asset(request) + response = await client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = data_products.UpdateDataAssetRequest() + request = data_products.CreateDataAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_data_asset_field_headers(): +def test_create_data_asset_field_headers(): client = DataProductServiceClient( 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_products.UpdateDataAssetRequest() + request = data_products.CreateDataAssetRequest() - request.data_asset.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_data_asset(request) + client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3933,30 +3940,30 @@ def test_update_data_asset_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_asset.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_data_asset_field_headers_async(): +async def test_create_data_asset_field_headers_async(): client = DataProductServiceAsyncClient( 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_products.UpdateDataAssetRequest() + request = data_products.CreateDataAssetRequest() - request.data_asset.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_data_asset(request) + await client.create_data_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3967,41 +3974,45 @@ async def test_update_data_asset_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_asset.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_data_asset_flattened(): +def test_create_data_asset_flattened(): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__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.update_data_asset( + client.create_data_asset( + parent="parent_value", data_asset=data_products.DataAsset(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + data_asset_id="data_asset_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].data_asset mock_val = data_products.DataAsset(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].data_asset_id + mock_val = "data_asset_id_value" assert arg == mock_val -def test_update_data_asset_flattened_error(): +def test_create_data_asset_flattened_error(): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4009,22 +4020,23 @@ def test_update_data_asset_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_asset( - data_products.UpdateDataAssetRequest(), + client.create_data_asset( + data_products.CreateDataAssetRequest(), + parent="parent_value", data_asset=data_products.DataAsset(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + data_asset_id="data_asset_id_value", ) @pytest.mark.asyncio -async def test_update_data_asset_flattened_async(): +async def test_create_data_asset_flattened_async(): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_asset), "__call__" + type(client.transport.create_data_asset), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4034,25 +4046,29 @@ async def test_update_data_asset_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_data_asset( + response = await client.create_data_asset( + parent="parent_value", data_asset=data_products.DataAsset(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + data_asset_id="data_asset_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].data_asset mock_val = data_products.DataAsset(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].data_asset_id + mock_val = "data_asset_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_data_asset_flattened_error_async(): +async def test_create_data_asset_flattened_error_async(): client = DataProductServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4060,21 +4076,22 @@ async def test_update_data_asset_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_data_asset( - data_products.UpdateDataAssetRequest(), + await client.create_data_asset( + data_products.CreateDataAssetRequest(), + parent="parent_value", data_asset=data_products.DataAsset(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + data_asset_id="data_asset_id_value", ) @pytest.mark.parametrize( "request_type", [ - data_products.DeleteDataAssetRequest(), + data_products.UpdateDataAssetRequest(), {}, ], ) -def test_delete_data_asset(request_type, transport: str = "grpc"): +def test_update_data_asset(request_type, transport: str = "grpc"): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4086,23 +4103,23 @@ def test_delete_data_asset(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_asset), "__call__" + type(client.transport.update_data_asset), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_data_asset(request) + response = client.update_data_asset(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = data_products.DeleteDataAssetRequest() + request = data_products.UpdateDataAssetRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_data_asset_non_empty_request_with_auto_populated_field(): +def test_update_data_asset_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 = DataProductServiceClient( @@ -4113,29 +4130,23 @@ def test_delete_data_asset_non_empty_request_with_auto_populated_field(): # 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_products.DeleteDataAssetRequest( - name="name_value", - etag="etag_value", - ) + request = data_products.UpdateDataAssetRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_asset), "__call__" + type(client.transport.update_data_asset), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_data_asset(request=request) + client.update_data_asset(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = data_products.DeleteDataAssetRequest( - name="name_value", - etag="etag_value", - ) + request_msg = data_products.UpdateDataAssetRequest() assert args[0] == request_msg -def test_delete_data_asset_use_cached_wrapped_rpc(): +def test_update_data_asset_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: @@ -4149,14 +4160,370 @@ def test_delete_data_asset_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_data_asset in client._transport._wrapped_methods + assert client._transport.update_data_asset 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_data_asset] = ( + client._transport._wrapped_methods[client._transport.update_data_asset] = ( + mock_rpc + ) + request = {} + client.update_data_asset(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.update_data_asset(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_data_asset_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 = DataProductServiceAsyncClient( + 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_data_asset + 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_data_asset + ] = mock_rpc + + request = {} + await client.update_data_asset(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.update_data_asset(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 +@pytest.mark.parametrize( + "request_type", + [ + data_products.UpdateDataAssetRequest(), + {}, + ], +) +async def test_update_data_asset_async(request_type, transport: str = "grpc_asyncio"): + client = DataProductServiceAsyncClient( + 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_data_asset), "__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.update_data_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_products.UpdateDataAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_data_asset_field_headers(): + client = DataProductServiceClient( + 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_products.UpdateDataAssetRequest() + + request.data_asset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_asset), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_asset(request) + + # Establish that the 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", + "data_asset.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_data_asset_field_headers_async(): + client = DataProductServiceAsyncClient( + 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_products.UpdateDataAssetRequest() + + request.data_asset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_asset), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_data_asset(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", + "data_asset.name=name_value", + ) in kw["metadata"] + + +def test_update_data_asset_flattened(): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_asset), "__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.update_data_asset( + data_asset=data_products.DataAsset(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].data_asset + mock_val = data_products.DataAsset(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_data_asset_flattened_error(): + client = DataProductServiceClient( + 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_data_asset( + data_products.UpdateDataAssetRequest(), + data_asset=data_products.DataAsset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_data_asset_flattened_async(): + client = DataProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_asset), "__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.update_data_asset( + data_asset=data_products.DataAsset(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].data_asset + mock_val = data_products.DataAsset(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_data_asset_flattened_error_async(): + client = DataProductServiceAsyncClient( + 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_data_asset( + data_products.UpdateDataAssetRequest(), + data_asset=data_products.DataAsset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + data_products.DeleteDataAssetRequest(), + {}, + ], +) +def test_delete_data_asset(request_type, transport: str = "grpc"): + client = DataProductServiceClient( + 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_data_asset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_data_asset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_products.DeleteDataAssetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_data_asset_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 = DataProductServiceClient( + 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_products.DeleteDataAssetRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_asset), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_data_asset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_products.DeleteDataAssetRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_data_asset_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 = DataProductServiceClient( + 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_data_asset 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_data_asset] = ( mock_rpc ) request = {} @@ -6110,18 +6477,216 @@ def test_list_data_products_rest_pager(transport: str = "rest"): sample_request = {"parent": "projects/sample1/locations/sample2"} - pager = client.list_data_products(request=sample_request) + pager = client.list_data_products(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_products.DataProduct) for i in results) + + pages = list(client.list_data_products(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_data_product_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 = DataProductServiceClient( + 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_data_product 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_data_product] = ( + mock_rpc + ) + + request = {} + client.update_data_product(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.update_data_product(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_data_product_rest_required_fields( + request_type=data_products.UpdateDataProductRequest, +): + transport_class = transports.DataProductServiceRestTransport + + 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_data_product._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_data_product._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", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DataProductServiceClient( + 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": "patch", + "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.update_data_product(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_data_product_rest_unset_required_fields(): + transport = transports.DataProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_data_product._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "updateMask", + "validateOnly", + ) + ) + & set(("dataProduct",)) + ) + + +def test_update_data_product_rest_flattened(): + client = DataProductServiceClient( + 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 = { + "data_product": { + "name": "projects/sample1/locations/sample2/dataProducts/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + data_product=data_products.DataProduct(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_product(**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/v1/{data_product.name=projects/*/locations/*/dataProducts/*}" + % client.transport._host, + args[1], + ) + - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, data_products.DataProduct) for i in results) +def test_update_data_product_rest_flattened_error(transport: str = "rest"): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - pages = list(client.list_data_products(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_product( + data_products.UpdateDataProductRequest(), + data_product=data_products.DataProduct(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_update_data_product_rest_use_cached_wrapped_rpc(): +def test_request_data_product_access_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: @@ -6136,7 +6701,8 @@ def test_update_data_product_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_product in client._transport._wrapped_methods + client._transport.request_data_product_access + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6144,33 +6710,30 @@ def test_update_data_product_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_data_product] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.request_data_product_access + ] = mock_rpc request = {} - client.update_data_product(request) + client.request_data_product_access(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.update_data_product(request) + client.request_data_product_access(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_data_product_rest_required_fields( - request_type=data_products.UpdateDataProductRequest, +def test_request_data_product_access_rest_required_fields( + request_type=data_products.RequestDataProductAccessRequest, ): transport_class = transports.DataProductServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6181,24 +6744,21 @@ def test_update_data_product_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_data_product._get_unset_required_fields(jsonified_request) + ).request_data_product_access._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() - ).update_data_product._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", - "validate_only", - ) - ) + ).request_data_product_access._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 = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6207,7 +6767,7 @@ def test_update_data_product_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = data_products.RequestDataProductAccessResponse() # 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 @@ -6219,7 +6779,7 @@ def test_update_data_product_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6227,37 +6787,42 @@ def test_update_data_product_rest_required_fields( response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = data_products.RequestDataProductAccessResponse.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_data_product(request) + response = client.request_data_product_access(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_data_product_rest_unset_required_fields(): +def test_request_data_product_access_rest_unset_required_fields(): transport = transports.DataProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_data_product._get_unset_required_fields({}) + unset_fields = transport.request_data_product_access._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "updateMask", - "validateOnly", + "parent", + "changeRequest", ) ) - & set(("dataProduct",)) ) -def test_update_data_product_rest_flattened(): +def test_request_data_product_access_rest_flattened(): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6266,44 +6831,44 @@ def test_update_data_product_rest_flattened(): # 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") + return_value = data_products.RequestDataProductAccessResponse() # get arguments that satisfy an http rule for this method sample_request = { - "data_product": { - "name": "projects/sample1/locations/sample2/dataProducts/sample3" - } + "parent": "projects/sample1/locations/sample2/dataProducts/sample3" } # get truthy value for each flattened field mock_args = dict( - data_product=data_products.DataProduct(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + change_request=approval_workflow.ChangeRequest(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 = data_products.RequestDataProductAccessResponse.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_data_product(**mock_args) + client.request_data_product_access(**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/v1/{data_product.name=projects/*/locations/*/dataProducts/*}" + "%s/v1/{parent=projects/*/locations/*/dataProducts/*}:requestAccess" % client.transport._host, args[1], ) -def test_update_data_product_rest_flattened_error(transport: str = "rest"): +def test_request_data_product_access_rest_flattened_error(transport: str = "rest"): client = DataProductServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6312,10 +6877,10 @@ def test_update_data_product_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_product( - data_products.UpdateDataProductRequest(), - data_product=data_products.DataProduct(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.request_data_product_access( + data_products.RequestDataProductAccessRequest(), + parent="parent_value", + change_request=approval_workflow.ChangeRequest(name="name_value"), ) @@ -7577,6 +8142,28 @@ def test_update_data_product_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_request_data_product_access_empty_call_grpc(): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_data_product_access), "__call__" + ) as call: + call.return_value = data_products.RequestDataProductAccessResponse() + client.request_data_product_access(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_products.RequestDataProductAccessRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_data_asset_empty_call_grpc(): @@ -7837,6 +8424,34 @@ async def test_update_data_product_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_request_data_product_access_empty_call_grpc_asyncio(): + client = DataProductServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_data_product_access), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_products.RequestDataProductAccessResponse( + change_request_name="change_request_name_value", + ) + ) + await client.request_data_product_access(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_products.RequestDataProductAccessRequest() + assert args[0] == request_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 @@ -8030,6 +8645,9 @@ def test_create_data_product_rest_call_success(request_type): "owner_emails": ["owner_emails_value1", "owner_emails_value2"], "asset_count": 1192, "access_groups": {}, + "access_approval_config": { + "approver_emails": ["approver_emails_value1", "approver_emails_value2"] + }, } # 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 @@ -8654,6 +9272,9 @@ def test_update_data_product_rest_call_success(request_type): "owner_emails": ["owner_emails_value1", "owner_emails_value2"], "asset_count": 1192, "access_groups": {}, + "access_approval_config": { + "approver_emails": ["approver_emails_value1", "approver_emails_value2"] + }, } # 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 @@ -8671,79 +9292,211 @@ def get_message_fields(field): 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 + 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["data_product"].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["data_product"][field])): + del request_init["data_product"][field][i][subfield] + else: + del request_init["data_product"][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.update_data_product(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_update_data_product_rest_interceptors(null_interceptor): + transport = transports.DataProductServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataProductServiceRestInterceptor(), + ) + client = DataProductServiceClient(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.DataProductServiceRestInterceptor, "post_update_data_product" + ) as post, + mock.patch.object( + transports.DataProductServiceRestInterceptor, + "post_update_data_product_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataProductServiceRestInterceptor, "pre_update_data_product" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_products.UpdateDataProductRequest.pb( + data_products.UpdateDataProductRequest() + ) + 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 = data_products.UpdateDataProductRequest() + 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.update_data_product( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() - 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 = [] +def test_request_data_product_access_rest_bad_request( + request_type=data_products.RequestDataProductAccessRequest, +): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/dataProducts/sample3"} + request = request_type(**request_init) - # 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["data_product"].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 + # 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.request_data_product_access(request) - 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["data_product"][field])): - del request_init["data_product"][field][i][subfield] - else: - del request_init["data_product"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + data_products.RequestDataProductAccessRequest, + dict, + ], +) +def test_request_data_product_access_rest_call_success(request_type): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/dataProducts/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = data_products.RequestDataProductAccessResponse( + change_request_name="change_request_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 = data_products.RequestDataProductAccessResponse.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_data_product(request) + response = client.request_data_product_access(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, data_products.RequestDataProductAccessResponse) + assert response.change_request_name == "change_request_name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_product_rest_interceptors(null_interceptor): +def test_request_data_product_access_rest_interceptors(null_interceptor): transport = transports.DataProductServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8755,23 +9508,24 @@ def test_update_data_product_rest_interceptors(null_interceptor): 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.DataProductServiceRestInterceptor, "post_update_data_product" + transports.DataProductServiceRestInterceptor, + "post_request_data_product_access", ) as post, mock.patch.object( transports.DataProductServiceRestInterceptor, - "post_update_data_product_with_metadata", + "post_request_data_product_access_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataProductServiceRestInterceptor, "pre_update_data_product" + transports.DataProductServiceRestInterceptor, + "pre_request_data_product_access", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = data_products.UpdateDataProductRequest.pb( - data_products.UpdateDataProductRequest() + pb_message = data_products.RequestDataProductAccessRequest.pb( + data_products.RequestDataProductAccessRequest() ) transcode.return_value = { "method": "post", @@ -8783,19 +9537,24 @@ def test_update_data_product_rest_interceptors(null_interceptor): 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()) + return_value = data_products.RequestDataProductAccessResponse.to_json( + data_products.RequestDataProductAccessResponse() + ) req.return_value.content = return_value - request = data_products.UpdateDataProductRequest() + request = data_products.RequestDataProductAccessRequest() 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 + post.return_value = data_products.RequestDataProductAccessResponse() + post_with_metadata.return_value = ( + data_products.RequestDataProductAccessResponse(), + metadata, + ) - client.update_data_product( + client.request_data_product_access( request, metadata=[ ("key", "val"), @@ -10302,6 +11061,27 @@ def test_update_data_product_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_request_data_product_access_empty_call_rest(): + client = DataProductServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_data_product_access), "__call__" + ) as call: + client.request_data_product_access(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_products.RequestDataProductAccessRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_data_asset_empty_call_rest(): @@ -10458,6 +11238,7 @@ def test_data_product_service_base_transport(): "get_data_product", "list_data_products", "update_data_product", + "request_data_product_access", "create_data_asset", "update_data_asset", "delete_data_asset", @@ -10513,7 +11294,12 @@ def test_data_product_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -10539,7 +11325,12 @@ def test_data_product_service_auth_adc(): DataProductServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id=None, ) @@ -10559,7 +11350,12 @@ def test_data_product_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -10612,7 +11408,12 @@ def test_data_product_service_transport_create_channel(transport_class, grpc_hel credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -10759,6 +11560,9 @@ def test_data_product_service_client_transport_session_collision(transport_name) session1 = client1.transport.update_data_product._session session2 = client2.transport.update_data_product._session assert session1 != session2 + session1 = client1.transport.request_data_product_access._session + session2 = client2.transport.request_data_product_access._session + assert session1 != session2 session1 = client1.transport.create_data_asset._session session2 = client2.transport.create_data_asset._session assert session1 != session2 @@ -10937,11 +11741,39 @@ def test_data_product_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_data_asset_path(): +def test_change_request_path(): project = "squid" location = "clam" - data_product = "whelk" - data_asset = "octopus" + change_request = "whelk" + expected = "projects/{project}/locations/{location}/changeRequests/{change_request}".format( + project=project, + location=location, + change_request=change_request, + ) + actual = DataProductServiceClient.change_request_path( + project, location, change_request + ) + assert expected == actual + + +def test_parse_change_request_path(): + expected = { + "project": "octopus", + "location": "oyster", + "change_request": "nudibranch", + } + path = DataProductServiceClient.change_request_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_change_request_path(path) + assert expected == actual + + +def test_data_asset_path(): + project = "cuttlefish" + location = "mussel" + data_product = "winkle" + data_asset = "nautilus" expected = "projects/{project}/locations/{location}/dataProducts/{data_product}/dataAssets/{data_asset}".format( project=project, location=location, @@ -10956,10 +11788,10 @@ def test_data_asset_path(): def test_parse_data_asset_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "data_product": "cuttlefish", - "data_asset": "mussel", + "project": "scallop", + "location": "abalone", + "data_product": "squid", + "data_asset": "clam", } path = DataProductServiceClient.data_asset_path(**expected) @@ -10969,9 +11801,9 @@ def test_parse_data_asset_path(): def test_data_product_path(): - project = "winkle" - location = "nautilus" - data_product = "scallop" + project = "whelk" + location = "octopus" + data_product = "oyster" expected = ( "projects/{project}/locations/{location}/dataProducts/{data_product}".format( project=project, @@ -10985,9 +11817,9 @@ def test_data_product_path(): def test_parse_data_product_path(): expected = { - "project": "abalone", - "location": "squid", - "data_product": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "data_product": "mussel", } path = DataProductServiceClient.data_product_path(**expected) @@ -10996,8 +11828,184 @@ def test_parse_data_product_path(): assert expected == actual +def test_entry_path(): + project = "winkle" + location = "nautilus" + entry_group = "scallop" + entry = "abalone" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format( + project=project, + location=location, + entry_group=entry_group, + entry=entry, + ) + actual = DataProductServiceClient.entry_path(project, location, entry_group, entry) + assert expected == actual + + +def test_parse_entry_path(): + expected = { + "project": "squid", + "location": "clam", + "entry_group": "whelk", + "entry": "octopus", + } + path = DataProductServiceClient.entry_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_entry_path(path) + assert expected == actual + + +def test_entry_group_path(): + project = "oyster" + location = "nudibranch" + entry_group = "cuttlefish" + expected = ( + "projects/{project}/locations/{location}/entryGroups/{entry_group}".format( + project=project, + location=location, + entry_group=entry_group, + ) + ) + actual = DataProductServiceClient.entry_group_path(project, location, entry_group) + assert expected == actual + + +def test_parse_entry_group_path(): + expected = { + "project": "mussel", + "location": "winkle", + "entry_group": "nautilus", + } + path = DataProductServiceClient.entry_group_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_entry_group_path(path) + assert expected == actual + + +def test_entry_link_path(): + project = "scallop" + location = "abalone" + entry_group = "squid" + entry_link = "clam" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entryLinks/{entry_link}".format( + project=project, + location=location, + entry_group=entry_group, + entry_link=entry_link, + ) + actual = DataProductServiceClient.entry_link_path( + project, location, entry_group, entry_link + ) + assert expected == actual + + +def test_parse_entry_link_path(): + expected = { + "project": "whelk", + "location": "octopus", + "entry_group": "oyster", + "entry_link": "nudibranch", + } + path = DataProductServiceClient.entry_link_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_entry_link_path(path) + assert expected == actual + + +def test_glossary_path(): + project = "cuttlefish" + location = "mussel" + glossary = "winkle" + expected = "projects/{project}/locations/{location}/glossaries/{glossary}".format( + project=project, + location=location, + glossary=glossary, + ) + actual = DataProductServiceClient.glossary_path(project, location, glossary) + assert expected == actual + + +def test_parse_glossary_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "glossary": "abalone", + } + path = DataProductServiceClient.glossary_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_glossary_path(path) + assert expected == actual + + +def test_glossary_category_path(): + project = "squid" + location = "clam" + glossary = "whelk" + glossary_category = "octopus" + expected = "projects/{project}/locations/{location}/glossaries/{glossary}/categories/{glossary_category}".format( + project=project, + location=location, + glossary=glossary, + glossary_category=glossary_category, + ) + actual = DataProductServiceClient.glossary_category_path( + project, location, glossary, glossary_category + ) + assert expected == actual + + +def test_parse_glossary_category_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "glossary": "cuttlefish", + "glossary_category": "mussel", + } + path = DataProductServiceClient.glossary_category_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_glossary_category_path(path) + assert expected == actual + + +def test_glossary_term_path(): + project = "winkle" + location = "nautilus" + glossary = "scallop" + glossary_term = "abalone" + expected = "projects/{project}/locations/{location}/glossaries/{glossary}/terms/{glossary_term}".format( + project=project, + location=location, + glossary=glossary, + glossary_term=glossary_term, + ) + actual = DataProductServiceClient.glossary_term_path( + project, location, glossary, glossary_term + ) + assert expected == actual + + +def test_parse_glossary_term_path(): + expected = { + "project": "squid", + "location": "clam", + "glossary": "whelk", + "glossary_term": "octopus", + } + path = DataProductServiceClient.glossary_term_path(**expected) + + # Check that the path construction is reversible. + actual = DataProductServiceClient.parse_glossary_term_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -11007,7 +12015,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nudibranch", } path = DataProductServiceClient.common_billing_account_path(**expected) @@ -11017,7 +12025,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -11027,7 +12035,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "mussel", } path = DataProductServiceClient.common_folder_path(**expected) @@ -11037,7 +12045,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -11047,7 +12055,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "nautilus", } path = DataProductServiceClient.common_organization_path(**expected) @@ -11057,7 +12065,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -11067,7 +12075,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "abalone", } path = DataProductServiceClient.common_project_path(**expected) @@ -11077,8 +12085,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11089,8 +12097,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "whelk", + "location": "octopus", } path = DataProductServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py index ddd6e04143ed..082127b40a08 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_scan_service.py @@ -78,6 +78,7 @@ data_documentation, data_profile, data_quality, + data_quality_rule_template, datascans, datascans_common, processing, @@ -1361,7 +1362,12 @@ def test_data_scan_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -3597,6 +3603,7 @@ def test_get_data_scan_job(request_type, transport: str = "grpc"): call.return_value = datascans.DataScanJob( name="name_value", uid="uid_value", + partial_failure_message="partial_failure_message_value", state=datascans.DataScanJob.State.RUNNING, message="message_value", type_=datascans.DataScanType.DATA_QUALITY, @@ -3613,6 +3620,7 @@ def test_get_data_scan_job(request_type, transport: str = "grpc"): assert isinstance(response, datascans.DataScanJob) assert response.name == "name_value" assert response.uid == "uid_value" + assert response.partial_failure_message == "partial_failure_message_value" assert response.state == datascans.DataScanJob.State.RUNNING assert response.message == "message_value" assert response.type_ == datascans.DataScanType.DATA_QUALITY @@ -3755,6 +3763,7 @@ async def test_get_data_scan_job_async(request_type, transport: str = "grpc_asyn datascans.DataScanJob( name="name_value", uid="uid_value", + partial_failure_message="partial_failure_message_value", state=datascans.DataScanJob.State.RUNNING, message="message_value", type_=datascans.DataScanType.DATA_QUALITY, @@ -3772,6 +3781,7 @@ async def test_get_data_scan_job_async(request_type, transport: str = "grpc_asyn assert isinstance(response, datascans.DataScanJob) assert response.name == "name_value" assert response.uid == "uid_value" + assert response.partial_failure_message == "partial_failure_message_value" assert response.state == datascans.DataScanJob.State.RUNNING assert response.message == "message_value" assert response.type_ == datascans.DataScanType.DATA_QUALITY @@ -4472,6 +4482,344 @@ async def test_list_data_scan_jobs_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + datascans.CancelDataScanJobRequest(), + {}, + ], +) +def test_cancel_data_scan_job(request_type, transport: str = "grpc"): + client = DataScanServiceClient( + 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.cancel_data_scan_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datascans.CancelDataScanJobResponse() + response = client.cancel_data_scan_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datascans.CancelDataScanJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datascans.CancelDataScanJobResponse) + + +def test_cancel_data_scan_job_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 = DataScanServiceClient( + 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 = datascans.CancelDataScanJobRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.cancel_data_scan_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datascans.CancelDataScanJobRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_cancel_data_scan_job_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 = DataScanServiceClient( + 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.cancel_data_scan_job 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.cancel_data_scan_job] = ( + mock_rpc + ) + request = {} + client.cancel_data_scan_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_data_scan_job(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_cancel_data_scan_job_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 = DataScanServiceAsyncClient( + 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.cancel_data_scan_job + 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.cancel_data_scan_job + ] = mock_rpc + + request = {} + await client.cancel_data_scan_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.cancel_data_scan_job(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 +@pytest.mark.parametrize( + "request_type", + [ + datascans.CancelDataScanJobRequest(), + {}, + ], +) +async def test_cancel_data_scan_job_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataScanServiceAsyncClient( + 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.cancel_data_scan_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datascans.CancelDataScanJobResponse() + ) + response = await client.cancel_data_scan_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datascans.CancelDataScanJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datascans.CancelDataScanJobResponse) + + +def test_cancel_data_scan_job_field_headers(): + client = DataScanServiceClient( + 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 = datascans.CancelDataScanJobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + call.return_value = datascans.CancelDataScanJobResponse() + client.cancel_data_scan_job(request) + + # Establish that the 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_cancel_data_scan_job_field_headers_async(): + client = DataScanServiceAsyncClient( + 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 = datascans.CancelDataScanJobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datascans.CancelDataScanJobResponse() + ) + await client.cancel_data_scan_job(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_cancel_data_scan_job_flattened(): + client = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datascans.CancelDataScanJobResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.cancel_data_scan_job( + 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_cancel_data_scan_job_flattened_error(): + client = DataScanServiceClient( + 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.cancel_data_scan_job( + datascans.CancelDataScanJobRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_cancel_data_scan_job_flattened_async(): + client = DataScanServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datascans.CancelDataScanJobResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datascans.CancelDataScanJobResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.cancel_data_scan_job( + 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_cancel_data_scan_job_flattened_error_async(): + client = DataScanServiceAsyncClient( + 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.cancel_data_scan_job( + datascans.CancelDataScanJobRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ @@ -4860,7 +5208,6 @@ def test_create_data_scan_rest_required_fields( request_init = {} request_init["parent"] = "" - request_init["data_scan_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4868,7 +5215,6 @@ def test_create_data_scan_rest_required_fields( ) # verify fields with default values are dropped - assert "dataScanId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() @@ -4876,11 +5222,8 @@ def test_create_data_scan_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "dataScanId" in jsonified_request - assert jsonified_request["dataScanId"] == request_init["data_scan_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["dataScanId"] = "data_scan_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() @@ -4897,8 +5240,6 @@ def test_create_data_scan_rest_required_fields( # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "dataScanId" in jsonified_request - assert jsonified_request["dataScanId"] == "data_scan_id_value" client = DataScanServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4935,13 +5276,7 @@ def test_create_data_scan_rest_required_fields( response = client.create_data_scan(request) - expected_params = [ - ( - "dataScanId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) @@ -4963,7 +5298,6 @@ def test_create_data_scan_rest_unset_required_fields(): ( "parent", "dataScan", - "dataScanId", ) ) ) @@ -6457,18 +6791,203 @@ def test_list_data_scan_jobs_rest_pager(transport: str = "rest"): req.side_effect = return_values sample_request = { - "parent": "projects/sample1/locations/sample2/dataScans/sample3" + "parent": "projects/sample1/locations/sample2/dataScans/sample3" + } + + pager = client.list_data_scan_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, datascans.DataScanJob) for i in results) + + pages = list(client.list_data_scan_jobs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_cancel_data_scan_job_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 = DataScanServiceClient( + 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.cancel_data_scan_job 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.cancel_data_scan_job] = ( + mock_rpc + ) + + request = {} + client.cancel_data_scan_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_data_scan_job(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_cancel_data_scan_job_rest_required_fields( + request_type=datascans.CancelDataScanJobRequest, +): + transport_class = transports.DataScanServiceRestTransport + + 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() + ).cancel_data_scan_job._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() + ).cancel_data_scan_job._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 = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datascans.CancelDataScanJobResponse() + # 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 = datascans.CancelDataScanJobResponse.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.cancel_data_scan_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_data_scan_job_rest_unset_required_fields(): + transport = transports.DataScanServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel_data_scan_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_cancel_data_scan_job_rest_flattened(): + client = DataScanServiceClient( + 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 = datascans.CancelDataScanJobResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataScans/sample3/jobs/sample4" } - pager = client.list_data_scan_jobs(request=sample_request) + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, datascans.DataScanJob) for i in results) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = datascans.CancelDataScanJobResponse.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"} - pages = list(client.list_data_scan_jobs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.cancel_data_scan_job(**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/v1/{name=projects/*/locations/*/dataScans/*/jobs/*}:cancel" + % client.transport._host, + args[1], + ) + + +def test_cancel_data_scan_job_rest_flattened_error(transport: str = "rest"): + client = DataScanServiceClient( + 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.cancel_data_scan_job( + datascans.CancelDataScanJobRequest(), + name="name_value", + ) def test_generate_data_quality_rules_rest_use_cached_wrapped_rpc(): @@ -6927,6 +7446,28 @@ def test_list_data_scan_jobs_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_cancel_data_scan_job_empty_call_grpc(): + client = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + call.return_value = datascans.CancelDataScanJobResponse() + client.cancel_data_scan_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datascans.CancelDataScanJobRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_generate_data_quality_rules_empty_call_grpc(): @@ -7135,6 +7676,7 @@ async def test_get_data_scan_job_empty_call_grpc_asyncio(): datascans.DataScanJob( name="name_value", uid="uid_value", + partial_failure_message="partial_failure_message_value", state=datascans.DataScanJob.State.RUNNING, message="message_value", type_=datascans.DataScanType.DATA_QUALITY, @@ -7177,6 +7719,32 @@ async def test_list_data_scan_jobs_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_cancel_data_scan_job_empty_call_grpc_asyncio(): + client = DataScanServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datascans.CancelDataScanJobResponse() + ) + await client.cancel_data_scan_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datascans.CancelDataScanJobRequest() + assert args[0] == request_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 @@ -7303,6 +7871,21 @@ def test_create_data_scan_rest_call_success(request_type): "sql_expression": "sql_expression_value" }, "sql_assertion": {"sql_statement": "sql_statement_value"}, + "template_reference": { + "name": "name_value", + "values": {}, + "resolved_sql": "resolved_sql_value", + "rule_template": { + "name": "name_value", + "dimension": "dimension_value", + "sql_collection": [{"query": "query_value"}], + "input_parameters": {}, + "capabilities": [ + "capabilities_value1", + "capabilities_value2", + ], + }, + }, "column": "column_value", "ignore_null": True, "dimension": "dimension_value", @@ -7310,6 +7893,22 @@ def test_create_data_scan_rest_call_success(request_type): "name": "name_value", "description": "description_value", "suspended": True, + "attributes": {}, + "rule_source": { + "rule_path_elements": [ + { + "entry_source": { + "entry_type": "entry_type_value", + "entry": "entry_value", + "display_name": "display_name_value", + }, + "entry_link_source": { + "entry_link_type": "entry_link_type_value", + "entry_link": "entry_link_value", + }, + } + ] + }, "debug_queries": [ { "description": "description_value", @@ -7330,6 +7929,8 @@ def test_create_data_scan_rest_call_success(request_type): }, }, "catalog_publishing_enabled": True, + "enable_catalog_based_rules": True, + "filter": "filter_value", }, "data_profile_spec": { "sampling_percent": 0.17070000000000002, @@ -7342,6 +7943,7 @@ def test_create_data_scan_rest_call_success(request_type): }, "exclude_fields": {}, "catalog_publishing_enabled": True, + "mode": 1, }, "data_discovery_spec": { "bigquery_publishing_config": { @@ -7370,6 +7972,7 @@ def test_create_data_scan_rest_call_success(request_type): "encoding": "encoding_value", "type_inference_disabled": True, }, + "unstructured_data_options": {"semantic_inference_enabled": True}, }, }, "data_documentation_spec": { @@ -7523,6 +8126,11 @@ def test_create_data_scan_rest_call_success(request_type): "queries": {}, }, }, + "execution_identity": { + "dataplex_service_agent": {}, + "user_credential": {}, + "service_account": {"email": "email_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 @@ -7774,6 +8382,21 @@ def test_update_data_scan_rest_call_success(request_type): "sql_expression": "sql_expression_value" }, "sql_assertion": {"sql_statement": "sql_statement_value"}, + "template_reference": { + "name": "name_value", + "values": {}, + "resolved_sql": "resolved_sql_value", + "rule_template": { + "name": "name_value", + "dimension": "dimension_value", + "sql_collection": [{"query": "query_value"}], + "input_parameters": {}, + "capabilities": [ + "capabilities_value1", + "capabilities_value2", + ], + }, + }, "column": "column_value", "ignore_null": True, "dimension": "dimension_value", @@ -7781,6 +8404,22 @@ def test_update_data_scan_rest_call_success(request_type): "name": "name_value", "description": "description_value", "suspended": True, + "attributes": {}, + "rule_source": { + "rule_path_elements": [ + { + "entry_source": { + "entry_type": "entry_type_value", + "entry": "entry_value", + "display_name": "display_name_value", + }, + "entry_link_source": { + "entry_link_type": "entry_link_type_value", + "entry_link": "entry_link_value", + }, + } + ] + }, "debug_queries": [ { "description": "description_value", @@ -7801,6 +8440,8 @@ def test_update_data_scan_rest_call_success(request_type): }, }, "catalog_publishing_enabled": True, + "enable_catalog_based_rules": True, + "filter": "filter_value", }, "data_profile_spec": { "sampling_percent": 0.17070000000000002, @@ -7813,6 +8454,7 @@ def test_update_data_scan_rest_call_success(request_type): }, "exclude_fields": {}, "catalog_publishing_enabled": True, + "mode": 1, }, "data_discovery_spec": { "bigquery_publishing_config": { @@ -7841,6 +8483,7 @@ def test_update_data_scan_rest_call_success(request_type): "encoding": "encoding_value", "type_inference_disabled": True, }, + "unstructured_data_options": {"semantic_inference_enabled": True}, }, }, "data_documentation_spec": { @@ -7994,6 +8637,11 @@ def test_update_data_scan_rest_call_success(request_type): "queries": {}, }, }, + "execution_identity": { + "dataplex_service_agent": {}, + "user_credential": {}, + "service_account": {"email": "email_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 @@ -8720,6 +9368,7 @@ def test_get_data_scan_job_rest_call_success(request_type): return_value = datascans.DataScanJob( name="name_value", uid="uid_value", + partial_failure_message="partial_failure_message_value", state=datascans.DataScanJob.State.RUNNING, message="message_value", type_=datascans.DataScanType.DATA_QUALITY, @@ -8741,6 +9390,7 @@ def test_get_data_scan_job_rest_call_success(request_type): assert isinstance(response, datascans.DataScanJob) assert response.name == "name_value" assert response.uid == "uid_value" + assert response.partial_failure_message == "partial_failure_message_value" assert response.state == datascans.DataScanJob.State.RUNNING assert response.message == "message_value" assert response.type_ == datascans.DataScanType.DATA_QUALITY @@ -8944,6 +9594,143 @@ def test_list_data_scan_jobs_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_cancel_data_scan_job_rest_bad_request( + request_type=datascans.CancelDataScanJobRequest, +): + client = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataScans/sample3/jobs/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.cancel_data_scan_job(request) + + +@pytest.mark.parametrize( + "request_type", + [ + datascans.CancelDataScanJobRequest, + dict, + ], +) +def test_cancel_data_scan_job_rest_call_success(request_type): + client = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataScans/sample3/jobs/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 = datascans.CancelDataScanJobResponse() + + # 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 = datascans.CancelDataScanJobResponse.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.cancel_data_scan_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, datascans.CancelDataScanJobResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_data_scan_job_rest_interceptors(null_interceptor): + transport = transports.DataScanServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataScanServiceRestInterceptor(), + ) + client = DataScanServiceClient(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.DataScanServiceRestInterceptor, "post_cancel_data_scan_job" + ) as post, + mock.patch.object( + transports.DataScanServiceRestInterceptor, + "post_cancel_data_scan_job_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataScanServiceRestInterceptor, "pre_cancel_data_scan_job" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = datascans.CancelDataScanJobRequest.pb( + datascans.CancelDataScanJobRequest() + ) + 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 = datascans.CancelDataScanJobResponse.to_json( + datascans.CancelDataScanJobResponse() + ) + req.return_value.content = return_value + + request = datascans.CancelDataScanJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = datascans.CancelDataScanJobResponse() + post_with_metadata.return_value = ( + datascans.CancelDataScanJobResponse(), + metadata, + ) + + client.cancel_data_scan_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_generate_data_quality_rules_rest_bad_request( request_type=datascans.GenerateDataQualityRulesRequest, ): @@ -9804,6 +10591,27 @@ def test_list_data_scan_jobs_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_cancel_data_scan_job_empty_call_rest(): + client = DataScanServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.cancel_data_scan_job), "__call__" + ) as call: + client.cancel_data_scan_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datascans.CancelDataScanJobRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_generate_data_quality_rules_empty_call_rest(): @@ -9883,6 +10691,7 @@ def test_data_scan_service_base_transport(): "run_data_scan", "get_data_scan_job", "list_data_scan_jobs", + "cancel_data_scan_job", "generate_data_quality_rules", "set_iam_policy", "get_iam_policy", @@ -9934,7 +10743,12 @@ def test_data_scan_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -9960,7 +10774,12 @@ def test_data_scan_service_auth_adc(): DataScanServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id=None, ) @@ -9980,7 +10799,12 @@ def test_data_scan_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -10033,7 +10857,12 @@ def test_data_scan_service_transport_create_channel(transport_class, grpc_helper credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -10187,6 +11016,9 @@ def test_data_scan_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_data_scan_jobs._session session2 = client2.transport.list_data_scan_jobs._session assert session1 != session2 + session1 = client1.transport.cancel_data_scan_job._session + session2 = client2.transport.cancel_data_scan_job._session + assert session1 != session2 session1 = client1.transport.generate_data_quality_rules._session session2 = client2.transport.generate_data_quality_rules._session assert session1 != session2 @@ -10491,8 +11323,37 @@ def test_parse_entity_path(): assert expected == actual +def test_entry_path(): + project = "scallop" + location = "abalone" + entry_group = "squid" + entry = "clam" + expected = "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}".format( + project=project, + location=location, + entry_group=entry_group, + entry=entry, + ) + actual = DataScanServiceClient.entry_path(project, location, entry_group, entry) + assert expected == actual + + +def test_parse_entry_path(): + expected = { + "project": "whelk", + "location": "octopus", + "entry_group": "oyster", + "entry": "nudibranch", + } + path = DataScanServiceClient.entry_path(**expected) + + # Check that the path construction is reversible. + actual = DataScanServiceClient.parse_entry_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10502,7 +11363,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "mussel", } path = DataScanServiceClient.common_billing_account_path(**expected) @@ -10512,7 +11373,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -10522,7 +11383,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "nautilus", } path = DataScanServiceClient.common_folder_path(**expected) @@ -10532,7 +11393,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -10542,7 +11403,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "abalone", } path = DataScanServiceClient.common_organization_path(**expected) @@ -10552,7 +11413,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -10562,7 +11423,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "clam", } path = DataScanServiceClient.common_project_path(**expected) @@ -10572,8 +11433,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -10584,8 +11445,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "oyster", + "location": "nudibranch", } path = DataScanServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py index f2390303d714..a88f6d41f201 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_data_taxonomy_service.py @@ -1387,7 +1387,10 @@ def test_data_taxonomy_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -15048,7 +15051,10 @@ def test_data_taxonomy_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -15074,7 +15080,10 @@ def test_data_taxonomy_service_auth_adc(): DataTaxonomyServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id=None, ) @@ -15094,7 +15103,10 @@ def test_data_taxonomy_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -15147,7 +15159,10 @@ def test_data_taxonomy_service_transport_create_channel(transport_class, grpc_he credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py index dea7ecc7d9f7..e5a370cd5d75 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_dataplex_service.py @@ -1351,7 +1351,12 @@ def test_dataplex_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -24548,7 +24553,12 @@ def test_dataplex_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -24574,7 +24584,12 @@ def test_dataplex_service_auth_adc(): DataplexServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id=None, ) @@ -24594,7 +24609,12 @@ def test_dataplex_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), quota_project_id="octopus", ) @@ -24647,7 +24667,12 @@ def test_dataplex_service_transport_create_channel(transport_class, grpc_helpers credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/dataplex.read-write", + "https://www.googleapis.com/auth/dataplex.readonly", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, diff --git a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py index fe02b962f1a3..ff5eccc63563 100644 --- a/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py +++ b/packages/google-cloud-dataplex/tests/unit/gapic/dataplex_v1/test_metadata_service.py @@ -1344,7 +1344,10 @@ def test_metadata_service_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=None, default_host="dataplex.googleapis.com", ssl_credentials=None, @@ -9408,7 +9411,10 @@ def test_metadata_service_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -9434,7 +9440,10 @@ def test_metadata_service_auth_adc(): MetadataServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id=None, ) @@ -9454,7 +9463,10 @@ def test_metadata_service_transport_auth_adc(transport_class): 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",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), quota_project_id="octopus", ) @@ -9507,7 +9519,10 @@ def test_metadata_service_transport_create_channel(transport_class, grpc_helpers credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dataplex.read-write", + ), scopes=["1", "2"], default_host="dataplex.googleapis.com", ssl_credentials=None, diff --git a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py index 370aa72044b5..f4e3d6a1ec2e 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py @@ -65,6 +65,9 @@ ContentLocation, ContentMetadata, ContentOption, + Conversation, + ConversationLocation, + ConversationMessage, CreateConnectionRequest, CreateDeidentifyTemplateRequest, CreateDiscoveryConfigRequest, @@ -384,6 +387,9 @@ "ContentItem", "ContentLocation", "ContentMetadata", + "Conversation", + "ConversationLocation", + "ConversationMessage", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", "CreateDiscoveryConfigRequest", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py index 52a594231705..4bc8431e09e9 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py @@ -69,6 +69,9 @@ ContentLocation, ContentMetadata, ContentOption, + Conversation, + ConversationLocation, + ConversationMessage, CreateConnectionRequest, CreateDeidentifyTemplateRequest, CreateDiscoveryConfigRequest, @@ -484,6 +487,9 @@ def _get_version(dependency_name): "ContentLocation", "ContentMetadata", "ContentOption", + "Conversation", + "ConversationLocation", + "ConversationMessage", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", "CreateDiscoveryConfigRequest", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py index 9e0098944843..0b416e4fa3a0 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py @@ -58,6 +58,9 @@ ContentLocation, ContentMetadata, ContentOption, + Conversation, + ConversationLocation, + ConversationMessage, CreateConnectionRequest, CreateDeidentifyTemplateRequest, CreateDiscoveryConfigRequest, @@ -375,6 +378,9 @@ "ContentItem", "ContentLocation", "ContentMetadata", + "Conversation", + "ConversationLocation", + "ConversationMessage", "CreateConnectionRequest", "CreateDeidentifyTemplateRequest", "CreateDiscoveryConfigRequest", 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 f1ba158bb4c1..567cd1d2d95d 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 @@ -66,12 +66,15 @@ "ByteContentItem", "ContentItem", "ContentMetadata", + "Conversation", + "ConversationMessage", "Table", "KeyValueMetadataProperty", "InspectResult", "Finding", "Location", "ContentLocation", + "ConversationLocation", "MetadataLocation", "StorageMetadataLabel", "KeyValueMetadataLabel", @@ -337,22 +340,22 @@ class TransformationResultStatusType(proto.Enum): STATE_TYPE_UNSPECIFIED (0): Unused. INVALID_TRANSFORM (1): - This will be set when a finding could not be + This is set when a finding cannot be transformed (i.e. outside user set bucket range). BIGQUERY_MAX_ROW_SIZE_EXCEEDED (2): - This will be set when a BigQuery - transformation was successful but could not be - stored back in BigQuery because the transformed - row exceeds BigQuery's max row size. + This is set when a transformation is + successful but cannot be stored in BigQuery + because the transformed row exceeds BigQuery's + max row size. METADATA_UNRETRIEVABLE (3): - This will be set when there is a finding in - the custom metadata of a file, but at the write - time of the transformed file, this key / value - pair is unretrievable. + This is set when there is a finding in the + custom metadata of a file, but at the write time + of the transformed file, this key / value pair + is unretrievable. SUCCESS (4): - This will be set when the transformation and - storing of it is successful. + This is set when the transformation and its + storage are successful. """ STATE_TYPE_UNSPECIFIED = 0 @@ -1634,6 +1637,13 @@ class ContentItem(proto.Message): Content data to inspect or redact. Replaces ``type`` and ``data``. + This field is a member of `oneof`_ ``data_item``. + conversation (google.cloud.dlp_v2.types.Conversation): + Represents a conversation (either complete or + a slice). It is assumed that all included + messages are contiguous and ordered in + chronological order. + This field is a member of `oneof`_ ``data_item``. content_metadata (google.cloud.dlp_v2.types.ContentMetadata): User provided metadata for the content. @@ -1656,6 +1666,12 @@ class ContentItem(proto.Message): oneof="data_item", message="ByteContentItem", ) + conversation: "Conversation" = proto.Field( + proto.MESSAGE, + number=7, + oneof="data_item", + message="Conversation", + ) content_metadata: "ContentMetadata" = proto.Field( proto.MESSAGE, number=6, @@ -1679,6 +1695,78 @@ class ContentMetadata(proto.Message): ) +class Conversation(proto.Message): + r"""Complete conversation or slice of a conversation. + It is assumed that all included messages are contiguous and + ordered in chronological order. + + Attributes: + messages (MutableSequence[google.cloud.dlp_v2.types.ConversationMessage]): + Messages exchanged within this conversation. + The maximum number of messages allowed is 50k. + The order of the messages is assumed to be + chronological and will be used to index findings + in the response. + """ + + messages: MutableSequence["ConversationMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ConversationMessage", + ) + + +class ConversationMessage(proto.Message): + r"""Single message in a conversation. + + Attributes: + content (str): + The contents of this message. + message_type (google.cloud.dlp_v2.types.ConversationMessage.MessageType): + The type of message. + participant_id (str): + Optional. The identifier of the participant, for example, + 'test-user' or 'gemini'. The participant ID can contain + lowercase letters, numbers, and hyphens; that is, it must + match the regular expression: + ``^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$``. The maximum length is + 63 characters. + """ + + class MessageType(proto.Enum): + r"""The type of message. + New values may be added in the future. + + Values: + MESSAGE_TYPE_UNSPECIFIED (0): + Unused. + CONTENT (1): + Message contains content to be inspected. + CONTEXT (2): + Message contains context only and will not + have findings reported from it during inspection + or redacted from it during de-identification. + """ + + MESSAGE_TYPE_UNSPECIFIED = 0 + CONTENT = 1 + CONTEXT = 2 + + content: str = proto.Field( + proto.STRING, + number=1, + ) + message_type: MessageType = proto.Field( + proto.ENUM, + number=2, + enum=MessageType, + ) + participant_id: str = proto.Field( + proto.STRING, + number=3, + ) + + class Table(proto.Message): r"""Structured content to inspect. Up to 50,000 ``Value``\ s per request allowed. See @@ -1977,6 +2065,10 @@ class ContentLocation(proto.Message): Location within the metadata for inspected content. + This field is a member of `oneof`_ ``location``. + conversation_location (google.cloud.dlp_v2.types.ConversationLocation): + Location within a conversation. + This field is a member of `oneof`_ ``location``. container_timestamp (google.protobuf.timestamp_pb2.Timestamp): Finding container modification timestamp, if applicable. For @@ -2017,6 +2109,12 @@ class ContentLocation(proto.Message): oneof="location", message="MetadataLocation", ) + conversation_location: "ConversationLocation" = proto.Field( + proto.MESSAGE, + number=10, + oneof="location", + message="ConversationLocation", + ) container_timestamp: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=6, @@ -2028,6 +2126,48 @@ class ContentLocation(proto.Message): ) +class ConversationLocation(proto.Message): + r"""Location within a conversation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + message_index (int): + Matches an index of a message in the + conversation provided in the request. + + This field is a member of `oneof`_ ``location``. + all_messages (google.cloud.dlp_v2.types.ConversationLocation.AllMessages): + If set, indicates that the finding applies to + all messages in the conversation. + + This field is a member of `oneof`_ ``location``. + """ + + class AllMessages(proto.Message): + r"""If set, indicates that the finding applies to all messages in + the conversation. + + """ + + message_index: int = proto.Field( + proto.INT32, + number=1, + oneof="location", + ) + all_messages: AllMessages = proto.Field( + proto.MESSAGE, + number=2, + oneof="location", + message=AllMessages, + ) + + class MetadataLocation(proto.Message): r"""Metadata Location @@ -8555,7 +8695,7 @@ class Export(proto.Message): receives the Pub/Sub notification. - The best practice is to use the same table for an entire organization so that you can take advantage of the - `provided Looker + `provided Data Studio reports `__. If you use VPC Service Controls to define security perimeters, then you must use a separate table for each diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py index aeeb9bf70d24..70ca234d8777 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py @@ -96,6 +96,7 @@ ExampleQueries, ListMessagesRequest, ListMessagesResponse, + LookerSettings, Message, SchemaMessage, SchemaQuery, @@ -182,6 +183,7 @@ "ExampleQueries", "ListMessagesRequest", "ListMessagesResponse", + "LookerSettings", "Message", "SchemaMessage", "SchemaQuery", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py index b27f73f8a524..0f4040145eb1 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/__init__.py @@ -92,6 +92,7 @@ ExampleQueries, ListMessagesRequest, ListMessagesResponse, + LookerSettings, Message, SchemaMessage, SchemaQuery, @@ -264,6 +265,7 @@ def _get_version(dependency_name): "LookerExploreReferences", "LookerGoldenQuery", "LookerQuery", + "LookerSettings", "MatchedQuery", "Message", "OAuthCredentials", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py index 58f4c10426dc..8143faecfa14 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/__init__.py @@ -81,6 +81,7 @@ ExampleQueries, ListMessagesRequest, ListMessagesResponse, + LookerSettings, Message, SchemaMessage, SchemaQuery, @@ -163,6 +164,7 @@ "ExampleQueries", "ListMessagesRequest", "ListMessagesResponse", + "LookerSettings", "Message", "SchemaMessage", "SchemaQuery", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py index ac9618e89409..5dcb26f7012a 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/context.py @@ -266,8 +266,6 @@ class BigQueryRoutine(proto.Message): class BigQueryRoutineReference(proto.Message): r"""A reference to a BigQuery routine. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: project_id (str): The project ID of the routine. @@ -275,15 +273,6 @@ class BigQueryRoutineReference(proto.Message): The dataset ID of the routine. routine_id (str): The routine ID of the routine. - boundary_location_id (str): - Optional. The location to restrict BigQuery - operations to. - If unspecified, this value defaults to the - location of the endpoint. - - Examples: "us-central1", "europe-west1". - - This field is a member of `oneof`_ ``_boundary_location_id``. """ project_id: str = proto.Field( @@ -298,11 +287,6 @@ class BigQueryRoutineReference(proto.Message): proto.STRING, number=3, ) - boundary_location_id: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) class ExampleQuery(proto.Message): @@ -484,6 +468,19 @@ class LookerQuery(proto.Message): Optional. Limit in the query. This field is a member of `oneof`_ ``_limit``. + query_id (str): + Optional. The primary identifier for the query resource in + Looker, used for API operations. Maps to ``id`` (or + ``slug``) in the Looker API ``Query`` resource. + + This field is a member of `oneof`_ ``_query_id``. + client_id (str): + Optional. The short alphanumeric identifier for the query, + used for share links and Explore URLs (e.g., in the ``qid`` + parameter). Maps to ``client_id`` in the Looker API + ``Query`` resource. + + This field is a member of `oneof`_ ``_client_id``. """ class Filter(proto.Message): @@ -539,6 +536,16 @@ class Filter(proto.Message): number=6, optional=True, ) + query_id: str = proto.Field( + proto.STRING, + number=10, + optional=True, + ) + client_id: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) class GlossaryTerm(proto.Message): @@ -578,13 +585,38 @@ class GlossaryTerm(proto.Message): class ConversationOptions(proto.Message): r"""Options for the conversation. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: analysis (google.cloud.geminidataanalytics_v1.types.AnalysisOptions): Optional. Options for analysis. datasource (google.cloud.geminidataanalytics_v1.types.DatasourceOptions): Optional. Options for datasources. + model (google.cloud.geminidataanalytics_v1.types.ConversationOptions.Model): + Optional. The model to use for the agent + loop. + + This field is a member of `oneof`_ ``_model``. """ + class Model(proto.Enum): + r"""Allowed models for the agent/conversation. + + Values: + MODEL_UNSPECIFIED (0): + No model specified. The model may be set on the chat + request, or the default model will be used. Currently, this + is ``gemini-3.0-flash-preview``. + LATEST_GA_MODEL (1): + Use the most up-to-date non-preview model. Currently, this + is ``gemini-2.5-flash``. This constrains the request level + settings. The default will change to ``gemini-2.5-flash``, + and setting ``thinking_mode`` will not be supported. + """ + + MODEL_UNSPECIFIED = 0 + LATEST_GA_MODEL = 1 + analysis: "AnalysisOptions" = proto.Field( proto.MESSAGE, number=2, @@ -595,6 +627,12 @@ class ConversationOptions(proto.Message): number=3, message="DatasourceOptions", ) + model: Model = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=Model, + ) class DatasourceOptions(proto.Message): diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py index 908a15cfa7f6..11eb63ff0551 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/data_chat_service.py @@ -35,6 +35,7 @@ "ConversationReference", "ClientManagedResourceContext", "Message", + "LookerSettings", "UserMessage", "SystemMessage", "TextMessage", @@ -189,6 +190,10 @@ class ChatRequest(proto.Message): conversations and agents resources. This field is a member of `oneof`_ ``context_provider``. + looker_settings (google.cloud.geminidataanalytics_v1.types.LookerSettings): + Optional. Looker specific settings. + + This field is a member of `oneof`_ ``datasource_settings``. parent (str): Required. The parent value for chat request. Pattern: ``projects/{project}/locations/{location}`` @@ -206,6 +211,11 @@ class ChatRequest(proto.Message): thinking_mode (google.cloud.geminidataanalytics_v1.types.ChatRequest.ThinkingMode): Optional. The thinking mode to use for the agent loop. Defaults to THINKING_MODE_UNSPECIFIED if not specified. + model (google.cloud.geminidataanalytics_v1.types.ChatRequest.Model): + Optional. The model to use for the agent loop + when processing the request. This setting only + has an effect when context.options.model is not + set. """ class ThinkingMode(proto.Enum): @@ -225,6 +235,23 @@ class ThinkingMode(proto.Enum): FAST = 1 THINKING = 2 + class Model(proto.Enum): + r"""Model selection for the agent. + + Values: + MODEL_UNSPECIFIED (0): + No model specified. The default model will be used. + Currently, this is ``gemini-3.0-flash-preview``. + LATEST_GA_MODEL (1): + Use the most up-to-date non-preview model. Currently, this + is ``gemini-2.5-flash``. This constrains the request level + settings. The default will change to ``gemini-2.5-flash``, + and setting ``thinking_mode`` will not be supported. + """ + + MODEL_UNSPECIFIED = 0 + LATEST_GA_MODEL = 1 + inline_context: context.Context = proto.Field( proto.MESSAGE, number=101, @@ -249,6 +276,12 @@ class ThinkingMode(proto.Enum): oneof="context_provider", message="ClientManagedResourceContext", ) + looker_settings: "LookerSettings" = proto.Field( + proto.MESSAGE, + number=13, + oneof="datasource_settings", + message="LookerSettings", + ) parent: str = proto.Field( proto.STRING, number=3, @@ -268,6 +301,11 @@ class ThinkingMode(proto.Enum): number=9, enum=ThinkingMode, ) + model: Model = proto.Field( + proto.ENUM, + number=11, + enum=Model, + ) class DataAgentContext(proto.Message): @@ -424,6 +462,28 @@ class Message(proto.Message): ) +class LookerSettings(proto.Message): + r"""Message to hold Looker specific custom settings. + + Attributes: + enable_dev_mode (bool): + Optional. Whether to operate in Looker's + Development Mode. If true, the API session will + be switched to the "dev" workspace, allowing + interaction with LookML changes in the user's + development branch. If false or unset, the + session remains in the default state (Production + Mode). + See + https://cloud.google.com/looker/docs/dev-mode-prod-mode. + """ + + enable_dev_mode: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class UserMessage(proto.Message): r"""A message from the user that is interacting with the system. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/datasource.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/datasource.py index d2c1b7352ef9..ecf87e2ef9f9 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/datasource.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1/types/datasource.py @@ -124,8 +124,6 @@ class BigQueryTableReferences(proto.Message): class BigQueryTableReference(proto.Message): r"""Message representing a reference to a single BigQuery table. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: project_id (str): Required. The project that the table belongs @@ -137,15 +135,6 @@ class BigQueryTableReference(proto.Message): Required. The table id. schema (google.cloud.geminidataanalytics_v1.types.Schema): Optional. The schema of the datasource. - location_boundary (str): - Optional. The location to restrict BigQuery - operations to. - If unspecified, this value defaults to the - location of the endpoint. - - Examples: "us-central1", "europe-west1". - - This field is a member of `oneof`_ ``_location_boundary``. """ project_id: str = proto.Field( @@ -165,11 +154,6 @@ class BigQueryTableReference(proto.Message): number=6, message="Schema", ) - location_boundary: str = proto.Field( - proto.STRING, - number=7, - optional=True, - ) class StudioDatasourceReferences(proto.Message): @@ -282,9 +266,6 @@ class BigQueryPropertyGraphReference(proto.Message): r"""Message representing a reference to a single BigQuery property graph. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - Attributes: project_id (str): Required. The project that the property graph @@ -294,10 +275,6 @@ class BigQueryPropertyGraphReference(proto.Message): belongs to. property_graph_id (str): Required. The property graph id. - location_boundary (str): - Optional. The location boundary of the graph. - - This field is a member of `oneof`_ ``_location_boundary``. """ project_id: str = proto.Field( @@ -312,11 +289,6 @@ class BigQueryPropertyGraphReference(proto.Message): proto.STRING, number=3, ) - location_boundary: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) class PrivateLookerInstanceInfo(proto.Message): diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py index 1eb657312a46..1a1f6af2bd50 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1/test_data_agent_service.py @@ -9212,7 +9212,6 @@ def test_create_data_agent_rest_call_success(request_type): } ], }, - "location_boundary": "location_boundary_value", } ] }, @@ -9237,6 +9236,7 @@ def test_create_data_agent_rest_call_success(request_type): "options": { "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { @@ -9266,6 +9266,8 @@ def test_create_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -9294,7 +9296,6 @@ def test_create_data_agent_rest_call_success(request_type): "project_id": "project_id_value", "dataset_id": "dataset_id_value", "routine_id": "routine_id_value", - "boundary_location_id": "boundary_location_id_value", }, "description": "description_value", } @@ -9548,7 +9549,6 @@ def test_create_data_agent_sync_rest_call_success(request_type): } ], }, - "location_boundary": "location_boundary_value", } ] }, @@ -9573,6 +9573,7 @@ def test_create_data_agent_sync_rest_call_success(request_type): "options": { "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { @@ -9602,6 +9603,8 @@ def test_create_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -9630,7 +9633,6 @@ def test_create_data_agent_sync_rest_call_success(request_type): "project_id": "project_id_value", "dataset_id": "dataset_id_value", "routine_id": "routine_id_value", - "boundary_location_id": "boundary_location_id_value", }, "description": "description_value", } @@ -9899,7 +9901,6 @@ def test_update_data_agent_rest_call_success(request_type): } ], }, - "location_boundary": "location_boundary_value", } ] }, @@ -9924,6 +9925,7 @@ def test_update_data_agent_rest_call_success(request_type): "options": { "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { @@ -9953,6 +9955,8 @@ def test_update_data_agent_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -9981,7 +9985,6 @@ def test_update_data_agent_rest_call_success(request_type): "project_id": "project_id_value", "dataset_id": "dataset_id_value", "routine_id": "routine_id_value", - "boundary_location_id": "boundary_location_id_value", }, "description": "description_value", } @@ -10239,7 +10242,6 @@ def test_update_data_agent_sync_rest_call_success(request_type): } ], }, - "location_boundary": "location_boundary_value", } ] }, @@ -10264,6 +10266,7 @@ def test_update_data_agent_sync_rest_call_success(request_type): "options": { "analysis": {"python": {"enabled": True}}, "datasource": {"big_query_max_billed_bytes": {"value": 541}}, + "model": 1, }, "example_queries": [ { @@ -10293,6 +10296,8 @@ def test_update_data_agent_sync_rest_call_success(request_type): ], "sorts": ["sorts_value1", "sorts_value2"], "limit": "limit_value", + "query_id": "query_id_value", + "client_id": "client_id_value", }, } ], @@ -10321,7 +10326,6 @@ def test_update_data_agent_sync_rest_call_success(request_type): "project_id": "project_id_value", "dataset_id": "dataset_id_value", "routine_id": "routine_id_value", - "boundary_location_id": "boundary_location_id_value", }, "description": "description_value", } diff --git a/packages/google-cloud-network-security/docs/network_security_v1/security_profile_group_service.rst b/packages/google-cloud-network-security/docs/network_security_v1/security_profile_group_service.rst new file mode 100644 index 000000000000..7d3ef8258b96 --- /dev/null +++ b/packages/google-cloud-network-security/docs/network_security_v1/security_profile_group_service.rst @@ -0,0 +1,10 @@ +SecurityProfileGroupService +--------------------------------------------- + +.. automodule:: google.cloud.network_security_v1.services.security_profile_group_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1.services.security_profile_group_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-network-security/docs/network_security_v1/services_.rst b/packages/google-cloud-network-security/docs/network_security_v1/services_.rst index 9f39de9f1ac7..cdf9c9175f83 100644 --- a/packages/google-cloud-network-security/docs/network_security_v1/services_.rst +++ b/packages/google-cloud-network-security/docs/network_security_v1/services_.rst @@ -11,3 +11,5 @@ Services for Google Cloud Network Security v1 API network_security organization_address_group_service organization_security_profile_group_service + security_profile_group_service + sse_realm_service diff --git a/packages/google-cloud-network-security/docs/network_security_v1/sse_realm_service.rst b/packages/google-cloud-network-security/docs/network_security_v1/sse_realm_service.rst new file mode 100644 index 000000000000..c319094ec6ed --- /dev/null +++ b/packages/google-cloud-network-security/docs/network_security_v1/sse_realm_service.rst @@ -0,0 +1,10 @@ +SSERealmService +--------------------------------- + +.. automodule:: google.cloud.network_security_v1.services.sse_realm_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1.services.sse_realm_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-network-security/google/cloud/network_security/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security/__init__.py index 2e6163743d30..16d854ce9f54 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security/__init__.py @@ -62,6 +62,18 @@ from google.cloud.network_security_v1.services.organization_security_profile_group_service.client import ( OrganizationSecurityProfileGroupServiceClient, ) +from google.cloud.network_security_v1.services.security_profile_group_service.async_client import ( + SecurityProfileGroupServiceAsyncClient, +) +from google.cloud.network_security_v1.services.security_profile_group_service.client import ( + SecurityProfileGroupServiceClient, +) +from google.cloud.network_security_v1.services.sse_realm_service.async_client import ( + SSERealmServiceAsyncClient, +) +from google.cloud.network_security_v1.services.sse_realm_service.client import ( + SSERealmServiceClient, +) from google.cloud.network_security_v1.types.address_group import ( AddAddressGroupItemsRequest, AddressGroup, @@ -265,6 +277,20 @@ ServerTlsPolicy, UpdateServerTlsPolicyRequest, ) +from google.cloud.network_security_v1.types.sse_realm import ( + CreateSACAttachmentRequest, + CreateSACRealmRequest, + DeleteSACAttachmentRequest, + DeleteSACRealmRequest, + GetSACAttachmentRequest, + GetSACRealmRequest, + ListSACAttachmentsRequest, + ListSACAttachmentsResponse, + ListSACRealmsRequest, + ListSACRealmsResponse, + SACAttachment, + SACRealm, +) from google.cloud.network_security_v1.types.tls import ( CertificateProvider, CertificateProviderInstance, @@ -307,6 +333,10 @@ "OrganizationAddressGroupServiceAsyncClient", "OrganizationSecurityProfileGroupServiceClient", "OrganizationSecurityProfileGroupServiceAsyncClient", + "SecurityProfileGroupServiceClient", + "SecurityProfileGroupServiceAsyncClient", + "SSERealmServiceClient", + "SSERealmServiceAsyncClient", "AddAddressGroupItemsRequest", "AddressGroup", "CloneAddressGroupItemsRequest", @@ -474,6 +504,18 @@ "ListServerTlsPoliciesResponse", "ServerTlsPolicy", "UpdateServerTlsPolicyRequest", + "CreateSACAttachmentRequest", + "CreateSACRealmRequest", + "DeleteSACAttachmentRequest", + "DeleteSACRealmRequest", + "GetSACAttachmentRequest", + "GetSACRealmRequest", + "ListSACAttachmentsRequest", + "ListSACAttachmentsResponse", + "ListSACRealmsRequest", + "ListSACRealmsResponse", + "SACAttachment", + "SACRealm", "CertificateProvider", "CertificateProviderInstance", "GrpcEndpoint", diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py index 45974090cf3f..962e4da8b6ad 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py @@ -46,6 +46,14 @@ OrganizationSecurityProfileGroupServiceAsyncClient, OrganizationSecurityProfileGroupServiceClient, ) +from .services.security_profile_group_service import ( + SecurityProfileGroupServiceAsyncClient, + SecurityProfileGroupServiceClient, +) +from .services.sse_realm_service import ( + SSERealmServiceAsyncClient, + SSERealmServiceClient, +) from .types.address_group import ( AddAddressGroupItemsRequest, AddressGroup, @@ -239,6 +247,20 @@ ServerTlsPolicy, UpdateServerTlsPolicyRequest, ) +from .types.sse_realm import ( + CreateSACAttachmentRequest, + CreateSACRealmRequest, + DeleteSACAttachmentRequest, + DeleteSACRealmRequest, + GetSACAttachmentRequest, + GetSACRealmRequest, + ListSACAttachmentsRequest, + ListSACAttachmentsResponse, + ListSACRealmsRequest, + ListSACRealmsResponse, + SACAttachment, + SACRealm, +) from .types.tls import ( CertificateProvider, CertificateProviderInstance, @@ -356,6 +378,8 @@ def _get_version(dependency_name): "NetworkSecurityAsyncClient", "OrganizationAddressGroupServiceAsyncClient", "OrganizationSecurityProfileGroupServiceAsyncClient", + "SSERealmServiceAsyncClient", + "SecurityProfileGroupServiceAsyncClient", "AddAddressGroupItemsRequest", "AddressGroup", "AddressGroupServiceClient", @@ -385,6 +409,8 @@ def _get_version(dependency_name): "CreateMirroringDeploymentRequest", "CreateMirroringEndpointGroupAssociationRequest", "CreateMirroringEndpointGroupRequest", + "CreateSACAttachmentRequest", + "CreateSACRealmRequest", "CreateSecurityProfileGroupRequest", "CreateSecurityProfileRequest", "CreateServerTlsPolicyRequest", @@ -410,6 +436,8 @@ def _get_version(dependency_name): "DeleteMirroringDeploymentRequest", "DeleteMirroringEndpointGroupAssociationRequest", "DeleteMirroringEndpointGroupRequest", + "DeleteSACAttachmentRequest", + "DeleteSACRealmRequest", "DeleteSecurityProfileGroupRequest", "DeleteSecurityProfileRequest", "DeleteServerTlsPolicyRequest", @@ -440,6 +468,8 @@ def _get_version(dependency_name): "GetMirroringDeploymentRequest", "GetMirroringEndpointGroupAssociationRequest", "GetMirroringEndpointGroupRequest", + "GetSACAttachmentRequest", + "GetSACRealmRequest", "GetSecurityProfileGroupRequest", "GetSecurityProfileRequest", "GetServerTlsPolicyRequest", @@ -490,6 +520,10 @@ def _get_version(dependency_name): "ListMirroringEndpointGroupAssociationsResponse", "ListMirroringEndpointGroupsRequest", "ListMirroringEndpointGroupsResponse", + "ListSACAttachmentsRequest", + "ListSACAttachmentsResponse", + "ListSACRealmsRequest", + "ListSACRealmsResponse", "ListSecurityProfileGroupsRequest", "ListSecurityProfileGroupsResponse", "ListSecurityProfilesRequest", @@ -512,8 +546,12 @@ def _get_version(dependency_name): "OrganizationSecurityProfileGroupServiceClient", "Protocol", "RemoveAddressGroupItemsRequest", + "SACAttachment", + "SACRealm", + "SSERealmServiceClient", "SecurityProfile", "SecurityProfileGroup", + "SecurityProfileGroupServiceClient", "ServerTlsPolicy", "Severity", "SeverityOverride", diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json index 021aab45fdbf..64cdde77e4f8 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json @@ -268,6 +268,11 @@ "create_firewall_endpoint_association" ] }, + "CreateProjectFirewallEndpoint": { + "methods": [ + "create_project_firewall_endpoint" + ] + }, "DeleteFirewallEndpoint": { "methods": [ "delete_firewall_endpoint" @@ -278,6 +283,11 @@ "delete_firewall_endpoint_association" ] }, + "DeleteProjectFirewallEndpoint": { + "methods": [ + "delete_project_firewall_endpoint" + ] + }, "GetFirewallEndpoint": { "methods": [ "get_firewall_endpoint" @@ -288,6 +298,11 @@ "get_firewall_endpoint_association" ] }, + "GetProjectFirewallEndpoint": { + "methods": [ + "get_project_firewall_endpoint" + ] + }, "ListFirewallEndpointAssociations": { "methods": [ "list_firewall_endpoint_associations" @@ -298,6 +313,11 @@ "list_firewall_endpoints" ] }, + "ListProjectFirewallEndpoints": { + "methods": [ + "list_project_firewall_endpoints" + ] + }, "UpdateFirewallEndpoint": { "methods": [ "update_firewall_endpoint" @@ -307,6 +327,11 @@ "methods": [ "update_firewall_endpoint_association" ] + }, + "UpdateProjectFirewallEndpoint": { + "methods": [ + "update_project_firewall_endpoint" + ] } } }, @@ -323,6 +348,11 @@ "create_firewall_endpoint_association" ] }, + "CreateProjectFirewallEndpoint": { + "methods": [ + "create_project_firewall_endpoint" + ] + }, "DeleteFirewallEndpoint": { "methods": [ "delete_firewall_endpoint" @@ -333,6 +363,11 @@ "delete_firewall_endpoint_association" ] }, + "DeleteProjectFirewallEndpoint": { + "methods": [ + "delete_project_firewall_endpoint" + ] + }, "GetFirewallEndpoint": { "methods": [ "get_firewall_endpoint" @@ -343,6 +378,11 @@ "get_firewall_endpoint_association" ] }, + "GetProjectFirewallEndpoint": { + "methods": [ + "get_project_firewall_endpoint" + ] + }, "ListFirewallEndpointAssociations": { "methods": [ "list_firewall_endpoint_associations" @@ -353,6 +393,11 @@ "list_firewall_endpoints" ] }, + "ListProjectFirewallEndpoints": { + "methods": [ + "list_project_firewall_endpoints" + ] + }, "UpdateFirewallEndpoint": { "methods": [ "update_firewall_endpoint" @@ -362,6 +407,11 @@ "methods": [ "update_firewall_endpoint_association" ] + }, + "UpdateProjectFirewallEndpoint": { + "methods": [ + "update_project_firewall_endpoint" + ] } } }, @@ -378,6 +428,11 @@ "create_firewall_endpoint_association" ] }, + "CreateProjectFirewallEndpoint": { + "methods": [ + "create_project_firewall_endpoint" + ] + }, "DeleteFirewallEndpoint": { "methods": [ "delete_firewall_endpoint" @@ -388,6 +443,11 @@ "delete_firewall_endpoint_association" ] }, + "DeleteProjectFirewallEndpoint": { + "methods": [ + "delete_project_firewall_endpoint" + ] + }, "GetFirewallEndpoint": { "methods": [ "get_firewall_endpoint" @@ -398,6 +458,11 @@ "get_firewall_endpoint_association" ] }, + "GetProjectFirewallEndpoint": { + "methods": [ + "get_project_firewall_endpoint" + ] + }, "ListFirewallEndpointAssociations": { "methods": [ "list_firewall_endpoint_associations" @@ -408,6 +473,11 @@ "list_firewall_endpoints" ] }, + "ListProjectFirewallEndpoints": { + "methods": [ + "list_project_firewall_endpoints" + ] + }, "UpdateFirewallEndpoint": { "methods": [ "update_firewall_endpoint" @@ -417,6 +487,11 @@ "methods": [ "update_firewall_endpoint_association" ] + }, + "UpdateProjectFirewallEndpoint": { + "methods": [ + "update_project_firewall_endpoint" + ] } } } @@ -2076,6 +2151,314 @@ } } } + }, + "SSERealmService": { + "clients": { + "grpc": { + "libraryClient": "SSERealmServiceClient", + "rpcs": { + "CreateSACAttachment": { + "methods": [ + "create_sac_attachment" + ] + }, + "CreateSACRealm": { + "methods": [ + "create_sac_realm" + ] + }, + "DeleteSACAttachment": { + "methods": [ + "delete_sac_attachment" + ] + }, + "DeleteSACRealm": { + "methods": [ + "delete_sac_realm" + ] + }, + "GetSACAttachment": { + "methods": [ + "get_sac_attachment" + ] + }, + "GetSACRealm": { + "methods": [ + "get_sac_realm" + ] + }, + "ListSACAttachments": { + "methods": [ + "list_sac_attachments" + ] + }, + "ListSACRealms": { + "methods": [ + "list_sac_realms" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SSERealmServiceAsyncClient", + "rpcs": { + "CreateSACAttachment": { + "methods": [ + "create_sac_attachment" + ] + }, + "CreateSACRealm": { + "methods": [ + "create_sac_realm" + ] + }, + "DeleteSACAttachment": { + "methods": [ + "delete_sac_attachment" + ] + }, + "DeleteSACRealm": { + "methods": [ + "delete_sac_realm" + ] + }, + "GetSACAttachment": { + "methods": [ + "get_sac_attachment" + ] + }, + "GetSACRealm": { + "methods": [ + "get_sac_realm" + ] + }, + "ListSACAttachments": { + "methods": [ + "list_sac_attachments" + ] + }, + "ListSACRealms": { + "methods": [ + "list_sac_realms" + ] + } + } + }, + "rest": { + "libraryClient": "SSERealmServiceClient", + "rpcs": { + "CreateSACAttachment": { + "methods": [ + "create_sac_attachment" + ] + }, + "CreateSACRealm": { + "methods": [ + "create_sac_realm" + ] + }, + "DeleteSACAttachment": { + "methods": [ + "delete_sac_attachment" + ] + }, + "DeleteSACRealm": { + "methods": [ + "delete_sac_realm" + ] + }, + "GetSACAttachment": { + "methods": [ + "get_sac_attachment" + ] + }, + "GetSACRealm": { + "methods": [ + "get_sac_realm" + ] + }, + "ListSACAttachments": { + "methods": [ + "list_sac_attachments" + ] + }, + "ListSACRealms": { + "methods": [ + "list_sac_realms" + ] + } + } + } + } + }, + "SecurityProfileGroupService": { + "clients": { + "grpc": { + "libraryClient": "SecurityProfileGroupServiceClient", + "rpcs": { + "CreateSecurityProfile": { + "methods": [ + "create_security_profile" + ] + }, + "CreateSecurityProfileGroup": { + "methods": [ + "create_security_profile_group" + ] + }, + "DeleteSecurityProfile": { + "methods": [ + "delete_security_profile" + ] + }, + "DeleteSecurityProfileGroup": { + "methods": [ + "delete_security_profile_group" + ] + }, + "GetSecurityProfile": { + "methods": [ + "get_security_profile" + ] + }, + "GetSecurityProfileGroup": { + "methods": [ + "get_security_profile_group" + ] + }, + "ListSecurityProfileGroups": { + "methods": [ + "list_security_profile_groups" + ] + }, + "ListSecurityProfiles": { + "methods": [ + "list_security_profiles" + ] + }, + "UpdateSecurityProfile": { + "methods": [ + "update_security_profile" + ] + }, + "UpdateSecurityProfileGroup": { + "methods": [ + "update_security_profile_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityProfileGroupServiceAsyncClient", + "rpcs": { + "CreateSecurityProfile": { + "methods": [ + "create_security_profile" + ] + }, + "CreateSecurityProfileGroup": { + "methods": [ + "create_security_profile_group" + ] + }, + "DeleteSecurityProfile": { + "methods": [ + "delete_security_profile" + ] + }, + "DeleteSecurityProfileGroup": { + "methods": [ + "delete_security_profile_group" + ] + }, + "GetSecurityProfile": { + "methods": [ + "get_security_profile" + ] + }, + "GetSecurityProfileGroup": { + "methods": [ + "get_security_profile_group" + ] + }, + "ListSecurityProfileGroups": { + "methods": [ + "list_security_profile_groups" + ] + }, + "ListSecurityProfiles": { + "methods": [ + "list_security_profiles" + ] + }, + "UpdateSecurityProfile": { + "methods": [ + "update_security_profile" + ] + }, + "UpdateSecurityProfileGroup": { + "methods": [ + "update_security_profile_group" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityProfileGroupServiceClient", + "rpcs": { + "CreateSecurityProfile": { + "methods": [ + "create_security_profile" + ] + }, + "CreateSecurityProfileGroup": { + "methods": [ + "create_security_profile_group" + ] + }, + "DeleteSecurityProfile": { + "methods": [ + "delete_security_profile" + ] + }, + "DeleteSecurityProfileGroup": { + "methods": [ + "delete_security_profile_group" + ] + }, + "GetSecurityProfile": { + "methods": [ + "get_security_profile" + ] + }, + "GetSecurityProfileGroup": { + "methods": [ + "get_security_profile_group" + ] + }, + "ListSecurityProfileGroups": { + "methods": [ + "list_security_profile_groups" + ] + }, + "ListSecurityProfiles": { + "methods": [ + "list_security_profiles" + ] + }, + "UpdateSecurityProfile": { + "methods": [ + "update_security_profile" + ] + }, + "UpdateSecurityProfileGroup": { + "methods": [ + "update_security_profile_group" + ] + } + } + } + } } } } diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py index 703cd182c7d1..88e756cbc3ea 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py @@ -611,7 +611,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -642,10 +642,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -689,11 +685,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -742,12 +733,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/dns_threat_detector_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/dns_threat_detector_service/transports/rest_base.py index 1acf71ebb4aa..191ccf335e39 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/dns_threat_detector_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/dns_threat_detector_service/transports/rest_base.py @@ -398,7 +398,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -429,10 +429,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -476,11 +472,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -529,12 +520,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/async_client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/async_client.py index 4045e88af29d..cfb33aede5de 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/async_client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/async_client.py @@ -458,18 +458,657 @@ async def sample_list_firewall_endpoints(): # Done; return the response. return response + async def list_project_firewall_endpoints( + self, + request: Optional[ + Union[firewall_activation.ListFirewallEndpointsRequest, 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.ListProjectFirewallEndpointsAsyncPager: + r"""Lists FirewallEndpoints in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_project_firewall_endpoints(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListFirewallEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_project_firewall_endpoints(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListFirewallEndpointsRequest, dict]]): + The request object. Message for requesting list of + Endpoints + parent (:class:`str`): + Required. Parent value for + ListEndpointsRequest + + 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.network_security_v1.services.firewall_activation.pagers.ListProjectFirewallEndpointsAsyncPager: + Message for response to listing + Endpoints + 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, firewall_activation.ListFirewallEndpointsRequest): + request = firewall_activation.ListFirewallEndpointsRequest(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_project_firewall_endpoints + ] + + # 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.ListProjectFirewallEndpointsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.GetFirewallEndpointRequest, dict] + Union[firewall_activation.GetFirewallEndpointRequest, 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]]] = (), + ) -> firewall_activation.FirewallEndpoint: + r"""Gets details of a single org Endpoint. + + .. 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 network_security_v1 + + async def sample_get_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = await client.get_firewall_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]]): + The request object. Message for getting a Endpoint + name (:class:`str`): + Required. Name of the resource + 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.network_security_v1.types.FirewallEndpoint: + Message describing Endpoint object. + """ + # 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, firewall_activation.GetFirewallEndpointRequest): + request = firewall_activation.GetFirewallEndpointRequest(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_firewall_endpoint + ] + + # 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_project_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.GetFirewallEndpointRequest, 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]]] = (), + ) -> firewall_activation.FirewallEndpoint: + r"""Gets details of a single project Endpoint. + + .. 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 network_security_v1 + + async def sample_get_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = await client.get_project_firewall_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]]): + The request object. Message for getting a Endpoint + name (:class:`str`): + Required. Name of the resource + 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.network_security_v1.types.FirewallEndpoint: + Message describing Endpoint object. + """ + # 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, firewall_activation.GetFirewallEndpointRequest): + request = firewall_activation.GetFirewallEndpointRequest(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_project_firewall_endpoint + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.CreateFirewallEndpointRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, + firewall_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new FirewallEndpoint in a given + organization and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = await client.create_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]]): + The request object. Message for creating a Endpoint + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint (:class:`google.cloud.network_security_v1.types.FirewallEndpoint`): + Required. The resource being created + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint_id (:class:`str`): + Required. Id of the requesting object. If + auto-generating Id server-side, remove this field and + firewall_endpoint_id from the method_signature of Create + RPC. + + This corresponds to the ``firewall_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. + + """ + # 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, firewall_endpoint, firewall_endpoint_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, firewall_activation.CreateFirewallEndpointRequest): + request = firewall_activation.CreateFirewallEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + if firewall_endpoint_id is not None: + request.firewall_endpoint_id = firewall_endpoint_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_firewall_endpoint + ] + + # 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, + firewall_activation.FirewallEndpoint, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_project_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.CreateFirewallEndpointRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, + firewall_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new FirewallEndpoint in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = await client.create_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]]): + The request object. Message for creating a Endpoint + parent (:class:`str`): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint (:class:`google.cloud.network_security_v1.types.FirewallEndpoint`): + Required. The resource being created + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint_id (:class:`str`): + Required. Id of the requesting object. If + auto-generating Id server-side, remove this field and + firewall_endpoint_id from the method_signature of Create + RPC. + + This corresponds to the ``firewall_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. + + """ + # 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, firewall_endpoint, firewall_endpoint_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, firewall_activation.CreateFirewallEndpointRequest): + request = firewall_activation.CreateFirewallEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + if firewall_endpoint_id is not None: + request.firewall_endpoint_id = firewall_endpoint_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_project_firewall_endpoint + ] + + # 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, + firewall_activation.FirewallEndpoint, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.DeleteFirewallEndpointRequest, 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]]] = (), - ) -> firewall_activation.FirewallEndpoint: - r"""Gets details of a single org Endpoint. + ) -> operation_async.AsyncOperation: + r"""Deletes a single org Endpoint. .. code-block:: python @@ -482,24 +1121,28 @@ async def get_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - async def sample_get_firewall_endpoint(): + async def sample_delete_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationAsyncClient() # Initialize request argument(s) - request = network_security_v1.GetFirewallEndpointRequest( + request = network_security_v1.DeleteFirewallEndpointRequest( name="name_value", ) # Make the request - response = await client.get_firewall_endpoint(request=request) + operation = await client.delete_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() # Handle the response print(response) Args: - request (Optional[Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]]): - The request object. Message for getting a Endpoint + request (Optional[Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]]): + The request object. Message for deleting a Endpoint name (:class:`str`): Required. Name of the resource This corresponds to the ``name`` field @@ -514,8 +1157,20 @@ async def sample_get_firewall_endpoint(): be of type `bytes`. Returns: - google.cloud.network_security_v1.types.FirewallEndpoint: - Message describing Endpoint object. + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -532,8 +1187,8 @@ async def sample_get_firewall_endpoint(): # - 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, firewall_activation.GetFirewallEndpointRequest): - request = firewall_activation.GetFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.DeleteFirewallEndpointRequest): + request = firewall_activation.DeleteFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -543,7 +1198,7 @@ async def sample_get_firewall_endpoint(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_firewall_endpoint + self._client._transport.delete_firewall_endpoint ] # Certain fields should be provided within the metadata header; @@ -563,24 +1218,29 @@ async def sample_get_firewall_endpoint(): metadata=metadata, ) + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + # Done; return the response. return response - async def create_firewall_endpoint( + async def delete_project_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.CreateFirewallEndpointRequest, dict] + Union[firewall_activation.DeleteFirewallEndpointRequest, dict] ] = None, *, - parent: Optional[str] = None, - firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, - firewall_endpoint_id: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: - r"""Creates a new FirewallEndpoint in a given - organization and location. + r"""Deletes a single project Endpoint. .. code-block:: python @@ -593,18 +1253,17 @@ async def create_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - async def sample_create_firewall_endpoint(): + async def sample_delete_project_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationAsyncClient() # Initialize request argument(s) - request = network_security_v1.CreateFirewallEndpointRequest( - parent="parent_value", - firewall_endpoint_id="firewall_endpoint_id_value", + request = network_security_v1.DeleteFirewallEndpointRequest( + name="name_value", ) # Make the request - operation = await client.create_firewall_endpoint(request=request) + operation = await client.delete_project_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -614,25 +1273,11 @@ async def sample_create_firewall_endpoint(): print(response) Args: - request (Optional[Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]]): - The request object. Message for creating a Endpoint - parent (:class:`str`): - Required. Value for parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - firewall_endpoint (:class:`google.cloud.network_security_v1.types.FirewallEndpoint`): - Required. The resource being created - This corresponds to the ``firewall_endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - firewall_endpoint_id (:class:`str`): - Required. Id of the requesting object. If - auto-generating Id server-side, remove this field and - firewall_endpoint_id from the method_signature of Create - RPC. - - This corresponds to the ``firewall_endpoint_id`` field + request (Optional[Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]]): + The request object. Message for deleting a Endpoint + name (:class:`str`): + Required. Name of the resource + 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, @@ -647,15 +1292,22 @@ async def sample_create_firewall_endpoint(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be - :class:`google.cloud.network_security_v1.types.FirewallEndpoint` - Message describing Endpoint object. + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - flattened_params = [parent, firewall_endpoint, firewall_endpoint_id] + flattened_params = [name] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -667,28 +1319,24 @@ async def sample_create_firewall_endpoint(): # - 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, firewall_activation.CreateFirewallEndpointRequest): - request = firewall_activation.CreateFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.DeleteFirewallEndpointRequest): + request = firewall_activation.DeleteFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if firewall_endpoint is not None: - request.firewall_endpoint = firewall_endpoint - if firewall_endpoint_id is not None: - request.firewall_endpoint_id = firewall_endpoint_id + 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.create_firewall_endpoint + self._client._transport.delete_project_firewall_endpoint ] # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -706,25 +1354,26 @@ async def sample_create_firewall_endpoint(): response = operation_async.from_gapic( response, self._client._transport.operations_client, - firewall_activation.FirewallEndpoint, + empty_pb2.Empty, metadata_type=common.OperationMetadata, ) # Done; return the response. return response - async def delete_firewall_endpoint( + async def update_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.DeleteFirewallEndpointRequest, dict] + Union[firewall_activation.UpdateFirewallEndpointRequest, dict] ] = None, *, - name: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = 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]]] = (), ) -> operation_async.AsyncOperation: - r"""Deletes a single org Endpoint. + r"""Update a single org Endpoint. .. code-block:: python @@ -737,17 +1386,16 @@ async def delete_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - async def sample_delete_firewall_endpoint(): + async def sample_update_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationAsyncClient() # Initialize request argument(s) - request = network_security_v1.DeleteFirewallEndpointRequest( - name="name_value", + request = network_security_v1.UpdateFirewallEndpointRequest( ) # Make the request - operation = await client.delete_firewall_endpoint(request=request) + operation = await client.update_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -757,11 +1405,22 @@ async def sample_delete_firewall_endpoint(): print(response) Args: - request (Optional[Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]]): - The request object. Message for deleting a Endpoint - name (:class:`str`): - Required. Name of the resource - This corresponds to the ``name`` field + request (Optional[Union[google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest, dict]]): + The request object. Message for updating a Endpoint + firewall_endpoint (:class:`google.cloud.network_security_v1.types.FirewallEndpoint`): + Required. The resource being updated + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the Endpoint resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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, @@ -776,22 +1435,15 @@ async def sample_delete_firewall_endpoint(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. """ # 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] + flattened_params = [firewall_endpoint, update_mask] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -803,24 +1455,28 @@ async def sample_delete_firewall_endpoint(): # - 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, firewall_activation.DeleteFirewallEndpointRequest): - request = firewall_activation.DeleteFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.UpdateFirewallEndpointRequest): + request = firewall_activation.UpdateFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + 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.delete_firewall_endpoint + self._client._transport.update_firewall_endpoint ] # 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),)), + gapic_v1.routing_header.to_grpc_metadata( + (("firewall_endpoint.name", request.firewall_endpoint.name),) + ), ) # Validate the universe domain. @@ -838,14 +1494,14 @@ async def sample_delete_firewall_endpoint(): response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty_pb2.Empty, + firewall_activation.FirewallEndpoint, metadata_type=common.OperationMetadata, ) # Done; return the response. return response - async def update_firewall_endpoint( + async def update_project_firewall_endpoint( self, request: Optional[ Union[firewall_activation.UpdateFirewallEndpointRequest, dict] @@ -857,7 +1513,7 @@ async def update_firewall_endpoint( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: - r"""Update a single org Endpoint. + r"""Update a single project Endpoint. .. code-block:: python @@ -870,7 +1526,7 @@ async def update_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - async def sample_update_firewall_endpoint(): + async def sample_update_project_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationAsyncClient() @@ -879,7 +1535,7 @@ async def sample_update_firewall_endpoint(): ) # Make the request - operation = await client.update_firewall_endpoint(request=request) + operation = await client.update_project_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -952,7 +1608,7 @@ async def sample_update_firewall_endpoint(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_firewall_endpoint + self._client._transport.update_project_firewall_endpoint ] # Certain fields should be provided within the metadata header; diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/client.py index 383a2cd6b995..023f4213fd6e 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/client.py @@ -933,18 +933,648 @@ def sample_list_firewall_endpoints(): # Done; return the response. return response + def list_project_firewall_endpoints( + self, + request: Optional[ + Union[firewall_activation.ListFirewallEndpointsRequest, 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.ListProjectFirewallEndpointsPager: + r"""Lists FirewallEndpoints in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_project_firewall_endpoints(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.ListFirewallEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_project_firewall_endpoints(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListFirewallEndpointsRequest, dict]): + The request object. Message for requesting list of + Endpoints + parent (str): + Required. Parent value for + ListEndpointsRequest + + 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.network_security_v1.services.firewall_activation.pagers.ListProjectFirewallEndpointsPager: + Message for response to listing + Endpoints + 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, firewall_activation.ListFirewallEndpointsRequest): + request = firewall_activation.ListFirewallEndpointsRequest(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_project_firewall_endpoints + ] + + # 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.ListProjectFirewallEndpointsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def get_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.GetFirewallEndpointRequest, dict] + Union[firewall_activation.GetFirewallEndpointRequest, 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]]] = (), + ) -> firewall_activation.FirewallEndpoint: + r"""Gets details of a single org Endpoint. + + .. 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 network_security_v1 + + def sample_get_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = client.get_firewall_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]): + The request object. Message for getting a Endpoint + name (str): + Required. Name of the resource + 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.network_security_v1.types.FirewallEndpoint: + Message describing Endpoint object. + """ + # 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, firewall_activation.GetFirewallEndpointRequest): + request = firewall_activation.GetFirewallEndpointRequest(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_firewall_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_project_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.GetFirewallEndpointRequest, 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]]] = (), + ) -> firewall_activation.FirewallEndpoint: + r"""Gets details of a single project Endpoint. + + .. 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 network_security_v1 + + def sample_get_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = client.get_project_firewall_endpoint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]): + The request object. Message for getting a Endpoint + name (str): + Required. Name of the resource + 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.network_security_v1.types.FirewallEndpoint: + Message describing Endpoint object. + """ + # 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, firewall_activation.GetFirewallEndpointRequest): + request = firewall_activation.GetFirewallEndpointRequest(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_project_firewall_endpoint + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.CreateFirewallEndpointRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, + firewall_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new FirewallEndpoint in a given + organization and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = client.create_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]): + The request object. Message for creating a Endpoint + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint (google.cloud.network_security_v1.types.FirewallEndpoint): + Required. The resource being created + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint_id (str): + Required. Id of the requesting object. If + auto-generating Id server-side, remove this field and + firewall_endpoint_id from the method_signature of Create + RPC. + + This corresponds to the ``firewall_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. + + """ + # 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, firewall_endpoint, firewall_endpoint_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, firewall_activation.CreateFirewallEndpointRequest): + request = firewall_activation.CreateFirewallEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + if firewall_endpoint_id is not None: + request.firewall_endpoint_id = firewall_endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_firewall_endpoint] + + # 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, + firewall_activation.FirewallEndpoint, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_project_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.CreateFirewallEndpointRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, + firewall_endpoint_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new FirewallEndpoint in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = client.create_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]): + The request object. Message for creating a Endpoint + parent (str): + Required. Value for parent. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint (google.cloud.network_security_v1.types.FirewallEndpoint): + Required. The resource being created + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firewall_endpoint_id (str): + Required. Id of the requesting object. If + auto-generating Id server-side, remove this field and + firewall_endpoint_id from the method_signature of Create + RPC. + + This corresponds to the ``firewall_endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. + + """ + # 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, firewall_endpoint, firewall_endpoint_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, firewall_activation.CreateFirewallEndpointRequest): + request = firewall_activation.CreateFirewallEndpointRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + if firewall_endpoint_id is not None: + request.firewall_endpoint_id = firewall_endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_project_firewall_endpoint + ] + + # 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, + firewall_activation.FirewallEndpoint, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_firewall_endpoint( + self, + request: Optional[ + Union[firewall_activation.DeleteFirewallEndpointRequest, 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]]] = (), - ) -> firewall_activation.FirewallEndpoint: - r"""Gets details of a single org Endpoint. + ) -> operation.Operation: + r"""Deletes a single org Endpoint. .. code-block:: python @@ -957,24 +1587,28 @@ def get_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - def sample_get_firewall_endpoint(): + def sample_delete_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationClient() # Initialize request argument(s) - request = network_security_v1.GetFirewallEndpointRequest( + request = network_security_v1.DeleteFirewallEndpointRequest( name="name_value", ) # Make the request - response = client.get_firewall_endpoint(request=request) + operation = client.delete_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() # Handle the response print(response) Args: - request (Union[google.cloud.network_security_v1.types.GetFirewallEndpointRequest, dict]): - The request object. Message for getting a Endpoint + request (Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]): + The request object. Message for deleting a Endpoint name (str): Required. Name of the resource This corresponds to the ``name`` field @@ -989,8 +1623,20 @@ def sample_get_firewall_endpoint(): be of type `bytes`. Returns: - google.cloud.network_security_v1.types.FirewallEndpoint: - Message describing Endpoint object. + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -1007,8 +1653,8 @@ def sample_get_firewall_endpoint(): # - 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, firewall_activation.GetFirewallEndpointRequest): - request = firewall_activation.GetFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.DeleteFirewallEndpointRequest): + request = firewall_activation.DeleteFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -1016,7 +1662,7 @@ def sample_get_firewall_endpoint(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_firewall_endpoint] + rpc = self._transport._wrapped_methods[self._transport.delete_firewall_endpoint] # Certain fields should be provided within the metadata header; # add these here. @@ -1035,24 +1681,29 @@ def sample_get_firewall_endpoint(): metadata=metadata, ) + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + # Done; return the response. return response - def create_firewall_endpoint( + def delete_project_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.CreateFirewallEndpointRequest, dict] + Union[firewall_activation.DeleteFirewallEndpointRequest, dict] ] = None, *, - parent: Optional[str] = None, - firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = None, - firewall_endpoint_id: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: - r"""Creates a new FirewallEndpoint in a given - organization and location. + r"""Deletes a single project Endpoint. .. code-block:: python @@ -1065,18 +1716,17 @@ def create_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - def sample_create_firewall_endpoint(): + def sample_delete_project_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationClient() # Initialize request argument(s) - request = network_security_v1.CreateFirewallEndpointRequest( - parent="parent_value", - firewall_endpoint_id="firewall_endpoint_id_value", + request = network_security_v1.DeleteFirewallEndpointRequest( + name="name_value", ) # Make the request - operation = client.create_firewall_endpoint(request=request) + operation = client.delete_project_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -1086,25 +1736,11 @@ def sample_create_firewall_endpoint(): print(response) Args: - request (Union[google.cloud.network_security_v1.types.CreateFirewallEndpointRequest, dict]): - The request object. Message for creating a Endpoint - parent (str): - Required. Value for parent. - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - firewall_endpoint (google.cloud.network_security_v1.types.FirewallEndpoint): - Required. The resource being created - This corresponds to the ``firewall_endpoint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - firewall_endpoint_id (str): - Required. Id of the requesting object. If - auto-generating Id server-side, remove this field and - firewall_endpoint_id from the method_signature of Create - RPC. - - This corresponds to the ``firewall_endpoint_id`` field + request (Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]): + The request object. Message for deleting a Endpoint + name (str): + Required. Name of the resource + 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, @@ -1119,15 +1755,22 @@ def sample_create_firewall_endpoint(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be - :class:`google.cloud.network_security_v1.types.FirewallEndpoint` - Message describing Endpoint object. + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - flattened_params = [parent, firewall_endpoint, firewall_endpoint_id] + flattened_params = [name] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -1139,25 +1782,23 @@ def sample_create_firewall_endpoint(): # - 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, firewall_activation.CreateFirewallEndpointRequest): - request = firewall_activation.CreateFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.DeleteFirewallEndpointRequest): + request = firewall_activation.DeleteFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if firewall_endpoint is not None: - request.firewall_endpoint = firewall_endpoint - if firewall_endpoint_id is not None: - request.firewall_endpoint_id = firewall_endpoint_id + 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.create_firewall_endpoint] + rpc = self._transport._wrapped_methods[ + self._transport.delete_project_firewall_endpoint + ] # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1175,25 +1816,26 @@ def sample_create_firewall_endpoint(): response = operation.from_gapic( response, self._transport.operations_client, - firewall_activation.FirewallEndpoint, + empty_pb2.Empty, metadata_type=common.OperationMetadata, ) # Done; return the response. return response - def delete_firewall_endpoint( + def update_firewall_endpoint( self, request: Optional[ - Union[firewall_activation.DeleteFirewallEndpointRequest, dict] + Union[firewall_activation.UpdateFirewallEndpointRequest, dict] ] = None, *, - name: Optional[str] = None, + firewall_endpoint: Optional[firewall_activation.FirewallEndpoint] = 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]]] = (), ) -> operation.Operation: - r"""Deletes a single org Endpoint. + r"""Update a single org Endpoint. .. code-block:: python @@ -1206,17 +1848,16 @@ def delete_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - def sample_delete_firewall_endpoint(): + def sample_update_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationClient() # Initialize request argument(s) - request = network_security_v1.DeleteFirewallEndpointRequest( - name="name_value", + request = network_security_v1.UpdateFirewallEndpointRequest( ) # Make the request - operation = client.delete_firewall_endpoint(request=request) + operation = client.update_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -1226,11 +1867,22 @@ def sample_delete_firewall_endpoint(): print(response) Args: - request (Union[google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest, dict]): - The request object. Message for deleting a Endpoint - name (str): - Required. Name of the resource - This corresponds to the ``name`` field + request (Union[google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest, dict]): + The request object. Message for updating a Endpoint + firewall_endpoint (google.cloud.network_security_v1.types.FirewallEndpoint): + Required. The resource being updated + This corresponds to the ``firewall_endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the Endpoint resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + 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, @@ -1245,22 +1897,15 @@ def sample_delete_firewall_endpoint(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.FirewallEndpoint` + Message describing Endpoint object. """ # 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] + flattened_params = [firewall_endpoint, update_mask] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -1272,21 +1917,25 @@ def sample_delete_firewall_endpoint(): # - 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, firewall_activation.DeleteFirewallEndpointRequest): - request = firewall_activation.DeleteFirewallEndpointRequest(request) + if not isinstance(request, firewall_activation.UpdateFirewallEndpointRequest): + request = firewall_activation.UpdateFirewallEndpointRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if firewall_endpoint is not None: + request.firewall_endpoint = firewall_endpoint + 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.delete_firewall_endpoint] + rpc = self._transport._wrapped_methods[self._transport.update_firewall_endpoint] # 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),)), + gapic_v1.routing_header.to_grpc_metadata( + (("firewall_endpoint.name", request.firewall_endpoint.name),) + ), ) # Validate the universe domain. @@ -1304,14 +1953,14 @@ def sample_delete_firewall_endpoint(): response = operation.from_gapic( response, self._transport.operations_client, - empty_pb2.Empty, + firewall_activation.FirewallEndpoint, metadata_type=common.OperationMetadata, ) # Done; return the response. return response - def update_firewall_endpoint( + def update_project_firewall_endpoint( self, request: Optional[ Union[firewall_activation.UpdateFirewallEndpointRequest, dict] @@ -1323,7 +1972,7 @@ def update_firewall_endpoint( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: - r"""Update a single org Endpoint. + r"""Update a single project Endpoint. .. code-block:: python @@ -1336,7 +1985,7 @@ def update_firewall_endpoint( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import network_security_v1 - def sample_update_firewall_endpoint(): + def sample_update_project_firewall_endpoint(): # Create a client client = network_security_v1.FirewallActivationClient() @@ -1345,7 +1994,7 @@ def sample_update_firewall_endpoint(): ) # Make the request - operation = client.update_firewall_endpoint(request=request) + operation = client.update_project_firewall_endpoint(request=request) print("Waiting for operation to complete...") @@ -1416,7 +2065,9 @@ def sample_update_firewall_endpoint(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_firewall_endpoint] + rpc = self._transport._wrapped_methods[ + self._transport.update_project_firewall_endpoint + ] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/pagers.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/pagers.py index 9fcadac98098..bcdb994cec37 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/pagers.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/pagers.py @@ -201,6 +201,166 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListProjectFirewallEndpointsPager: + """A pager for iterating through ``list_project_firewall_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListFirewallEndpointsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``firewall_endpoints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProjectFirewallEndpoints`` requests and continue to iterate + through the ``firewall_endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListFirewallEndpointsResponse` + 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[..., firewall_activation.ListFirewallEndpointsResponse], + request: firewall_activation.ListFirewallEndpointsRequest, + response: firewall_activation.ListFirewallEndpointsResponse, + *, + 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.network_security_v1.types.ListFirewallEndpointsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListFirewallEndpointsResponse): + 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 = firewall_activation.ListFirewallEndpointsRequest(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[firewall_activation.ListFirewallEndpointsResponse]: + 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[firewall_activation.FirewallEndpoint]: + for page in self.pages: + yield from page.firewall_endpoints + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProjectFirewallEndpointsAsyncPager: + """A pager for iterating through ``list_project_firewall_endpoints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListFirewallEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``firewall_endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProjectFirewallEndpoints`` requests and continue to iterate + through the ``firewall_endpoints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListFirewallEndpointsResponse` + 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[firewall_activation.ListFirewallEndpointsResponse] + ], + request: firewall_activation.ListFirewallEndpointsRequest, + response: firewall_activation.ListFirewallEndpointsResponse, + *, + 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.network_security_v1.types.ListFirewallEndpointsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListFirewallEndpointsResponse): + 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 = firewall_activation.ListFirewallEndpointsRequest(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[firewall_activation.ListFirewallEndpointsResponse]: + 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[firewall_activation.FirewallEndpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.firewall_endpoints: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListFirewallEndpointAssociationsPager: """A pager for iterating through ``list_firewall_endpoint_associations`` requests. diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/base.py index cf77d0141955..d64acb781774 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/base.py @@ -153,26 +153,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_project_firewall_endpoints: gapic_v1.method.wrap_method( + self.list_project_firewall_endpoints, + default_timeout=None, + client_info=client_info, + ), self.get_firewall_endpoint: gapic_v1.method.wrap_method( self.get_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.get_project_firewall_endpoint: gapic_v1.method.wrap_method( + self.get_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.create_firewall_endpoint: gapic_v1.method.wrap_method( self.create_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.create_project_firewall_endpoint: gapic_v1.method.wrap_method( + self.create_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.delete_firewall_endpoint: gapic_v1.method.wrap_method( self.delete_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.delete_project_firewall_endpoint: gapic_v1.method.wrap_method( + self.delete_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.update_firewall_endpoint: gapic_v1.method.wrap_method( self.update_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.update_project_firewall_endpoint: gapic_v1.method.wrap_method( + self.update_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.list_firewall_endpoint_associations: gapic_v1.method.wrap_method( self.list_firewall_endpoint_associations, default_timeout=None, @@ -271,6 +296,18 @@ def list_firewall_endpoints( ]: raise NotImplementedError() + @property + def list_project_firewall_endpoints( + self, + ) -> Callable[ + [firewall_activation.ListFirewallEndpointsRequest], + Union[ + firewall_activation.ListFirewallEndpointsResponse, + Awaitable[firewall_activation.ListFirewallEndpointsResponse], + ], + ]: + raise NotImplementedError() + @property def get_firewall_endpoint( self, @@ -283,6 +320,18 @@ def get_firewall_endpoint( ]: raise NotImplementedError() + @property + def get_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.GetFirewallEndpointRequest], + Union[ + firewall_activation.FirewallEndpoint, + Awaitable[firewall_activation.FirewallEndpoint], + ], + ]: + raise NotImplementedError() + @property def create_firewall_endpoint( self, @@ -292,6 +341,15 @@ def create_firewall_endpoint( ]: raise NotImplementedError() + @property + def create_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.CreateFirewallEndpointRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def delete_firewall_endpoint( self, @@ -301,6 +359,15 @@ def delete_firewall_endpoint( ]: raise NotImplementedError() + @property + def delete_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.DeleteFirewallEndpointRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def update_firewall_endpoint( self, @@ -310,6 +377,15 @@ def update_firewall_endpoint( ]: raise NotImplementedError() + @property + def update_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.UpdateFirewallEndpointRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_firewall_endpoint_associations( self, diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc.py index a7e13b8d4b58..ee934cd205b7 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc.py @@ -378,6 +378,39 @@ def list_firewall_endpoints( ) return self._stubs["list_firewall_endpoints"] + @property + def list_project_firewall_endpoints( + self, + ) -> Callable[ + [firewall_activation.ListFirewallEndpointsRequest], + firewall_activation.ListFirewallEndpointsResponse, + ]: + r"""Return a callable for the list project firewall + endpoints method over gRPC. + + Lists FirewallEndpoints in a given project and + location. + + Returns: + Callable[[~.ListFirewallEndpointsRequest], + ~.ListFirewallEndpointsResponse]: + 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_project_firewall_endpoints" not in self._stubs: + self._stubs["list_project_firewall_endpoints"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/ListProjectFirewallEndpoints", + request_serializer=firewall_activation.ListFirewallEndpointsRequest.serialize, + response_deserializer=firewall_activation.ListFirewallEndpointsResponse.deserialize, + ) + ) + return self._stubs["list_project_firewall_endpoints"] + @property def get_firewall_endpoint( self, @@ -407,6 +440,37 @@ def get_firewall_endpoint( ) return self._stubs["get_firewall_endpoint"] + @property + def get_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.GetFirewallEndpointRequest], + firewall_activation.FirewallEndpoint, + ]: + r"""Return a callable for the get project firewall endpoint method over gRPC. + + Gets details of a single project Endpoint. + + Returns: + Callable[[~.GetFirewallEndpointRequest], + ~.FirewallEndpoint]: + 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_project_firewall_endpoint" not in self._stubs: + self._stubs["get_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/GetProjectFirewallEndpoint", + request_serializer=firewall_activation.GetFirewallEndpointRequest.serialize, + response_deserializer=firewall_activation.FirewallEndpoint.deserialize, + ) + ) + return self._stubs["get_project_firewall_endpoint"] + @property def create_firewall_endpoint( self, @@ -436,6 +500,38 @@ def create_firewall_endpoint( ) return self._stubs["create_firewall_endpoint"] + @property + def create_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.CreateFirewallEndpointRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create project firewall + endpoint method over gRPC. + + Creates a new FirewallEndpoint in a given project and + location. + + Returns: + Callable[[~.CreateFirewallEndpointRequest], + ~.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_project_firewall_endpoint" not in self._stubs: + self._stubs["create_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/CreateProjectFirewallEndpoint", + request_serializer=firewall_activation.CreateFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_project_firewall_endpoint"] + @property def delete_firewall_endpoint( self, @@ -464,6 +560,37 @@ def delete_firewall_endpoint( ) return self._stubs["delete_firewall_endpoint"] + @property + def delete_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.DeleteFirewallEndpointRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete project firewall + endpoint method over gRPC. + + Deletes a single project Endpoint. + + Returns: + Callable[[~.DeleteFirewallEndpointRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_project_firewall_endpoint" not in self._stubs: + self._stubs["delete_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/DeleteProjectFirewallEndpoint", + request_serializer=firewall_activation.DeleteFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_project_firewall_endpoint"] + @property def update_firewall_endpoint( self, @@ -492,6 +619,37 @@ def update_firewall_endpoint( ) return self._stubs["update_firewall_endpoint"] + @property + def update_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.UpdateFirewallEndpointRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update project firewall + endpoint method over gRPC. + + Update a single project Endpoint. + + Returns: + Callable[[~.UpdateFirewallEndpointRequest], + ~.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 "update_project_firewall_endpoint" not in self._stubs: + self._stubs["update_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/UpdateProjectFirewallEndpoint", + request_serializer=firewall_activation.UpdateFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_project_firewall_endpoint"] + @property def list_firewall_endpoint_associations( self, diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc_asyncio.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc_asyncio.py index 56be424e204f..0b4a2517804a 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc_asyncio.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/grpc_asyncio.py @@ -386,6 +386,39 @@ def list_firewall_endpoints( ) return self._stubs["list_firewall_endpoints"] + @property + def list_project_firewall_endpoints( + self, + ) -> Callable[ + [firewall_activation.ListFirewallEndpointsRequest], + Awaitable[firewall_activation.ListFirewallEndpointsResponse], + ]: + r"""Return a callable for the list project firewall + endpoints method over gRPC. + + Lists FirewallEndpoints in a given project and + location. + + Returns: + Callable[[~.ListFirewallEndpointsRequest], + Awaitable[~.ListFirewallEndpointsResponse]]: + 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_project_firewall_endpoints" not in self._stubs: + self._stubs["list_project_firewall_endpoints"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/ListProjectFirewallEndpoints", + request_serializer=firewall_activation.ListFirewallEndpointsRequest.serialize, + response_deserializer=firewall_activation.ListFirewallEndpointsResponse.deserialize, + ) + ) + return self._stubs["list_project_firewall_endpoints"] + @property def get_firewall_endpoint( self, @@ -415,6 +448,37 @@ def get_firewall_endpoint( ) return self._stubs["get_firewall_endpoint"] + @property + def get_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.GetFirewallEndpointRequest], + Awaitable[firewall_activation.FirewallEndpoint], + ]: + r"""Return a callable for the get project firewall endpoint method over gRPC. + + Gets details of a single project Endpoint. + + Returns: + Callable[[~.GetFirewallEndpointRequest], + Awaitable[~.FirewallEndpoint]]: + 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_project_firewall_endpoint" not in self._stubs: + self._stubs["get_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/GetProjectFirewallEndpoint", + request_serializer=firewall_activation.GetFirewallEndpointRequest.serialize, + response_deserializer=firewall_activation.FirewallEndpoint.deserialize, + ) + ) + return self._stubs["get_project_firewall_endpoint"] + @property def create_firewall_endpoint( self, @@ -445,6 +509,39 @@ def create_firewall_endpoint( ) return self._stubs["create_firewall_endpoint"] + @property + def create_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.CreateFirewallEndpointRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create project firewall + endpoint method over gRPC. + + Creates a new FirewallEndpoint in a given project and + location. + + Returns: + Callable[[~.CreateFirewallEndpointRequest], + 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_project_firewall_endpoint" not in self._stubs: + self._stubs["create_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/CreateProjectFirewallEndpoint", + request_serializer=firewall_activation.CreateFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_project_firewall_endpoint"] + @property def delete_firewall_endpoint( self, @@ -474,6 +571,38 @@ def delete_firewall_endpoint( ) return self._stubs["delete_firewall_endpoint"] + @property + def delete_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.DeleteFirewallEndpointRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete project firewall + endpoint method over gRPC. + + Deletes a single project Endpoint. + + Returns: + Callable[[~.DeleteFirewallEndpointRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_project_firewall_endpoint" not in self._stubs: + self._stubs["delete_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/DeleteProjectFirewallEndpoint", + request_serializer=firewall_activation.DeleteFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_project_firewall_endpoint"] + @property def update_firewall_endpoint( self, @@ -503,6 +632,38 @@ def update_firewall_endpoint( ) return self._stubs["update_firewall_endpoint"] + @property + def update_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.UpdateFirewallEndpointRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update project firewall + endpoint method over gRPC. + + Update a single project Endpoint. + + Returns: + Callable[[~.UpdateFirewallEndpointRequest], + 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 "update_project_firewall_endpoint" not in self._stubs: + self._stubs["update_project_firewall_endpoint"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.FirewallActivation/UpdateProjectFirewallEndpoint", + request_serializer=firewall_activation.UpdateFirewallEndpointRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_project_firewall_endpoint"] + @property def list_firewall_endpoint_associations( self, @@ -672,26 +833,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_project_firewall_endpoints: self._wrap_method( + self.list_project_firewall_endpoints, + default_timeout=None, + client_info=client_info, + ), self.get_firewall_endpoint: self._wrap_method( self.get_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.get_project_firewall_endpoint: self._wrap_method( + self.get_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.create_firewall_endpoint: self._wrap_method( self.create_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.create_project_firewall_endpoint: self._wrap_method( + self.create_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.delete_firewall_endpoint: self._wrap_method( self.delete_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.delete_project_firewall_endpoint: self._wrap_method( + self.delete_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.update_firewall_endpoint: self._wrap_method( self.update_firewall_endpoint, default_timeout=None, client_info=client_info, ), + self.update_project_firewall_endpoint: self._wrap_method( + self.update_project_firewall_endpoint, + default_timeout=None, + client_info=client_info, + ), self.list_firewall_endpoint_associations: self._wrap_method( self.list_firewall_endpoint_associations, default_timeout=None, diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest.py index 1d67fe38b4e8..621609a69198 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest.py @@ -94,6 +94,14 @@ def post_create_firewall_endpoint_association(self, response): logging.log(f"Received response: {response}") return response + def pre_create_project_firewall_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_project_firewall_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_firewall_endpoint(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -110,6 +118,14 @@ def post_delete_firewall_endpoint_association(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_project_firewall_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_project_firewall_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_firewall_endpoint(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -126,6 +142,14 @@ def post_get_firewall_endpoint_association(self, response): logging.log(f"Received response: {response}") return response + def pre_get_project_firewall_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_project_firewall_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_firewall_endpoint_associations(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -142,6 +166,14 @@ def post_list_firewall_endpoints(self, response): logging.log(f"Received response: {response}") return response + def pre_list_project_firewall_endpoints(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_project_firewall_endpoints(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_firewall_endpoint(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -158,6 +190,14 @@ def post_update_firewall_endpoint_association(self, response): logging.log(f"Received response: {response}") return response + def pre_update_project_firewall_endpoint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_project_firewall_endpoint(self, response): + logging.log(f"Received response: {response}") + return response + transport = FirewallActivationRestTransport(interceptor=MyCustomFirewallActivationInterceptor()) client = FirewallActivationClient(transport=transport) @@ -262,6 +302,55 @@ def post_create_firewall_endpoint_association_with_metadata( """ return response, metadata + def pre_create_project_firewall_endpoint( + self, + request: firewall_activation.CreateFirewallEndpointRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.CreateFirewallEndpointRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_project_firewall_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the FirewallActivation server. + """ + return request, metadata + + def post_create_project_firewall_endpoint( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_project_firewall_endpoint + + DEPRECATED. Please use the `post_create_project_firewall_endpoint_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FirewallActivation server but before + it is returned to user code. This `post_create_project_firewall_endpoint` interceptor runs + before the `post_create_project_firewall_endpoint_with_metadata` interceptor. + """ + return response + + def post_create_project_firewall_endpoint_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_project_firewall_endpoint + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FirewallActivation server but before it is returned to user code. + + We recommend only using this `post_create_project_firewall_endpoint_with_metadata` + interceptor in new development instead of the `post_create_project_firewall_endpoint` interceptor. + When both interceptors are used, this `post_create_project_firewall_endpoint_with_metadata` interceptor runs after the + `post_create_project_firewall_endpoint` interceptor. The (possibly modified) response returned by + `post_create_project_firewall_endpoint` will be passed to + `post_create_project_firewall_endpoint_with_metadata`. + """ + return response, metadata + def pre_delete_firewall_endpoint( self, request: firewall_activation.DeleteFirewallEndpointRequest, @@ -360,6 +449,55 @@ def post_delete_firewall_endpoint_association_with_metadata( """ return response, metadata + def pre_delete_project_firewall_endpoint( + self, + request: firewall_activation.DeleteFirewallEndpointRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.DeleteFirewallEndpointRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_project_firewall_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the FirewallActivation server. + """ + return request, metadata + + def post_delete_project_firewall_endpoint( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_project_firewall_endpoint + + DEPRECATED. Please use the `post_delete_project_firewall_endpoint_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FirewallActivation server but before + it is returned to user code. This `post_delete_project_firewall_endpoint` interceptor runs + before the `post_delete_project_firewall_endpoint_with_metadata` interceptor. + """ + return response + + def post_delete_project_firewall_endpoint_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_project_firewall_endpoint + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FirewallActivation server but before it is returned to user code. + + We recommend only using this `post_delete_project_firewall_endpoint_with_metadata` + interceptor in new development instead of the `post_delete_project_firewall_endpoint` interceptor. + When both interceptors are used, this `post_delete_project_firewall_endpoint_with_metadata` interceptor runs after the + `post_delete_project_firewall_endpoint` interceptor. The (possibly modified) response returned by + `post_delete_project_firewall_endpoint` will be passed to + `post_delete_project_firewall_endpoint_with_metadata`. + """ + return response, metadata + def pre_get_firewall_endpoint( self, request: firewall_activation.GetFirewallEndpointRequest, @@ -463,6 +601,57 @@ def post_get_firewall_endpoint_association_with_metadata( """ return response, metadata + def pre_get_project_firewall_endpoint( + self, + request: firewall_activation.GetFirewallEndpointRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.GetFirewallEndpointRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_project_firewall_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the FirewallActivation server. + """ + return request, metadata + + def post_get_project_firewall_endpoint( + self, response: firewall_activation.FirewallEndpoint + ) -> firewall_activation.FirewallEndpoint: + """Post-rpc interceptor for get_project_firewall_endpoint + + DEPRECATED. Please use the `post_get_project_firewall_endpoint_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FirewallActivation server but before + it is returned to user code. This `post_get_project_firewall_endpoint` interceptor runs + before the `post_get_project_firewall_endpoint_with_metadata` interceptor. + """ + return response + + def post_get_project_firewall_endpoint_with_metadata( + self, + response: firewall_activation.FirewallEndpoint, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.FirewallEndpoint, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_project_firewall_endpoint + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FirewallActivation server but before it is returned to user code. + + We recommend only using this `post_get_project_firewall_endpoint_with_metadata` + interceptor in new development instead of the `post_get_project_firewall_endpoint` interceptor. + When both interceptors are used, this `post_get_project_firewall_endpoint_with_metadata` interceptor runs after the + `post_get_project_firewall_endpoint` interceptor. The (possibly modified) response returned by + `post_get_project_firewall_endpoint` will be passed to + `post_get_project_firewall_endpoint_with_metadata`. + """ + return response, metadata + def pre_list_firewall_endpoint_associations( self, request: firewall_activation.ListFirewallEndpointAssociationsRequest, @@ -567,6 +756,58 @@ def post_list_firewall_endpoints_with_metadata( """ return response, metadata + def pre_list_project_firewall_endpoints( + self, + request: firewall_activation.ListFirewallEndpointsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.ListFirewallEndpointsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_project_firewall_endpoints + + Override in a subclass to manipulate the request or metadata + before they are sent to the FirewallActivation server. + """ + return request, metadata + + def post_list_project_firewall_endpoints( + self, response: firewall_activation.ListFirewallEndpointsResponse + ) -> firewall_activation.ListFirewallEndpointsResponse: + """Post-rpc interceptor for list_project_firewall_endpoints + + DEPRECATED. Please use the `post_list_project_firewall_endpoints_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FirewallActivation server but before + it is returned to user code. This `post_list_project_firewall_endpoints` interceptor runs + before the `post_list_project_firewall_endpoints_with_metadata` interceptor. + """ + return response + + def post_list_project_firewall_endpoints_with_metadata( + self, + response: firewall_activation.ListFirewallEndpointsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.ListFirewallEndpointsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_project_firewall_endpoints + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FirewallActivation server but before it is returned to user code. + + We recommend only using this `post_list_project_firewall_endpoints_with_metadata` + interceptor in new development instead of the `post_list_project_firewall_endpoints` interceptor. + When both interceptors are used, this `post_list_project_firewall_endpoints_with_metadata` interceptor runs after the + `post_list_project_firewall_endpoints` interceptor. The (possibly modified) response returned by + `post_list_project_firewall_endpoints` will be passed to + `post_list_project_firewall_endpoints_with_metadata`. + """ + return response, metadata + def pre_update_firewall_endpoint( self, request: firewall_activation.UpdateFirewallEndpointRequest, @@ -665,6 +906,55 @@ def post_update_firewall_endpoint_association_with_metadata( """ return response, metadata + def pre_update_project_firewall_endpoint( + self, + request: firewall_activation.UpdateFirewallEndpointRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + firewall_activation.UpdateFirewallEndpointRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_project_firewall_endpoint + + Override in a subclass to manipulate the request or metadata + before they are sent to the FirewallActivation server. + """ + return request, metadata + + def post_update_project_firewall_endpoint( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_project_firewall_endpoint + + DEPRECATED. Please use the `post_update_project_firewall_endpoint_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FirewallActivation server but before + it is returned to user code. This `post_update_project_firewall_endpoint` interceptor runs + before the `post_update_project_firewall_endpoint_with_metadata` interceptor. + """ + return response + + def post_update_project_firewall_endpoint_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 update_project_firewall_endpoint + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FirewallActivation server but before it is returned to user code. + + We recommend only using this `post_update_project_firewall_endpoint_with_metadata` + interceptor in new development instead of the `post_update_project_firewall_endpoint` interceptor. + When both interceptors are used, this `post_update_project_firewall_endpoint_with_metadata` interceptor runs after the + `post_update_project_firewall_endpoint` interceptor. The (possibly modified) response returned by + `post_update_project_firewall_endpoint` will be passed to + `post_update_project_firewall_endpoint_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -1361,12 +1651,12 @@ def __call__( ) return resp - class _DeleteFirewallEndpoint( - _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint, + class _CreateProjectFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint, FirewallActivationRestStub, ): def __hash__(self): - return hash("FirewallActivationRestTransport.DeleteFirewallEndpoint") + return hash("FirewallActivationRestTransport.CreateProjectFirewallEndpoint") @staticmethod def _get_response( @@ -1387,49 +1677,55 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: firewall_activation.DeleteFirewallEndpointRequest, + request: firewall_activation.CreateFirewallEndpointRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete firewall endpoint method over HTTP. + r"""Call the create project firewall + endpoint method over HTTP. - Args: - request (~.firewall_activation.DeleteFirewallEndpointRequest): - The request object. Message for deleting a Endpoint - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.firewall_activation.CreateFirewallEndpointRequest): + The request object. Message for creating a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint._get_http_options() - request, metadata = self._interceptor.pre_delete_firewall_endpoint( + request, metadata = self._interceptor.pre_create_project_firewall_endpoint( request, metadata ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint._get_transcoded_request( http_options, request ) + body = _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint._get_query_params_json( transcoded_request ) @@ -1451,23 +1747,172 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.DeleteFirewallEndpoint", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.CreateProjectFirewallEndpoint", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "DeleteFirewallEndpoint", + "rpcName": "CreateProjectFirewallEndpoint", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - FirewallActivationRestTransport._DeleteFirewallEndpoint._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, + response = FirewallActivationRestTransport._CreateProjectFirewallEndpoint._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_project_firewall_endpoint(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_project_firewall_endpoint_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.networksecurity_v1.FirewallActivationClient.create_project_firewall_endpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "CreateProjectFirewallEndpoint", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint, + FirewallActivationRestStub, + ): + def __hash__(self): + return hash("FirewallActivationRestTransport.DeleteFirewallEndpoint") + + @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: firewall_activation.DeleteFirewallEndpointRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete firewall endpoint method over HTTP. + + Args: + request (~.firewall_activation.DeleteFirewallEndpointRequest): + The request object. Message for deleting a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._get_http_options() + + request, metadata = self._interceptor.pre_delete_firewall_endpoint( + request, metadata + ) + transcoded_request = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpoint._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.networksecurity_v1.FirewallActivationClient.DeleteFirewallEndpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "DeleteFirewallEndpoint", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FirewallActivationRestTransport._DeleteFirewallEndpoint._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, transcoded_request, ) ) @@ -1570,19 +2015,465 @@ def __call__( """ - http_options = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._get_http_options() + + request, metadata = ( + self._interceptor.pre_delete_firewall_endpoint_association( + request, metadata + ) + ) + transcoded_request = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._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.networksecurity_v1.FirewallActivationClient.DeleteFirewallEndpointAssociation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "DeleteFirewallEndpointAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FirewallActivationRestTransport._DeleteFirewallEndpointAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_firewall_endpoint_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_firewall_endpoint_association_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.networksecurity_v1.FirewallActivationClient.delete_firewall_endpoint_association", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "DeleteFirewallEndpointAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteProjectFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseDeleteProjectFirewallEndpoint, + FirewallActivationRestStub, + ): + def __hash__(self): + return hash("FirewallActivationRestTransport.DeleteProjectFirewallEndpoint") + + @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: firewall_activation.DeleteFirewallEndpointRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete project firewall + endpoint method over HTTP. + + Args: + request (~.firewall_activation.DeleteFirewallEndpointRequest): + The request object. Message for deleting a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseFirewallActivationRestTransport._BaseDeleteProjectFirewallEndpoint._get_http_options() + + request, metadata = self._interceptor.pre_delete_project_firewall_endpoint( + request, metadata + ) + transcoded_request = _BaseFirewallActivationRestTransport._BaseDeleteProjectFirewallEndpoint._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFirewallActivationRestTransport._BaseDeleteProjectFirewallEndpoint._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.networksecurity_v1.FirewallActivationClient.DeleteProjectFirewallEndpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "DeleteProjectFirewallEndpoint", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FirewallActivationRestTransport._DeleteProjectFirewallEndpoint._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_project_firewall_endpoint(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_project_firewall_endpoint_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.networksecurity_v1.FirewallActivationClient.delete_project_firewall_endpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "DeleteProjectFirewallEndpoint", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint, + FirewallActivationRestStub, + ): + def __hash__(self): + return hash("FirewallActivationRestTransport.GetFirewallEndpoint") + + @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: firewall_activation.GetFirewallEndpointRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> firewall_activation.FirewallEndpoint: + r"""Call the get firewall endpoint method over HTTP. + + Args: + request (~.firewall_activation.GetFirewallEndpointRequest): + The request object. Message for getting a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.firewall_activation.FirewallEndpoint: + Message describing Endpoint object. + """ + + http_options = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._get_http_options() + + request, metadata = self._interceptor.pre_get_firewall_endpoint( + request, metadata + ) + transcoded_request = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._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.networksecurity_v1.FirewallActivationClient.GetFirewallEndpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "GetFirewallEndpoint", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FirewallActivationRestTransport._GetFirewallEndpoint._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 = firewall_activation.FirewallEndpoint() + pb_resp = firewall_activation.FirewallEndpoint.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_firewall_endpoint(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_firewall_endpoint_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = firewall_activation.FirewallEndpoint.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.networksecurity_v1.FirewallActivationClient.get_firewall_endpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "GetFirewallEndpoint", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFirewallEndpointAssociation( + _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation, + FirewallActivationRestStub, + ): + def __hash__(self): + return hash( + "FirewallActivationRestTransport.GetFirewallEndpointAssociation" + ) + + @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: firewall_activation.GetFirewallEndpointAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> firewall_activation.FirewallEndpointAssociation: + r"""Call the get firewall endpoint + association method over HTTP. + + Args: + request (~.firewall_activation.GetFirewallEndpointAssociationRequest): + The request object. Message for getting a Association + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.firewall_activation.FirewallEndpointAssociation: + Message describing Association object + """ + + http_options = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_http_options() - request, metadata = ( - self._interceptor.pre_delete_firewall_endpoint_association( - request, metadata - ) + request, metadata = self._interceptor.pre_get_firewall_endpoint_association( + request, metadata ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseDeleteFirewallEndpointAssociation._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_query_params_json( transcoded_request ) @@ -1604,17 +2495,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.DeleteFirewallEndpointAssociation", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.GetFirewallEndpointAssociation", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "DeleteFirewallEndpointAssociation", + "rpcName": "GetFirewallEndpointAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = FirewallActivationRestTransport._DeleteFirewallEndpointAssociation._get_response( + response = FirewallActivationRestTransport._GetFirewallEndpointAssociation._get_response( self._host, metadata, query_params, @@ -1629,13 +2520,15 @@ def __call__( 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 = firewall_activation.FirewallEndpointAssociation() + pb_resp = firewall_activation.FirewallEndpointAssociation.pb(resp) - resp = self._interceptor.post_delete_firewall_endpoint_association(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_firewall_endpoint_association(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_delete_firewall_endpoint_association_with_metadata( + self._interceptor.post_get_firewall_endpoint_association_with_metadata( resp, response_metadata ) ) @@ -1643,7 +2536,11 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = ( + firewall_activation.FirewallEndpointAssociation.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -1652,22 +2549,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.delete_firewall_endpoint_association", + "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.get_firewall_endpoint_association", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "DeleteFirewallEndpointAssociation", + "rpcName": "GetFirewallEndpointAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetFirewallEndpoint( - _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint, + class _GetProjectFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseGetProjectFirewallEndpoint, FirewallActivationRestStub, ): def __hash__(self): - return hash("FirewallActivationRestTransport.GetFirewallEndpoint") + return hash("FirewallActivationRestTransport.GetProjectFirewallEndpoint") @staticmethod def _get_response( @@ -1699,35 +2596,36 @@ def __call__( timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> firewall_activation.FirewallEndpoint: - r"""Call the get firewall endpoint method over HTTP. + r"""Call the get project firewall + endpoint method over HTTP. - Args: - request (~.firewall_activation.GetFirewallEndpointRequest): - The request object. Message for getting a Endpoint - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.firewall_activation.GetFirewallEndpointRequest): + The request object. Message for getting a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.firewall_activation.FirewallEndpoint: - Message describing Endpoint object. + Returns: + ~.firewall_activation.FirewallEndpoint: + Message describing Endpoint object. """ - http_options = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseGetProjectFirewallEndpoint._get_http_options() - request, metadata = self._interceptor.pre_get_firewall_endpoint( + request, metadata = self._interceptor.pre_get_project_firewall_endpoint( request, metadata ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseGetProjectFirewallEndpoint._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpoint._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseGetProjectFirewallEndpoint._get_query_params_json( transcoded_request ) @@ -1749,25 +2647,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.GetFirewallEndpoint", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.GetProjectFirewallEndpoint", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "GetFirewallEndpoint", + "rpcName": "GetProjectFirewallEndpoint", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - FirewallActivationRestTransport._GetFirewallEndpoint._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = FirewallActivationRestTransport._GetProjectFirewallEndpoint._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1781,10 +2677,12 @@ def __call__( json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_firewall_endpoint(resp) + resp = self._interceptor.post_get_project_firewall_endpoint(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_firewall_endpoint_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_get_project_firewall_endpoint_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -1801,23 +2699,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.get_firewall_endpoint", + "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.get_project_firewall_endpoint", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "GetFirewallEndpoint", + "rpcName": "GetProjectFirewallEndpoint", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetFirewallEndpointAssociation( - _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation, + class _ListFirewallEndpointAssociations( + _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations, FirewallActivationRestStub, ): def __hash__(self): return hash( - "FirewallActivationRestTransport.GetFirewallEndpointAssociation" + "FirewallActivationRestTransport.ListFirewallEndpointAssociations" ) @staticmethod @@ -1844,18 +2742,19 @@ def _get_response( def __call__( self, - request: firewall_activation.GetFirewallEndpointAssociationRequest, + request: firewall_activation.ListFirewallEndpointAssociationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> firewall_activation.FirewallEndpointAssociation: - r"""Call the get firewall endpoint - association method over HTTP. + ) -> firewall_activation.ListFirewallEndpointAssociationsResponse: + r"""Call the list firewall endpoint + associations method over HTTP. Args: - request (~.firewall_activation.GetFirewallEndpointAssociationRequest): - The request object. Message for getting a Association + request (~.firewall_activation.ListFirewallEndpointAssociationsRequest): + The request object. Message for requesting list of + Associations retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1865,21 +2764,25 @@ def __call__( be of type `bytes`. Returns: - ~.firewall_activation.FirewallEndpointAssociation: - Message describing Association object + ~.firewall_activation.ListFirewallEndpointAssociationsResponse: + Message for response to listing + Associations + """ - http_options = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_http_options() - request, metadata = self._interceptor.pre_get_firewall_endpoint_association( - request, metadata + request, metadata = ( + self._interceptor.pre_list_firewall_endpoint_associations( + request, metadata + ) ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseGetFirewallEndpointAssociation._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_query_params_json( transcoded_request ) @@ -1901,17 +2804,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.GetFirewallEndpointAssociation", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.ListFirewallEndpointAssociations", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "GetFirewallEndpointAssociation", + "rpcName": "ListFirewallEndpointAssociations", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = FirewallActivationRestTransport._GetFirewallEndpointAssociation._get_response( + response = FirewallActivationRestTransport._ListFirewallEndpointAssociations._get_response( self._host, metadata, query_params, @@ -1926,15 +2829,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = firewall_activation.FirewallEndpointAssociation() - pb_resp = firewall_activation.FirewallEndpointAssociation.pb(resp) + resp = firewall_activation.ListFirewallEndpointAssociationsResponse() + pb_resp = firewall_activation.ListFirewallEndpointAssociationsResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_firewall_endpoint_association(resp) + resp = self._interceptor.post_list_firewall_endpoint_associations(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_get_firewall_endpoint_association_with_metadata( + self._interceptor.post_list_firewall_endpoint_associations_with_metadata( resp, response_metadata ) ) @@ -1942,10 +2847,8 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - firewall_activation.FirewallEndpointAssociation.to_json( - response - ) + response_payload = firewall_activation.ListFirewallEndpointAssociationsResponse.to_json( + response ) except: response_payload = None @@ -1955,24 +2858,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.get_firewall_endpoint_association", + "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.list_firewall_endpoint_associations", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "GetFirewallEndpointAssociation", + "rpcName": "ListFirewallEndpointAssociations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListFirewallEndpointAssociations( - _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations, + class _ListFirewallEndpoints( + _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints, FirewallActivationRestStub, ): def __hash__(self): - return hash( - "FirewallActivationRestTransport.ListFirewallEndpointAssociations" - ) + return hash("FirewallActivationRestTransport.ListFirewallEndpoints") @staticmethod def _get_response( @@ -1998,47 +2899,44 @@ def _get_response( def __call__( self, - request: firewall_activation.ListFirewallEndpointAssociationsRequest, + request: firewall_activation.ListFirewallEndpointsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> firewall_activation.ListFirewallEndpointAssociationsResponse: - r"""Call the list firewall endpoint - associations method over HTTP. + ) -> firewall_activation.ListFirewallEndpointsResponse: + r"""Call the list firewall endpoints method over HTTP. - Args: - request (~.firewall_activation.ListFirewallEndpointAssociationsRequest): - The request object. Message for requesting list of - Associations - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.firewall_activation.ListFirewallEndpointsRequest): + The request object. Message for requesting list of + Endpoints + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.firewall_activation.ListFirewallEndpointAssociationsResponse: - Message for response to listing - Associations + Returns: + ~.firewall_activation.ListFirewallEndpointsResponse: + Message for response to listing + Endpoints """ - http_options = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_http_options() - request, metadata = ( - self._interceptor.pre_list_firewall_endpoint_associations( - request, metadata - ) + request, metadata = self._interceptor.pre_list_firewall_endpoints( + request, metadata ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseListFirewallEndpointAssociations._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_query_params_json( transcoded_request ) @@ -2060,23 +2958,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.ListFirewallEndpointAssociations", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.ListFirewallEndpoints", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "ListFirewallEndpointAssociations", + "rpcName": "ListFirewallEndpoints", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = FirewallActivationRestTransport._ListFirewallEndpointAssociations._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + FirewallActivationRestTransport._ListFirewallEndpoints._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2085,26 +2985,24 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = firewall_activation.ListFirewallEndpointAssociationsResponse() - pb_resp = firewall_activation.ListFirewallEndpointAssociationsResponse.pb( - resp - ) + resp = firewall_activation.ListFirewallEndpointsResponse() + pb_resp = firewall_activation.ListFirewallEndpointsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_firewall_endpoint_associations(resp) + resp = self._interceptor.post_list_firewall_endpoints(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_list_firewall_endpoint_associations_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_firewall_endpoints_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER - try: - response_payload = firewall_activation.ListFirewallEndpointAssociationsResponse.to_json( - response + try: + response_payload = ( + firewall_activation.ListFirewallEndpointsResponse.to_json( + response + ) ) except: response_payload = None @@ -2114,22 +3012,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.list_firewall_endpoint_associations", + "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.list_firewall_endpoints", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "ListFirewallEndpointAssociations", + "rpcName": "ListFirewallEndpoints", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListFirewallEndpoints( - _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints, + class _ListProjectFirewallEndpoints( + _BaseFirewallActivationRestTransport._BaseListProjectFirewallEndpoints, FirewallActivationRestStub, ): def __hash__(self): - return hash("FirewallActivationRestTransport.ListFirewallEndpoints") + return hash("FirewallActivationRestTransport.ListProjectFirewallEndpoints") @staticmethod def _get_response( @@ -2161,38 +3059,39 @@ def __call__( timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> firewall_activation.ListFirewallEndpointsResponse: - r"""Call the list firewall endpoints method over HTTP. + r"""Call the list project firewall + endpoints method over HTTP. - Args: - request (~.firewall_activation.ListFirewallEndpointsRequest): - The request object. Message for requesting list of - Endpoints - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + Args: + request (~.firewall_activation.ListFirewallEndpointsRequest): + The request object. Message for requesting list of + Endpoints + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. - Returns: - ~.firewall_activation.ListFirewallEndpointsResponse: - Message for response to listing - Endpoints + Returns: + ~.firewall_activation.ListFirewallEndpointsResponse: + Message for response to listing + Endpoints """ - http_options = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_http_options() + http_options = _BaseFirewallActivationRestTransport._BaseListProjectFirewallEndpoints._get_http_options() - request, metadata = self._interceptor.pre_list_firewall_endpoints( + request, metadata = self._interceptor.pre_list_project_firewall_endpoints( request, metadata ) - transcoded_request = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_transcoded_request( + transcoded_request = _BaseFirewallActivationRestTransport._BaseListProjectFirewallEndpoints._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseFirewallActivationRestTransport._BaseListFirewallEndpoints._get_query_params_json( + query_params = _BaseFirewallActivationRestTransport._BaseListProjectFirewallEndpoints._get_query_params_json( transcoded_request ) @@ -2214,25 +3113,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.ListFirewallEndpoints", + f"Sending request for google.cloud.networksecurity_v1.FirewallActivationClient.ListProjectFirewallEndpoints", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "ListFirewallEndpoints", + "rpcName": "ListProjectFirewallEndpoints", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - FirewallActivationRestTransport._ListFirewallEndpoints._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = FirewallActivationRestTransport._ListProjectFirewallEndpoints._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2246,10 +3143,12 @@ def __call__( json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_firewall_endpoints(resp) + resp = self._interceptor.post_list_project_firewall_endpoints(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_firewall_endpoints_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_project_firewall_endpoints_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -2268,10 +3167,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.list_firewall_endpoints", + "Received response for google.cloud.networksecurity_v1.FirewallActivationClient.list_project_firewall_endpoints", extra={ "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", - "rpcName": "ListFirewallEndpoints", + "rpcName": "ListProjectFirewallEndpoints", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -2591,6 +3490,161 @@ def __call__( ) return resp + class _UpdateProjectFirewallEndpoint( + _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint, + FirewallActivationRestStub, + ): + def __hash__(self): + return hash("FirewallActivationRestTransport.UpdateProjectFirewallEndpoint") + + @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: firewall_activation.UpdateFirewallEndpointRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update project firewall + endpoint method over HTTP. + + Args: + request (~.firewall_activation.UpdateFirewallEndpointRequest): + The request object. Message for updating a Endpoint + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint._get_http_options() + + request, metadata = self._interceptor.pre_update_project_firewall_endpoint( + request, metadata + ) + transcoded_request = _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint._get_transcoded_request( + http_options, request + ) + + body = _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint._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.networksecurity_v1.FirewallActivationClient.UpdateProjectFirewallEndpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "UpdateProjectFirewallEndpoint", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FirewallActivationRestTransport._UpdateProjectFirewallEndpoint._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_update_project_firewall_endpoint(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_project_firewall_endpoint_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.networksecurity_v1.FirewallActivationClient.update_project_firewall_endpoint", + extra={ + "serviceName": "google.cloud.networksecurity.v1.FirewallActivation", + "rpcName": "UpdateProjectFirewallEndpoint", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def create_firewall_endpoint( self, @@ -2616,6 +3670,18 @@ def create_firewall_endpoint_association( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.CreateFirewallEndpointRequest], 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._CreateProjectFirewallEndpoint( + self._session, self._host, self._interceptor + ) # type: ignore + @property def delete_firewall_endpoint( self, @@ -2641,6 +3707,18 @@ def delete_firewall_endpoint_association( self._session, self._host, self._interceptor ) # type: ignore + @property + def delete_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.DeleteFirewallEndpointRequest], 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._DeleteProjectFirewallEndpoint( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_firewall_endpoint( self, @@ -2665,6 +3743,19 @@ def get_firewall_endpoint_association( self._session, self._host, self._interceptor ) # type: ignore + @property + def get_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.GetFirewallEndpointRequest], + firewall_activation.FirewallEndpoint, + ]: + # 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._GetProjectFirewallEndpoint( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_firewall_endpoint_associations( self, @@ -2689,6 +3780,19 @@ def list_firewall_endpoints( # In C++ this would require a dynamic_cast return self._ListFirewallEndpoints(self._session, self._host, self._interceptor) # type: ignore + @property + def list_project_firewall_endpoints( + self, + ) -> Callable[ + [firewall_activation.ListFirewallEndpointsRequest], + firewall_activation.ListFirewallEndpointsResponse, + ]: + # 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._ListProjectFirewallEndpoints( + self._session, self._host, self._interceptor + ) # type: ignore + @property def update_firewall_endpoint( self, @@ -2714,6 +3818,18 @@ def update_firewall_endpoint_association( self._session, self._host, self._interceptor ) # type: ignore + @property + def update_project_firewall_endpoint( + self, + ) -> Callable[ + [firewall_activation.UpdateFirewallEndpointRequest], 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._UpdateProjectFirewallEndpoint( + 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-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest_base.py index 8e5654d24b6a..88261056bec5 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/firewall_activation/transports/rest_base.py @@ -211,6 +211,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateProjectFirewallEndpoint: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "firewallEndpointId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/firewallEndpoints", + "body": "firewall_endpoint", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = firewall_activation.CreateFirewallEndpointRequest.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( + _BaseFirewallActivationRestTransport._BaseCreateProjectFirewallEndpoint._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseDeleteFirewallEndpoint: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -307,6 +366,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseDeleteProjectFirewallEndpoint: + 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": "/v1/{name=projects/*/locations/*/firewallEndpoints/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = firewall_activation.DeleteFirewallEndpointRequest.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( + _BaseFirewallActivationRestTransport._BaseDeleteProjectFirewallEndpoint._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetFirewallEndpoint: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -403,6 +509,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetProjectFirewallEndpoint: + 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": "/v1/{name=projects/*/locations/*/firewallEndpoints/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = firewall_activation.GetFirewallEndpointRequest.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( + _BaseFirewallActivationRestTransport._BaseGetProjectFirewallEndpoint._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListFirewallEndpointAssociations: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -499,6 +652,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListProjectFirewallEndpoints: + 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": "/v1/{parent=projects/*/locations/*}/firewallEndpoints", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = firewall_activation.ListFirewallEndpointsRequest.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( + _BaseFirewallActivationRestTransport._BaseListProjectFirewallEndpoints._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateFirewallEndpoint: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -619,6 +819,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateProjectFirewallEndpoint: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v1/{firewall_endpoint.name=projects/*/locations/*/firewallEndpoints/*}", + "body": "firewall_endpoint", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = firewall_activation.UpdateFirewallEndpointRequest.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( + _BaseFirewallActivationRestTransport._BaseUpdateProjectFirewallEndpoint._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.") @@ -661,7 +920,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -692,10 +951,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -739,11 +994,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -792,12 +1042,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/intercept/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/intercept/transports/rest_base.py index 28fd8faaef3f..cb25e2b0a813 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/intercept/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/intercept/transports/rest_base.py @@ -1171,7 +1171,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -1202,10 +1202,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -1249,11 +1245,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -1302,12 +1293,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/mirroring/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/mirroring/transports/rest_base.py index c7e64feb6415..bd80230f4137 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/mirroring/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/mirroring/transports/rest_base.py @@ -1171,7 +1171,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -1202,10 +1202,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -1249,11 +1245,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -1302,12 +1293,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py index a9b5dd7ee9da..958183fe0926 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py @@ -2539,7 +2539,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -2570,10 +2570,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -2617,11 +2613,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -2670,12 +2661,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py index 61f8066bdde0..8faad46494bc 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py @@ -613,7 +613,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -644,10 +644,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -691,11 +687,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -744,12 +735,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_security_profile_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_security_profile_group_service/transports/rest_base.py index 1dfc6790a5be..94cbc1138d0b 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_security_profile_group_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_security_profile_group_service/transports/rest_base.py @@ -688,7 +688,7 @@ def _get_http_options(): }, { "method": "get", - "uri": "/v1/{name=organizations/*/locations/*}", + "uri": "/v1/{name=organizations/*}/locations", }, ] return http_options @@ -719,10 +719,6 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, - { - "method": "get", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", - }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -766,11 +762,6 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, - { - "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", - "body": "*", - }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -819,12 +810,12 @@ def _get_http_options(): }, { "method": "post", - "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", "body": "*", }, { "method": "post", - "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, { diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/__init__.py new file mode 100644 index 000000000000..9949f37b917e --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SecurityProfileGroupServiceAsyncClient +from .client import SecurityProfileGroupServiceClient + +__all__ = ( + "SecurityProfileGroupServiceClient", + "SecurityProfileGroupServiceAsyncClient", +) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/async_client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/async_client.py new file mode 100644 index 000000000000..41e66c12ea55 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/async_client.py @@ -0,0 +1,2457 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_security_v1.services.security_profile_group_service import ( + pagers, +) +from google.cloud.network_security_v1.types import ( + common, + security_profile_group, + security_profile_group_intercept, + security_profile_group_mirroring, + security_profile_group_service, + security_profile_group_threatprevention, + security_profile_group_urlfiltering, +) +from google.cloud.network_security_v1.types import ( + security_profile_group as gcn_security_profile_group, +) + +from .client import SecurityProfileGroupServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SecurityProfileGroupServiceTransport +from .transports.grpc_asyncio import SecurityProfileGroupServiceGrpcAsyncIOTransport + +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 SecurityProfileGroupServiceAsyncClient: + """SecurityProfileGroup is a resource that defines an action for + specific threat signatures or severity levels. + """ + + _client: SecurityProfileGroupServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityProfileGroupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityProfileGroupServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + SecurityProfileGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = SecurityProfileGroupServiceClient._DEFAULT_UNIVERSE + + intercept_endpoint_group_path = staticmethod( + SecurityProfileGroupServiceClient.intercept_endpoint_group_path + ) + parse_intercept_endpoint_group_path = staticmethod( + SecurityProfileGroupServiceClient.parse_intercept_endpoint_group_path + ) + mirroring_endpoint_group_path = staticmethod( + SecurityProfileGroupServiceClient.mirroring_endpoint_group_path + ) + parse_mirroring_endpoint_group_path = staticmethod( + SecurityProfileGroupServiceClient.parse_mirroring_endpoint_group_path + ) + security_profile_path = staticmethod( + SecurityProfileGroupServiceClient.security_profile_path + ) + parse_security_profile_path = staticmethod( + SecurityProfileGroupServiceClient.parse_security_profile_path + ) + security_profile_group_path = staticmethod( + SecurityProfileGroupServiceClient.security_profile_group_path + ) + parse_security_profile_group_path = staticmethod( + SecurityProfileGroupServiceClient.parse_security_profile_group_path + ) + common_billing_account_path = staticmethod( + SecurityProfileGroupServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SecurityProfileGroupServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + SecurityProfileGroupServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + SecurityProfileGroupServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SecurityProfileGroupServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SecurityProfileGroupServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + SecurityProfileGroupServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + SecurityProfileGroupServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SecurityProfileGroupServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SecurityProfileGroupServiceClient.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: + SecurityProfileGroupServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SecurityProfileGroupServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SecurityProfileGroupServiceAsyncClient, info, *args, **kwargs + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityProfileGroupServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SecurityProfileGroupServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SecurityProfileGroupServiceAsyncClient, filename, *args, **kwargs + ) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SecurityProfileGroupServiceClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> SecurityProfileGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityProfileGroupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = SecurityProfileGroupServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SecurityProfileGroupServiceTransport, + Callable[..., SecurityProfileGroupServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security profile group service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityProfileGroupServiceTransport,Callable[..., SecurityProfileGroupServiceTransport]]]): + 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 SecurityProfileGroupServiceTransport 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 = SecurityProfileGroupServiceClient( + 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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "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.networksecurity.v1.SecurityProfileGroupService", + "credentialsType": None, + }, + ) + + async def list_security_profile_groups( + self, + request: Optional[ + Union[security_profile_group_service.ListSecurityProfileGroupsRequest, 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.ListSecurityProfileGroupsAsyncPager: + r"""Lists SecurityProfileGroups in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_security_profile_groups(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfileGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profile_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListSecurityProfileGroupsRequest, dict]]): + The request object. Request used with the + ListSecurityProfileGroups method. + parent (:class:`str`): + Required. The project or organization and location from + which the SecurityProfileGroups should be listed, + specified in the format + ``projects|organizations/*/locations/{location}``. + + 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.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfileGroupsAsyncPager: + Response returned by the + ListSecurityProfileGroups method. + 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, security_profile_group_service.ListSecurityProfileGroupsRequest + ): + request = security_profile_group_service.ListSecurityProfileGroupsRequest( + 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_security_profile_groups + ] + + # 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.ListSecurityProfileGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_security_profile_group( + self, + request: Optional[ + Union[security_profile_group_service.GetSecurityProfileGroupRequest, 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]]] = (), + ) -> security_profile_group.SecurityProfileGroup: + r"""Gets details of a single SecurityProfileGroup. + + .. 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 network_security_v1 + + async def sample_get_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_profile_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetSecurityProfileGroupRequest, dict]]): + The request object. Request used by the + GetSecurityProfileGroup method. + name (:class:`str`): + Required. A name of the SecurityProfileGroup to get. + Must be in the format + ``projects|organizations/*/locations/{location}/securityProfileGroups/{security_profile_group}``. + + 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.network_security_v1.types.SecurityProfileGroup: + SecurityProfileGroup is a resource + that defines the behavior for various + ProfileTypes. + + """ + # 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, security_profile_group_service.GetSecurityProfileGroupRequest + ): + request = security_profile_group_service.GetSecurityProfileGroupRequest( + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.CreateSecurityProfileGroupRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + security_profile_group: Optional[ + gcn_security_profile_group.SecurityProfileGroup + ] = None, + security_profile_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new SecurityProfileGroup in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + + # Make the request + operation = await client.create_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateSecurityProfileGroupRequest, dict]]): + The request object. Request used by the + CreateSecurityProfileGroup method. + parent (:class:`str`): + Required. The parent resource of the + SecurityProfileGroup. Must be in the format + ``projects|organizations/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_group (:class:`google.cloud.network_security_v1.types.SecurityProfileGroup`): + Required. SecurityProfileGroup + resource to be created. + + This corresponds to the ``security_profile_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_group_id (:class:`str`): + Required. Short name of the SecurityProfileGroup + resource to be created. This value should be 1-63 + characters long, containing only letters, numbers, + hyphens, and underscores, and should not start with a + number. E.g. "security_profile_group1". + + This corresponds to the ``security_profile_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfileGroup` SecurityProfileGroup is a resource that defines the behavior for various + ProfileTypes. + + """ + # 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, security_profile_group, security_profile_group_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, security_profile_group_service.CreateSecurityProfileGroupRequest + ): + request = security_profile_group_service.CreateSecurityProfileGroupRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_profile_group is not None: + request.security_profile_group = security_profile_group + if security_profile_group_id is not None: + request.security_profile_group_id = security_profile_group_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_security_profile_group + ] + + # 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, + gcn_security_profile_group.SecurityProfileGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.UpdateSecurityProfileGroupRequest, dict + ] + ] = None, + *, + security_profile_group: Optional[ + gcn_security_profile_group.SecurityProfileGroup + ] = 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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single + SecurityProfileGroup. + + .. 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 network_security_v1 + + async def sample_update_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileGroupRequest( + ) + + # Make the request + operation = await client.update_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateSecurityProfileGroupRequest, dict]]): + The request object. Request used by the + UpdateSecurityProfileGroup method. + security_profile_group (:class:`google.cloud.network_security_v1.types.SecurityProfileGroup`): + Required. Updated + SecurityProfileGroup resource. + + This corresponds to the ``security_profile_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the SecurityProfileGroup resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfileGroup` SecurityProfileGroup is a resource that defines the behavior for various + ProfileTypes. + + """ + # 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 = [security_profile_group, 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, security_profile_group_service.UpdateSecurityProfileGroupRequest + ): + request = security_profile_group_service.UpdateSecurityProfileGroupRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_profile_group is not None: + request.security_profile_group = security_profile_group + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_profile_group.name", request.security_profile_group.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcn_security_profile_group.SecurityProfileGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.DeleteSecurityProfileGroupRequest, dict + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single SecurityProfileGroup. + + .. 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 network_security_v1 + + async def sample_delete_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteSecurityProfileGroupRequest, dict]]): + The request object. Request used by the + DeleteSecurityProfileGroup method. + name (:class:`str`): + Required. A name of the SecurityProfileGroup to delete. + Must be in the format + ``projects|organizations/*/locations/{location}/securityProfileGroups/{security_profile_group}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, security_profile_group_service.DeleteSecurityProfileGroupRequest + ): + request = security_profile_group_service.DeleteSecurityProfileGroupRequest( + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_security_profiles( + self, + request: Optional[ + Union[security_profile_group_service.ListSecurityProfilesRequest, 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.ListSecurityProfilesAsyncPager: + r"""Lists SecurityProfiles in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_security_profiles(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfilesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profiles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListSecurityProfilesRequest, dict]]): + The request object. Request used with the + ListSecurityProfiles method. + parent (:class:`str`): + Required. The project or organization and location from + which the SecurityProfiles should be listed, specified + in the format + ``projects|organizations/*/locations/{location}``. + + 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.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfilesAsyncPager: + Response returned by the + ListSecurityProfiles method. + 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, security_profile_group_service.ListSecurityProfilesRequest + ): + request = security_profile_group_service.ListSecurityProfilesRequest( + 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_security_profiles + ] + + # 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.ListSecurityProfilesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.GetSecurityProfileRequest, 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]]] = (), + ) -> security_profile_group.SecurityProfile: + r"""Gets details of a single SecurityProfile. + + .. 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 network_security_v1 + + async def sample_get_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_profile(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetSecurityProfileRequest, dict]]): + The request object. Request used by the + GetSecurityProfile method. + name (:class:`str`): + Required. A name of the SecurityProfile to get. Must be + in the format + ``projects|organizations/*/locations/{location}/securityProfiles/{security_profile_id}``. + + 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.network_security_v1.types.SecurityProfile: + SecurityProfile is a resource that + defines the behavior for one of many + ProfileTypes. + + """ + # 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, security_profile_group_service.GetSecurityProfileRequest + ): + request = security_profile_group_service.GetSecurityProfileRequest(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_security_profile + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.CreateSecurityProfileRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + security_profile: Optional[security_profile_group.SecurityProfile] = None, + security_profile_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new SecurityProfile in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + + # Make the request + operation = await client.create_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateSecurityProfileRequest, dict]]): + The request object. Request used by the + CreateSecurityProfile method. + parent (:class:`str`): + Required. The parent resource of the SecurityProfile. + Must be in the format + ``projects|organizations/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile (:class:`google.cloud.network_security_v1.types.SecurityProfile`): + Required. SecurityProfile resource to + be created. + + This corresponds to the ``security_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_id (:class:`str`): + Required. Short name of the SecurityProfile resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "security_profile1". + + This corresponds to the ``security_profile_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfile` SecurityProfile is a resource that defines the behavior for one of many + ProfileTypes. + + """ + # 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, security_profile, security_profile_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, security_profile_group_service.CreateSecurityProfileRequest + ): + request = security_profile_group_service.CreateSecurityProfileRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_profile is not None: + request.security_profile = security_profile + if security_profile_id is not None: + request.security_profile_id = security_profile_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_security_profile + ] + + # 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, + security_profile_group.SecurityProfile, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.UpdateSecurityProfileRequest, dict] + ] = None, + *, + security_profile: Optional[security_profile_group.SecurityProfile] = 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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single SecurityProfile. + + .. 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 network_security_v1 + + async def sample_update_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileRequest( + ) + + # Make the request + operation = await client.update_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateSecurityProfileRequest, dict]]): + The request object. Request used by the + UpdateSecurityProfile method. + security_profile (:class:`google.cloud.network_security_v1.types.SecurityProfile`): + Required. Updated SecurityProfile + resource. + + This corresponds to the ``security_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Field mask is used to specify the fields to be + overwritten in the SecurityProfile resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfile` SecurityProfile is a resource that defines the behavior for one of many + ProfileTypes. + + """ + # 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 = [security_profile, 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, security_profile_group_service.UpdateSecurityProfileRequest + ): + request = security_profile_group_service.UpdateSecurityProfileRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_profile is not None: + request.security_profile = security_profile + 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_security_profile + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_profile.name", request.security_profile.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + security_profile_group.SecurityProfile, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.DeleteSecurityProfileRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single SecurityProfile. + + .. 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 network_security_v1 + + async def sample_delete_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteSecurityProfileRequest, dict]]): + The request object. Request used by the + DeleteSecurityProfile method. + name (:class:`str`): + Required. A name of the SecurityProfile to delete. Must + be in the format + ``projects|organizations/*/locations/{location}/securityProfiles/{security_profile_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, security_profile_group_service.DeleteSecurityProfileRequest + ): + request = security_profile_group_service.DeleteSecurityProfileRequest( + 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_security_profile + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SecurityProfileGroupServiceAsyncClient": + 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__ = ("SecurityProfileGroupServiceAsyncClient",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/client.py new file mode 100644 index 000000000000..98a37299a7bd --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/client.py @@ -0,0 +1,2944 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_security_v1.services.security_profile_group_service import ( + pagers, +) +from google.cloud.network_security_v1.types import ( + common, + security_profile_group, + security_profile_group_intercept, + security_profile_group_mirroring, + security_profile_group_service, + security_profile_group_threatprevention, + security_profile_group_urlfiltering, +) +from google.cloud.network_security_v1.types import ( + security_profile_group as gcn_security_profile_group, +) + +from .transports.base import DEFAULT_CLIENT_INFO, SecurityProfileGroupServiceTransport +from .transports.grpc import SecurityProfileGroupServiceGrpcTransport +from .transports.grpc_asyncio import SecurityProfileGroupServiceGrpcAsyncIOTransport +from .transports.rest import SecurityProfileGroupServiceRestTransport + + +class SecurityProfileGroupServiceClientMeta(type): + """Metaclass for the SecurityProfileGroupService 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[SecurityProfileGroupServiceTransport]] + _transport_registry["grpc"] = SecurityProfileGroupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ( + SecurityProfileGroupServiceGrpcAsyncIOTransport + ) + _transport_registry["rest"] = SecurityProfileGroupServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SecurityProfileGroupServiceTransport]: + """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 SecurityProfileGroupServiceClient( + metaclass=SecurityProfileGroupServiceClientMeta +): + """SecurityProfileGroup is a resource that defines an action for + specific threat signatures or severity levels. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{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: + SecurityProfileGroupServiceClient: 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: + SecurityProfileGroupServiceClient: 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) -> SecurityProfileGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityProfileGroupServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def intercept_endpoint_group_path( + project: str, + location: str, + intercept_endpoint_group: str, + ) -> str: + """Returns a fully-qualified intercept_endpoint_group string.""" + return "projects/{project}/locations/{location}/interceptEndpointGroups/{intercept_endpoint_group}".format( + project=project, + location=location, + intercept_endpoint_group=intercept_endpoint_group, + ) + + @staticmethod + def parse_intercept_endpoint_group_path(path: str) -> Dict[str, str]: + """Parses a intercept_endpoint_group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/interceptEndpointGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mirroring_endpoint_group_path( + project: str, + location: str, + mirroring_endpoint_group: str, + ) -> str: + """Returns a fully-qualified mirroring_endpoint_group string.""" + return "projects/{project}/locations/{location}/mirroringEndpointGroups/{mirroring_endpoint_group}".format( + project=project, + location=location, + mirroring_endpoint_group=mirroring_endpoint_group, + ) + + @staticmethod + def parse_mirroring_endpoint_group_path(path: str) -> Dict[str, str]: + """Parses a mirroring_endpoint_group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/mirroringEndpointGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def security_profile_path( + organization: str, + location: str, + security_profile: str, + ) -> str: + """Returns a fully-qualified security_profile string.""" + return "organizations/{organization}/locations/{location}/securityProfiles/{security_profile}".format( + organization=organization, + location=location, + security_profile=security_profile, + ) + + @staticmethod + def parse_security_profile_path(path: str) -> Dict[str, str]: + """Parses a security_profile path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/securityProfiles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def security_profile_group_path( + organization: str, + location: str, + security_profile_group: str, + ) -> str: + """Returns a fully-qualified security_profile_group string.""" + return "organizations/{organization}/locations/{location}/securityProfileGroups/{security_profile_group}".format( + organization=organization, + location=location, + security_profile_group=security_profile_group, + ) + + @staticmethod + def parse_security_profile_group_path(path: str) -> Dict[str, str]: + """Parses a security_profile_group path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/securityProfileGroups/(?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 = SecurityProfileGroupServiceClient._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 = SecurityProfileGroupServiceClient._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 + ) -> str: + """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 = SecurityProfileGroupServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SecurityProfileGroupServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SecurityProfileGroupServiceClient._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 = SecurityProfileGroupServiceClient._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) -> str: + """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, + SecurityProfileGroupServiceTransport, + Callable[..., SecurityProfileGroupServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security profile group service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SecurityProfileGroupServiceTransport,Callable[..., SecurityProfileGroupServiceTransport]]]): + 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 SecurityProfileGroupServiceTransport 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 = ( + SecurityProfileGroupServiceClient._read_environment_variables() + ) + self._client_cert_source = ( + SecurityProfileGroupServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = SecurityProfileGroupServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, SecurityProfileGroupServiceTransport) + if transport_provided: + # transport is a SecurityProfileGroupServiceTransport 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(SecurityProfileGroupServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SecurityProfileGroupServiceClient._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[SecurityProfileGroupServiceTransport], + Callable[..., SecurityProfileGroupServiceTransport], + ] = ( + SecurityProfileGroupServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., SecurityProfileGroupServiceTransport], 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.networksecurity_v1.SecurityProfileGroupServiceClient`.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "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.networksecurity.v1.SecurityProfileGroupService", + "credentialsType": None, + }, + ) + + def list_security_profile_groups( + self, + request: Optional[ + Union[security_profile_group_service.ListSecurityProfileGroupsRequest, 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.ListSecurityProfileGroupsPager: + r"""Lists SecurityProfileGroups in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_security_profile_groups(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfileGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profile_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListSecurityProfileGroupsRequest, dict]): + The request object. Request used with the + ListSecurityProfileGroups method. + parent (str): + Required. The project or organization and location from + which the SecurityProfileGroups should be listed, + specified in the format + ``projects|organizations/*/locations/{location}``. + + 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.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfileGroupsPager: + Response returned by the + ListSecurityProfileGroups method. + 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, security_profile_group_service.ListSecurityProfileGroupsRequest + ): + request = security_profile_group_service.ListSecurityProfileGroupsRequest( + 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_security_profile_groups + ] + + # 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.ListSecurityProfileGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_security_profile_group( + self, + request: Optional[ + Union[security_profile_group_service.GetSecurityProfileGroupRequest, 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]]] = (), + ) -> security_profile_group.SecurityProfileGroup: + r"""Gets details of a single SecurityProfileGroup. + + .. 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 network_security_v1 + + def sample_get_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_profile_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetSecurityProfileGroupRequest, dict]): + The request object. Request used by the + GetSecurityProfileGroup method. + name (str): + Required. A name of the SecurityProfileGroup to get. + Must be in the format + ``projects|organizations/*/locations/{location}/securityProfileGroups/{security_profile_group}``. + + 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.network_security_v1.types.SecurityProfileGroup: + SecurityProfileGroup is a resource + that defines the behavior for various + ProfileTypes. + + """ + # 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, security_profile_group_service.GetSecurityProfileGroupRequest + ): + request = security_profile_group_service.GetSecurityProfileGroupRequest( + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.CreateSecurityProfileGroupRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + security_profile_group: Optional[ + gcn_security_profile_group.SecurityProfileGroup + ] = None, + security_profile_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new SecurityProfileGroup in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + + # Make the request + operation = client.create_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateSecurityProfileGroupRequest, dict]): + The request object. Request used by the + CreateSecurityProfileGroup method. + parent (str): + Required. The parent resource of the + SecurityProfileGroup. Must be in the format + ``projects|organizations/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_group (google.cloud.network_security_v1.types.SecurityProfileGroup): + Required. SecurityProfileGroup + resource to be created. + + This corresponds to the ``security_profile_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_group_id (str): + Required. Short name of the SecurityProfileGroup + resource to be created. This value should be 1-63 + characters long, containing only letters, numbers, + hyphens, and underscores, and should not start with a + number. E.g. "security_profile_group1". + + This corresponds to the ``security_profile_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfileGroup` SecurityProfileGroup is a resource that defines the behavior for various + ProfileTypes. + + """ + # 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, security_profile_group, security_profile_group_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, security_profile_group_service.CreateSecurityProfileGroupRequest + ): + request = security_profile_group_service.CreateSecurityProfileGroupRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_profile_group is not None: + request.security_profile_group = security_profile_group + if security_profile_group_id is not None: + request.security_profile_group_id = security_profile_group_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_security_profile_group + ] + + # 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, + gcn_security_profile_group.SecurityProfileGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.UpdateSecurityProfileGroupRequest, dict + ] + ] = None, + *, + security_profile_group: Optional[ + gcn_security_profile_group.SecurityProfileGroup + ] = 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]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single + SecurityProfileGroup. + + .. 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 network_security_v1 + + def sample_update_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileGroupRequest( + ) + + # Make the request + operation = client.update_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateSecurityProfileGroupRequest, dict]): + The request object. Request used by the + UpdateSecurityProfileGroup method. + security_profile_group (google.cloud.network_security_v1.types.SecurityProfileGroup): + Required. Updated + SecurityProfileGroup resource. + + This corresponds to the ``security_profile_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the SecurityProfileGroup resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfileGroup` SecurityProfileGroup is a resource that defines the behavior for various + ProfileTypes. + + """ + # 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 = [security_profile_group, 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, security_profile_group_service.UpdateSecurityProfileGroupRequest + ): + request = security_profile_group_service.UpdateSecurityProfileGroupRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_profile_group is not None: + request.security_profile_group = security_profile_group + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_profile_group.name", request.security_profile_group.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcn_security_profile_group.SecurityProfileGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_security_profile_group( + self, + request: Optional[ + Union[ + security_profile_group_service.DeleteSecurityProfileGroupRequest, dict + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single SecurityProfileGroup. + + .. 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 network_security_v1 + + def sample_delete_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteSecurityProfileGroupRequest, dict]): + The request object. Request used by the + DeleteSecurityProfileGroup method. + name (str): + Required. A name of the SecurityProfileGroup to delete. + Must be in the format + ``projects|organizations/*/locations/{location}/securityProfileGroups/{security_profile_group}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, security_profile_group_service.DeleteSecurityProfileGroupRequest + ): + request = security_profile_group_service.DeleteSecurityProfileGroupRequest( + 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_security_profile_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_security_profiles( + self, + request: Optional[ + Union[security_profile_group_service.ListSecurityProfilesRequest, 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.ListSecurityProfilesPager: + r"""Lists SecurityProfiles in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_security_profiles(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfilesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profiles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListSecurityProfilesRequest, dict]): + The request object. Request used with the + ListSecurityProfiles method. + parent (str): + Required. The project or organization and location from + which the SecurityProfiles should be listed, specified + in the format + ``projects|organizations/*/locations/{location}``. + + 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.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfilesPager: + Response returned by the + ListSecurityProfiles method. + 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, security_profile_group_service.ListSecurityProfilesRequest + ): + request = security_profile_group_service.ListSecurityProfilesRequest( + 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_security_profiles] + + # 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.ListSecurityProfilesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.GetSecurityProfileRequest, 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]]] = (), + ) -> security_profile_group.SecurityProfile: + r"""Gets details of a single SecurityProfile. + + .. 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 network_security_v1 + + def sample_get_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_profile(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetSecurityProfileRequest, dict]): + The request object. Request used by the + GetSecurityProfile method. + name (str): + Required. A name of the SecurityProfile to get. Must be + in the format + ``projects|organizations/*/locations/{location}/securityProfiles/{security_profile_id}``. + + 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.network_security_v1.types.SecurityProfile: + SecurityProfile is a resource that + defines the behavior for one of many + ProfileTypes. + + """ + # 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, security_profile_group_service.GetSecurityProfileRequest + ): + request = security_profile_group_service.GetSecurityProfileRequest(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_security_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.CreateSecurityProfileRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + security_profile: Optional[security_profile_group.SecurityProfile] = None, + security_profile_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new SecurityProfile in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + + # Make the request + operation = client.create_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateSecurityProfileRequest, dict]): + The request object. Request used by the + CreateSecurityProfile method. + parent (str): + Required. The parent resource of the SecurityProfile. + Must be in the format + ``projects|organizations/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile (google.cloud.network_security_v1.types.SecurityProfile): + Required. SecurityProfile resource to + be created. + + This corresponds to the ``security_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_profile_id (str): + Required. Short name of the SecurityProfile resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "security_profile1". + + This corresponds to the ``security_profile_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfile` SecurityProfile is a resource that defines the behavior for one of many + ProfileTypes. + + """ + # 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, security_profile, security_profile_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, security_profile_group_service.CreateSecurityProfileRequest + ): + request = security_profile_group_service.CreateSecurityProfileRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_profile is not None: + request.security_profile = security_profile + if security_profile_id is not None: + request.security_profile_id = security_profile_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_profile] + + # 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, + security_profile_group.SecurityProfile, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.UpdateSecurityProfileRequest, dict] + ] = None, + *, + security_profile: Optional[security_profile_group.SecurityProfile] = 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]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single SecurityProfile. + + .. 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 network_security_v1 + + def sample_update_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileRequest( + ) + + # Make the request + operation = client.update_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateSecurityProfileRequest, dict]): + The request object. Request used by the + UpdateSecurityProfile method. + security_profile (google.cloud.network_security_v1.types.SecurityProfile): + Required. Updated SecurityProfile + resource. + + This corresponds to the ``security_profile`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Field mask is used to specify the fields to be + overwritten in the SecurityProfile resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.SecurityProfile` SecurityProfile is a resource that defines the behavior for one of many + ProfileTypes. + + """ + # 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 = [security_profile, 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, security_profile_group_service.UpdateSecurityProfileRequest + ): + request = security_profile_group_service.UpdateSecurityProfileRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_profile is not None: + request.security_profile = security_profile + 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_security_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_profile.name", request.security_profile.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + security_profile_group.SecurityProfile, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_security_profile( + self, + request: Optional[ + Union[security_profile_group_service.DeleteSecurityProfileRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single SecurityProfile. + + .. 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 network_security_v1 + + def sample_delete_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteSecurityProfileRequest, dict]): + The request object. Request used by the + DeleteSecurityProfile method. + name (str): + Required. A name of the SecurityProfile to delete. Must + be in the format + ``projects|organizations/*/locations/{location}/securityProfiles/{security_profile_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, security_profile_group_service.DeleteSecurityProfileRequest + ): + request = security_profile_group_service.DeleteSecurityProfileRequest( + 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_security_profile] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SecurityProfileGroupServiceClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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 test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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[Union[locations_pb2.ListLocationsRequest, dict]] = 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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__ = ("SecurityProfileGroupServiceClient",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/pagers.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/pagers.py new file mode 100644 index 000000000000..4105fa87e569 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/pagers.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + + +class ListSecurityProfileGroupsPager: + """A pager for iterating through ``list_security_profile_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_profile_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecurityProfileGroups`` requests and continue to iterate + through the ``security_profile_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse` + 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[ + ..., security_profile_group_service.ListSecurityProfileGroupsResponse + ], + request: security_profile_group_service.ListSecurityProfileGroupsRequest, + response: security_profile_group_service.ListSecurityProfileGroupsResponse, + *, + 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.network_security_v1.types.ListSecurityProfileGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse): + 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 = security_profile_group_service.ListSecurityProfileGroupsRequest( + 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[security_profile_group_service.ListSecurityProfileGroupsResponse]: + 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[security_profile_group.SecurityProfileGroup]: + for page in self.pages: + yield from page.security_profile_groups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecurityProfileGroupsAsyncPager: + """A pager for iterating through ``list_security_profile_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_profile_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecurityProfileGroups`` requests and continue to iterate + through the ``security_profile_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse` + 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[security_profile_group_service.ListSecurityProfileGroupsResponse], + ], + request: security_profile_group_service.ListSecurityProfileGroupsRequest, + response: security_profile_group_service.ListSecurityProfileGroupsResponse, + *, + 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.network_security_v1.types.ListSecurityProfileGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSecurityProfileGroupsResponse): + 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 = security_profile_group_service.ListSecurityProfileGroupsRequest( + 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[ + security_profile_group_service.ListSecurityProfileGroupsResponse + ]: + 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[security_profile_group.SecurityProfileGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.security_profile_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecurityProfilesPager: + """A pager for iterating through ``list_security_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSecurityProfilesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_profiles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecurityProfiles`` requests and continue to iterate + through the ``security_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSecurityProfilesResponse` + 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[ + ..., security_profile_group_service.ListSecurityProfilesResponse + ], + request: security_profile_group_service.ListSecurityProfilesRequest, + response: security_profile_group_service.ListSecurityProfilesResponse, + *, + 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.network_security_v1.types.ListSecurityProfilesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSecurityProfilesResponse): + 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 = security_profile_group_service.ListSecurityProfilesRequest( + 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[security_profile_group_service.ListSecurityProfilesResponse]: + 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[security_profile_group.SecurityProfile]: + for page in self.pages: + yield from page.security_profiles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSecurityProfilesAsyncPager: + """A pager for iterating through ``list_security_profiles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSecurityProfilesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_profiles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecurityProfiles`` requests and continue to iterate + through the ``security_profiles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSecurityProfilesResponse` + 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[security_profile_group_service.ListSecurityProfilesResponse] + ], + request: security_profile_group_service.ListSecurityProfilesRequest, + response: security_profile_group_service.ListSecurityProfilesResponse, + *, + 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.network_security_v1.types.ListSecurityProfilesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSecurityProfilesResponse): + 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 = security_profile_group_service.ListSecurityProfilesRequest( + 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[security_profile_group_service.ListSecurityProfilesResponse]: + 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[security_profile_group.SecurityProfile]: + async def async_generator(): + async for page in self.pages: + for response in page.security_profiles: + 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-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/README.rst b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/README.rst new file mode 100644 index 000000000000..9963f77a8390 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``SecurityProfileGroupServiceTransport`` is the ABC for all transports. + +- public child ``SecurityProfileGroupServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``SecurityProfileGroupServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseSecurityProfileGroupServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``SecurityProfileGroupServiceRestTransport`` 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-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/__init__.py new file mode 100644 index 000000000000..c13f9659278c --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SecurityProfileGroupServiceTransport +from .grpc import SecurityProfileGroupServiceGrpcTransport +from .grpc_asyncio import SecurityProfileGroupServiceGrpcAsyncIOTransport +from .rest import ( + SecurityProfileGroupServiceRestInterceptor, + SecurityProfileGroupServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityProfileGroupServiceTransport]] +_transport_registry["grpc"] = SecurityProfileGroupServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SecurityProfileGroupServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SecurityProfileGroupServiceRestTransport + +__all__ = ( + "SecurityProfileGroupServiceTransport", + "SecurityProfileGroupServiceGrpcTransport", + "SecurityProfileGroupServiceGrpcAsyncIOTransport", + "SecurityProfileGroupServiceRestTransport", + "SecurityProfileGroupServiceRestInterceptor", +) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/base.py new file mode 100644 index 000000000000..fb878ea4bec6 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/base.py @@ -0,0 +1,462 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version +from google.cloud.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SecurityProfileGroupServiceTransport(abc.ABC): + """Abstract transport class for SecurityProfileGroupService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_security_profile_groups: gapic_v1.method.wrap_method( + self.list_security_profile_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_security_profile_group: gapic_v1.method.wrap_method( + self.get_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.create_security_profile_group: gapic_v1.method.wrap_method( + self.create_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.update_security_profile_group: gapic_v1.method.wrap_method( + self.update_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_profile_group: gapic_v1.method.wrap_method( + self.delete_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.list_security_profiles: gapic_v1.method.wrap_method( + self.list_security_profiles, + default_timeout=None, + client_info=client_info, + ), + self.get_security_profile: gapic_v1.method.wrap_method( + self.get_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.create_security_profile: gapic_v1.method.wrap_method( + self.create_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.update_security_profile: gapic_v1.method.wrap_method( + self.update_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_profile: gapic_v1.method.wrap_method( + self.delete_security_profile, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_security_profile_groups( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfileGroupsRequest], + Union[ + security_profile_group_service.ListSecurityProfileGroupsResponse, + Awaitable[security_profile_group_service.ListSecurityProfileGroupsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileGroupRequest], + Union[ + security_profile_group.SecurityProfileGroup, + Awaitable[security_profile_group.SecurityProfileGroup], + ], + ]: + raise NotImplementedError() + + @property + def create_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_security_profiles( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfilesRequest], + Union[ + security_profile_group_service.ListSecurityProfilesResponse, + Awaitable[security_profile_group_service.ListSecurityProfilesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileRequest], + Union[ + security_profile_group.SecurityProfile, + Awaitable[security_profile_group.SecurityProfile], + ], + ]: + raise NotImplementedError() + + @property + def create_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ("SecurityProfileGroupServiceTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc.py new file mode 100644 index 000000000000..2bbe20d88732 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc.py @@ -0,0 +1,854 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + +from .base import DEFAULT_CLIENT_INFO, SecurityProfileGroupServiceTransport + +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)!r}" + + 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.networksecurity.v1.SecurityProfileGroupService", + "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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SecurityProfileGroupServiceGrpcTransport(SecurityProfileGroupServiceTransport): + """gRPC backend transport for SecurityProfileGroupService. + + SecurityProfileGroup is a resource that defines an action for + specific threat signatures or severity levels. + + 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 = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_security_profile_groups( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfileGroupsRequest], + security_profile_group_service.ListSecurityProfileGroupsResponse, + ]: + r"""Return a callable for the list security profile groups method over gRPC. + + Lists SecurityProfileGroups in a given project and + location. + + Returns: + Callable[[~.ListSecurityProfileGroupsRequest], + ~.ListSecurityProfileGroupsResponse]: + 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_security_profile_groups" not in self._stubs: + self._stubs["list_security_profile_groups"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/ListSecurityProfileGroups", + request_serializer=security_profile_group_service.ListSecurityProfileGroupsRequest.serialize, + response_deserializer=security_profile_group_service.ListSecurityProfileGroupsResponse.deserialize, + ) + ) + return self._stubs["list_security_profile_groups"] + + @property + def get_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileGroupRequest], + security_profile_group.SecurityProfileGroup, + ]: + r"""Return a callable for the get security profile group method over gRPC. + + Gets details of a single SecurityProfileGroup. + + Returns: + Callable[[~.GetSecurityProfileGroupRequest], + ~.SecurityProfileGroup]: + 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_security_profile_group" not in self._stubs: + self._stubs["get_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/GetSecurityProfileGroup", + request_serializer=security_profile_group_service.GetSecurityProfileGroupRequest.serialize, + response_deserializer=security_profile_group.SecurityProfileGroup.deserialize, + ) + ) + return self._stubs["get_security_profile_group"] + + @property + def create_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileGroupRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create security profile group method over gRPC. + + Creates a new SecurityProfileGroup in a given project + and location. + + Returns: + Callable[[~.CreateSecurityProfileGroupRequest], + ~.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_security_profile_group" not in self._stubs: + self._stubs["create_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/CreateSecurityProfileGroup", + request_serializer=security_profile_group_service.CreateSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_security_profile_group"] + + @property + def update_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileGroupRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update security profile group method over gRPC. + + Updates the parameters of a single + SecurityProfileGroup. + + Returns: + Callable[[~.UpdateSecurityProfileGroupRequest], + ~.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 "update_security_profile_group" not in self._stubs: + self._stubs["update_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/UpdateSecurityProfileGroup", + request_serializer=security_profile_group_service.UpdateSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_security_profile_group"] + + @property + def delete_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileGroupRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete security profile group method over gRPC. + + Deletes a single SecurityProfileGroup. + + Returns: + Callable[[~.DeleteSecurityProfileGroupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_profile_group" not in self._stubs: + self._stubs["delete_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/DeleteSecurityProfileGroup", + request_serializer=security_profile_group_service.DeleteSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_security_profile_group"] + + @property + def list_security_profiles( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfilesRequest], + security_profile_group_service.ListSecurityProfilesResponse, + ]: + r"""Return a callable for the list security profiles method over gRPC. + + Lists SecurityProfiles in a given project and + location. + + Returns: + Callable[[~.ListSecurityProfilesRequest], + ~.ListSecurityProfilesResponse]: + 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_security_profiles" not in self._stubs: + self._stubs["list_security_profiles"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/ListSecurityProfiles", + request_serializer=security_profile_group_service.ListSecurityProfilesRequest.serialize, + response_deserializer=security_profile_group_service.ListSecurityProfilesResponse.deserialize, + ) + return self._stubs["list_security_profiles"] + + @property + def get_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileRequest], + security_profile_group.SecurityProfile, + ]: + r"""Return a callable for the get security profile method over gRPC. + + Gets details of a single SecurityProfile. + + Returns: + Callable[[~.GetSecurityProfileRequest], + ~.SecurityProfile]: + 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_security_profile" not in self._stubs: + self._stubs["get_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/GetSecurityProfile", + request_serializer=security_profile_group_service.GetSecurityProfileRequest.serialize, + response_deserializer=security_profile_group.SecurityProfile.deserialize, + ) + return self._stubs["get_security_profile"] + + @property + def create_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create security profile method over gRPC. + + Creates a new SecurityProfile in a given project and + location. + + Returns: + Callable[[~.CreateSecurityProfileRequest], + ~.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_security_profile" not in self._stubs: + self._stubs["create_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/CreateSecurityProfile", + request_serializer=security_profile_group_service.CreateSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_security_profile"] + + @property + def update_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update security profile method over gRPC. + + Updates the parameters of a single SecurityProfile. + + Returns: + Callable[[~.UpdateSecurityProfileRequest], + ~.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 "update_security_profile" not in self._stubs: + self._stubs["update_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/UpdateSecurityProfile", + request_serializer=security_profile_group_service.UpdateSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_security_profile"] + + @property + def delete_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete security profile method over gRPC. + + Deletes a single SecurityProfile. + + Returns: + Callable[[~.DeleteSecurityProfileRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_profile" not in self._stubs: + self._stubs["delete_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/DeleteSecurityProfile", + request_serializer=security_profile_group_service.DeleteSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_security_profile"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SecurityProfileGroupServiceGrpcTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc_asyncio.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..915eb529dc38 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/grpc_asyncio.py @@ -0,0 +1,969 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, 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.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + +from .base import DEFAULT_CLIENT_INFO, SecurityProfileGroupServiceTransport +from .grpc import SecurityProfileGroupServiceGrpcTransport + +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)!r}" + + 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.networksecurity.v1.SecurityProfileGroupService", + "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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SecurityProfileGroupServiceGrpcAsyncIOTransport( + SecurityProfileGroupServiceTransport +): + """gRPC AsyncIO backend transport for SecurityProfileGroupService. + + SecurityProfileGroup is a resource that defines an action for + specific threat signatures or severity levels. + + 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 = "networksecurity.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 = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_security_profile_groups( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfileGroupsRequest], + Awaitable[security_profile_group_service.ListSecurityProfileGroupsResponse], + ]: + r"""Return a callable for the list security profile groups method over gRPC. + + Lists SecurityProfileGroups in a given project and + location. + + Returns: + Callable[[~.ListSecurityProfileGroupsRequest], + Awaitable[~.ListSecurityProfileGroupsResponse]]: + 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_security_profile_groups" not in self._stubs: + self._stubs["list_security_profile_groups"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/ListSecurityProfileGroups", + request_serializer=security_profile_group_service.ListSecurityProfileGroupsRequest.serialize, + response_deserializer=security_profile_group_service.ListSecurityProfileGroupsResponse.deserialize, + ) + ) + return self._stubs["list_security_profile_groups"] + + @property + def get_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileGroupRequest], + Awaitable[security_profile_group.SecurityProfileGroup], + ]: + r"""Return a callable for the get security profile group method over gRPC. + + Gets details of a single SecurityProfileGroup. + + Returns: + Callable[[~.GetSecurityProfileGroupRequest], + Awaitable[~.SecurityProfileGroup]]: + 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_security_profile_group" not in self._stubs: + self._stubs["get_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/GetSecurityProfileGroup", + request_serializer=security_profile_group_service.GetSecurityProfileGroupRequest.serialize, + response_deserializer=security_profile_group.SecurityProfileGroup.deserialize, + ) + ) + return self._stubs["get_security_profile_group"] + + @property + def create_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileGroupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create security profile group method over gRPC. + + Creates a new SecurityProfileGroup in a given project + and location. + + Returns: + Callable[[~.CreateSecurityProfileGroupRequest], + 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_security_profile_group" not in self._stubs: + self._stubs["create_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/CreateSecurityProfileGroup", + request_serializer=security_profile_group_service.CreateSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_security_profile_group"] + + @property + def update_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileGroupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update security profile group method over gRPC. + + Updates the parameters of a single + SecurityProfileGroup. + + Returns: + Callable[[~.UpdateSecurityProfileGroupRequest], + 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 "update_security_profile_group" not in self._stubs: + self._stubs["update_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/UpdateSecurityProfileGroup", + request_serializer=security_profile_group_service.UpdateSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_security_profile_group"] + + @property + def delete_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileGroupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete security profile group method over gRPC. + + Deletes a single SecurityProfileGroup. + + Returns: + Callable[[~.DeleteSecurityProfileGroupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_profile_group" not in self._stubs: + self._stubs["delete_security_profile_group"] = ( + self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/DeleteSecurityProfileGroup", + request_serializer=security_profile_group_service.DeleteSecurityProfileGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_security_profile_group"] + + @property + def list_security_profiles( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfilesRequest], + Awaitable[security_profile_group_service.ListSecurityProfilesResponse], + ]: + r"""Return a callable for the list security profiles method over gRPC. + + Lists SecurityProfiles in a given project and + location. + + Returns: + Callable[[~.ListSecurityProfilesRequest], + Awaitable[~.ListSecurityProfilesResponse]]: + 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_security_profiles" not in self._stubs: + self._stubs["list_security_profiles"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/ListSecurityProfiles", + request_serializer=security_profile_group_service.ListSecurityProfilesRequest.serialize, + response_deserializer=security_profile_group_service.ListSecurityProfilesResponse.deserialize, + ) + return self._stubs["list_security_profiles"] + + @property + def get_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileRequest], + Awaitable[security_profile_group.SecurityProfile], + ]: + r"""Return a callable for the get security profile method over gRPC. + + Gets details of a single SecurityProfile. + + Returns: + Callable[[~.GetSecurityProfileRequest], + Awaitable[~.SecurityProfile]]: + 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_security_profile" not in self._stubs: + self._stubs["get_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/GetSecurityProfile", + request_serializer=security_profile_group_service.GetSecurityProfileRequest.serialize, + response_deserializer=security_profile_group.SecurityProfile.deserialize, + ) + return self._stubs["get_security_profile"] + + @property + def create_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create security profile method over gRPC. + + Creates a new SecurityProfile in a given project and + location. + + Returns: + Callable[[~.CreateSecurityProfileRequest], + 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_security_profile" not in self._stubs: + self._stubs["create_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/CreateSecurityProfile", + request_serializer=security_profile_group_service.CreateSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_security_profile"] + + @property + def update_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update security profile method over gRPC. + + Updates the parameters of a single SecurityProfile. + + Returns: + Callable[[~.UpdateSecurityProfileRequest], + 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 "update_security_profile" not in self._stubs: + self._stubs["update_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/UpdateSecurityProfile", + request_serializer=security_profile_group_service.UpdateSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_security_profile"] + + @property + def delete_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete security profile method over gRPC. + + Deletes a single SecurityProfile. + + Returns: + Callable[[~.DeleteSecurityProfileRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_security_profile" not in self._stubs: + self._stubs["delete_security_profile"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SecurityProfileGroupService/DeleteSecurityProfile", + request_serializer=security_profile_group_service.DeleteSecurityProfileRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_security_profile"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_security_profile_groups: self._wrap_method( + self.list_security_profile_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_security_profile_group: self._wrap_method( + self.get_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.create_security_profile_group: self._wrap_method( + self.create_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.update_security_profile_group: self._wrap_method( + self.update_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_profile_group: self._wrap_method( + self.delete_security_profile_group, + default_timeout=None, + client_info=client_info, + ), + self.list_security_profiles: self._wrap_method( + self.list_security_profiles, + default_timeout=None, + client_info=client_info, + ), + self.get_security_profile: self._wrap_method( + self.get_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.create_security_profile: self._wrap_method( + self.create_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.update_security_profile: self._wrap_method( + self.update_security_profile, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_profile: self._wrap_method( + self.delete_security_profile, + 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.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SecurityProfileGroupServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest.py new file mode 100644 index 000000000000..669ec16bbe10 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest.py @@ -0,0 +1,3961 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSecurityProfileGroupServiceRestTransport + +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 SecurityProfileGroupServiceRestInterceptor: + """Interceptor for SecurityProfileGroupService. + + 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 SecurityProfileGroupServiceRestTransport. + + .. code-block:: python + class MyCustomSecurityProfileGroupServiceInterceptor(SecurityProfileGroupServiceRestInterceptor): + def pre_create_security_profile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_security_profile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_security_profile_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_security_profile_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_security_profile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_security_profile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_security_profile_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_security_profile_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_security_profile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_security_profile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_security_profile_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_security_profile_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_security_profile_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_security_profile_groups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_security_profiles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_security_profiles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_profile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_profile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_profile_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_profile_group(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityProfileGroupServiceRestTransport(interceptor=MyCustomSecurityProfileGroupServiceInterceptor()) + client = SecurityProfileGroupServiceClient(transport=transport) + + + """ + + def pre_create_security_profile( + self, + request: security_profile_group_service.CreateSecurityProfileRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.CreateSecurityProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_security_profile + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_create_security_profile( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_security_profile + + DEPRECATED. Please use the `post_create_security_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_create_security_profile` interceptor runs + before the `post_create_security_profile_with_metadata` interceptor. + """ + return response + + def post_create_security_profile_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_security_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_create_security_profile_with_metadata` + interceptor in new development instead of the `post_create_security_profile` interceptor. + When both interceptors are used, this `post_create_security_profile_with_metadata` interceptor runs after the + `post_create_security_profile` interceptor. The (possibly modified) response returned by + `post_create_security_profile` will be passed to + `post_create_security_profile_with_metadata`. + """ + return response, metadata + + def pre_create_security_profile_group( + self, + request: security_profile_group_service.CreateSecurityProfileGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.CreateSecurityProfileGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_security_profile_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_create_security_profile_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_security_profile_group + + DEPRECATED. Please use the `post_create_security_profile_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_create_security_profile_group` interceptor runs + before the `post_create_security_profile_group_with_metadata` interceptor. + """ + return response + + def post_create_security_profile_group_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_security_profile_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_create_security_profile_group_with_metadata` + interceptor in new development instead of the `post_create_security_profile_group` interceptor. + When both interceptors are used, this `post_create_security_profile_group_with_metadata` interceptor runs after the + `post_create_security_profile_group` interceptor. The (possibly modified) response returned by + `post_create_security_profile_group` will be passed to + `post_create_security_profile_group_with_metadata`. + """ + return response, metadata + + def pre_delete_security_profile( + self, + request: security_profile_group_service.DeleteSecurityProfileRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.DeleteSecurityProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_security_profile + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_delete_security_profile( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_security_profile + + DEPRECATED. Please use the `post_delete_security_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_delete_security_profile` interceptor runs + before the `post_delete_security_profile_with_metadata` interceptor. + """ + return response + + def post_delete_security_profile_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_security_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_delete_security_profile_with_metadata` + interceptor in new development instead of the `post_delete_security_profile` interceptor. + When both interceptors are used, this `post_delete_security_profile_with_metadata` interceptor runs after the + `post_delete_security_profile` interceptor. The (possibly modified) response returned by + `post_delete_security_profile` will be passed to + `post_delete_security_profile_with_metadata`. + """ + return response, metadata + + def pre_delete_security_profile_group( + self, + request: security_profile_group_service.DeleteSecurityProfileGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.DeleteSecurityProfileGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_security_profile_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_delete_security_profile_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_security_profile_group + + DEPRECATED. Please use the `post_delete_security_profile_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_delete_security_profile_group` interceptor runs + before the `post_delete_security_profile_group_with_metadata` interceptor. + """ + return response + + def post_delete_security_profile_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_security_profile_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_delete_security_profile_group_with_metadata` + interceptor in new development instead of the `post_delete_security_profile_group` interceptor. + When both interceptors are used, this `post_delete_security_profile_group_with_metadata` interceptor runs after the + `post_delete_security_profile_group` interceptor. The (possibly modified) response returned by + `post_delete_security_profile_group` will be passed to + `post_delete_security_profile_group_with_metadata`. + """ + return response, metadata + + def pre_get_security_profile( + self, + request: security_profile_group_service.GetSecurityProfileRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.GetSecurityProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_security_profile + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_get_security_profile( + self, response: security_profile_group.SecurityProfile + ) -> security_profile_group.SecurityProfile: + """Post-rpc interceptor for get_security_profile + + DEPRECATED. Please use the `post_get_security_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_get_security_profile` interceptor runs + before the `post_get_security_profile_with_metadata` interceptor. + """ + return response + + def post_get_security_profile_with_metadata( + self, + response: security_profile_group.SecurityProfile, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group.SecurityProfile, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_security_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_get_security_profile_with_metadata` + interceptor in new development instead of the `post_get_security_profile` interceptor. + When both interceptors are used, this `post_get_security_profile_with_metadata` interceptor runs after the + `post_get_security_profile` interceptor. The (possibly modified) response returned by + `post_get_security_profile` will be passed to + `post_get_security_profile_with_metadata`. + """ + return response, metadata + + def pre_get_security_profile_group( + self, + request: security_profile_group_service.GetSecurityProfileGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.GetSecurityProfileGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_security_profile_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_get_security_profile_group( + self, response: security_profile_group.SecurityProfileGroup + ) -> security_profile_group.SecurityProfileGroup: + """Post-rpc interceptor for get_security_profile_group + + DEPRECATED. Please use the `post_get_security_profile_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_get_security_profile_group` interceptor runs + before the `post_get_security_profile_group_with_metadata` interceptor. + """ + return response + + def post_get_security_profile_group_with_metadata( + self, + response: security_profile_group.SecurityProfileGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group.SecurityProfileGroup, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_security_profile_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_get_security_profile_group_with_metadata` + interceptor in new development instead of the `post_get_security_profile_group` interceptor. + When both interceptors are used, this `post_get_security_profile_group_with_metadata` interceptor runs after the + `post_get_security_profile_group` interceptor. The (possibly modified) response returned by + `post_get_security_profile_group` will be passed to + `post_get_security_profile_group_with_metadata`. + """ + return response, metadata + + def pre_list_security_profile_groups( + self, + request: security_profile_group_service.ListSecurityProfileGroupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.ListSecurityProfileGroupsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_security_profile_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_list_security_profile_groups( + self, response: security_profile_group_service.ListSecurityProfileGroupsResponse + ) -> security_profile_group_service.ListSecurityProfileGroupsResponse: + """Post-rpc interceptor for list_security_profile_groups + + DEPRECATED. Please use the `post_list_security_profile_groups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_list_security_profile_groups` interceptor runs + before the `post_list_security_profile_groups_with_metadata` interceptor. + """ + return response + + def post_list_security_profile_groups_with_metadata( + self, + response: security_profile_group_service.ListSecurityProfileGroupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.ListSecurityProfileGroupsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_security_profile_groups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_list_security_profile_groups_with_metadata` + interceptor in new development instead of the `post_list_security_profile_groups` interceptor. + When both interceptors are used, this `post_list_security_profile_groups_with_metadata` interceptor runs after the + `post_list_security_profile_groups` interceptor. The (possibly modified) response returned by + `post_list_security_profile_groups` will be passed to + `post_list_security_profile_groups_with_metadata`. + """ + return response, metadata + + def pre_list_security_profiles( + self, + request: security_profile_group_service.ListSecurityProfilesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.ListSecurityProfilesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_security_profiles + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_list_security_profiles( + self, response: security_profile_group_service.ListSecurityProfilesResponse + ) -> security_profile_group_service.ListSecurityProfilesResponse: + """Post-rpc interceptor for list_security_profiles + + DEPRECATED. Please use the `post_list_security_profiles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_list_security_profiles` interceptor runs + before the `post_list_security_profiles_with_metadata` interceptor. + """ + return response + + def post_list_security_profiles_with_metadata( + self, + response: security_profile_group_service.ListSecurityProfilesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.ListSecurityProfilesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_security_profiles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_list_security_profiles_with_metadata` + interceptor in new development instead of the `post_list_security_profiles` interceptor. + When both interceptors are used, this `post_list_security_profiles_with_metadata` interceptor runs after the + `post_list_security_profiles` interceptor. The (possibly modified) response returned by + `post_list_security_profiles` will be passed to + `post_list_security_profiles_with_metadata`. + """ + return response, metadata + + def pre_update_security_profile( + self, + request: security_profile_group_service.UpdateSecurityProfileRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.UpdateSecurityProfileRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_security_profile + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_update_security_profile( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_security_profile + + DEPRECATED. Please use the `post_update_security_profile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_update_security_profile` interceptor runs + before the `post_update_security_profile_with_metadata` interceptor. + """ + return response + + def post_update_security_profile_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 update_security_profile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_update_security_profile_with_metadata` + interceptor in new development instead of the `post_update_security_profile` interceptor. + When both interceptors are used, this `post_update_security_profile_with_metadata` interceptor runs after the + `post_update_security_profile` interceptor. The (possibly modified) response returned by + `post_update_security_profile` will be passed to + `post_update_security_profile_with_metadata`. + """ + return response, metadata + + def pre_update_security_profile_group( + self, + request: security_profile_group_service.UpdateSecurityProfileGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + security_profile_group_service.UpdateSecurityProfileGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_security_profile_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_update_security_profile_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_security_profile_group + + DEPRECATED. Please use the `post_update_security_profile_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. This `post_update_security_profile_group` interceptor runs + before the `post_update_security_profile_group_with_metadata` interceptor. + """ + return response + + def post_update_security_profile_group_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 update_security_profile_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecurityProfileGroupService server but before it is returned to user code. + + We recommend only using this `post_update_security_profile_group_with_metadata` + interceptor in new development instead of the `post_update_security_profile_group` interceptor. + When both interceptors are used, this `post_update_security_profile_group_with_metadata` interceptor runs after the + `post_update_security_profile_group` interceptor. The (possibly modified) response returned by + `post_update_security_profile_group` will be passed to + `post_update_security_profile_group_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 SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SecurityProfileGroupService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityProfileGroupService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService 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 SecurityProfileGroupService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityProfileGroupServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityProfileGroupServiceRestInterceptor + + +class SecurityProfileGroupServiceRestTransport( + _BaseSecurityProfileGroupServiceRestTransport +): + """REST backend synchronous transport for SecurityProfileGroupService. + + SecurityProfileGroup is a resource that defines an action for + specific threat signatures or severity levels. + + 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 = "networksecurity.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[SecurityProfileGroupServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.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. + interceptor (Optional[SecurityProfileGroupServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 SecurityProfileGroupServiceRestInterceptor() + 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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateSecurityProfile( + _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.CreateSecurityProfile" + ) + + @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: security_profile_group_service.CreateSecurityProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create security profile method over HTTP. + + Args: + request (~.security_profile_group_service.CreateSecurityProfileRequest): + The request object. Request used by the + CreateSecurityProfile 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile._get_http_options() + + request, metadata = self._interceptor.pre_create_security_profile( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile._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.networksecurity_v1.SecurityProfileGroupServiceClient.CreateSecurityProfile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "CreateSecurityProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._CreateSecurityProfile._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_security_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_security_profile_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.networksecurity_v1.SecurityProfileGroupServiceClient.create_security_profile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "CreateSecurityProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSecurityProfileGroup( + _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.CreateSecurityProfileGroup" + ) + + @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: security_profile_group_service.CreateSecurityProfileGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create security profile + group method over HTTP. + + Args: + request (~.security_profile_group_service.CreateSecurityProfileGroupRequest): + The request object. Request used by the + CreateSecurityProfileGroup 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup._get_http_options() + + request, metadata = self._interceptor.pre_create_security_profile_group( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup._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.networksecurity_v1.SecurityProfileGroupServiceClient.CreateSecurityProfileGroup", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "CreateSecurityProfileGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._CreateSecurityProfileGroup._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_security_profile_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_security_profile_group_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.networksecurity_v1.SecurityProfileGroupServiceClient.create_security_profile_group", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "CreateSecurityProfileGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSecurityProfile( + _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfile, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.DeleteSecurityProfile" + ) + + @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: security_profile_group_service.DeleteSecurityProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete security profile method over HTTP. + + Args: + request (~.security_profile_group_service.DeleteSecurityProfileRequest): + The request object. Request used by the + DeleteSecurityProfile 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfile._get_http_options() + + request, metadata = self._interceptor.pre_delete_security_profile( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfile._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfile._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.networksecurity_v1.SecurityProfileGroupServiceClient.DeleteSecurityProfile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "DeleteSecurityProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._DeleteSecurityProfile._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_security_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_security_profile_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.networksecurity_v1.SecurityProfileGroupServiceClient.delete_security_profile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "DeleteSecurityProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSecurityProfileGroup( + _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfileGroup, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.DeleteSecurityProfileGroup" + ) + + @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: security_profile_group_service.DeleteSecurityProfileGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete security profile + group method over HTTP. + + Args: + request (~.security_profile_group_service.DeleteSecurityProfileGroupRequest): + The request object. Request used by the + DeleteSecurityProfileGroup 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfileGroup._get_http_options() + + request, metadata = self._interceptor.pre_delete_security_profile_group( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfileGroup._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfileGroup._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.networksecurity_v1.SecurityProfileGroupServiceClient.DeleteSecurityProfileGroup", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "DeleteSecurityProfileGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._DeleteSecurityProfileGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_security_profile_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_security_profile_group_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.networksecurity_v1.SecurityProfileGroupServiceClient.delete_security_profile_group", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "DeleteSecurityProfileGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSecurityProfile( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfile, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.GetSecurityProfile") + + @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: security_profile_group_service.GetSecurityProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> security_profile_group.SecurityProfile: + r"""Call the get security profile method over HTTP. + + Args: + request (~.security_profile_group_service.GetSecurityProfileRequest): + The request object. Request used by the + GetSecurityProfile 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: + ~.security_profile_group.SecurityProfile: + SecurityProfile is a resource that + defines the behavior for one of many + ProfileTypes. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfile._get_http_options() + + request, metadata = self._interceptor.pre_get_security_profile( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfile._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfile._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.networksecurity_v1.SecurityProfileGroupServiceClient.GetSecurityProfile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetSecurityProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._GetSecurityProfile._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 = security_profile_group.SecurityProfile() + pb_resp = security_profile_group.SecurityProfile.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_security_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_security_profile_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = security_profile_group.SecurityProfile.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.networksecurity_v1.SecurityProfileGroupServiceClient.get_security_profile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetSecurityProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSecurityProfileGroup( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfileGroup, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.GetSecurityProfileGroup" + ) + + @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: security_profile_group_service.GetSecurityProfileGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> security_profile_group.SecurityProfileGroup: + r"""Call the get security profile + group method over HTTP. + + Args: + request (~.security_profile_group_service.GetSecurityProfileGroupRequest): + The request object. Request used by the + GetSecurityProfileGroup 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: + ~.security_profile_group.SecurityProfileGroup: + SecurityProfileGroup is a resource + that defines the behavior for various + ProfileTypes. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfileGroup._get_http_options() + + request, metadata = self._interceptor.pre_get_security_profile_group( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfileGroup._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfileGroup._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.networksecurity_v1.SecurityProfileGroupServiceClient.GetSecurityProfileGroup", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetSecurityProfileGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._GetSecurityProfileGroup._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 = security_profile_group.SecurityProfileGroup() + pb_resp = security_profile_group.SecurityProfileGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_security_profile_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_security_profile_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + security_profile_group.SecurityProfileGroup.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.networksecurity_v1.SecurityProfileGroupServiceClient.get_security_profile_group", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetSecurityProfileGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSecurityProfileGroups( + _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfileGroups, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.ListSecurityProfileGroups" + ) + + @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: security_profile_group_service.ListSecurityProfileGroupsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> security_profile_group_service.ListSecurityProfileGroupsResponse: + r"""Call the list security profile + groups method over HTTP. + + Args: + request (~.security_profile_group_service.ListSecurityProfileGroupsRequest): + The request object. Request used with the + ListSecurityProfileGroups 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: + ~.security_profile_group_service.ListSecurityProfileGroupsResponse: + Response returned by the + ListSecurityProfileGroups method. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfileGroups._get_http_options() + + request, metadata = self._interceptor.pre_list_security_profile_groups( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfileGroups._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfileGroups._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.networksecurity_v1.SecurityProfileGroupServiceClient.ListSecurityProfileGroups", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListSecurityProfileGroups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._ListSecurityProfileGroups._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 = security_profile_group_service.ListSecurityProfileGroupsResponse() + pb_resp = ( + security_profile_group_service.ListSecurityProfileGroupsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_security_profile_groups(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_security_profile_groups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = security_profile_group_service.ListSecurityProfileGroupsResponse.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.networksecurity_v1.SecurityProfileGroupServiceClient.list_security_profile_groups", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListSecurityProfileGroups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSecurityProfiles( + _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfiles, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.ListSecurityProfiles") + + @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: security_profile_group_service.ListSecurityProfilesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> security_profile_group_service.ListSecurityProfilesResponse: + r"""Call the list security profiles method over HTTP. + + Args: + request (~.security_profile_group_service.ListSecurityProfilesRequest): + The request object. Request used with the + ListSecurityProfiles 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: + ~.security_profile_group_service.ListSecurityProfilesResponse: + Response returned by the + ListSecurityProfiles method. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfiles._get_http_options() + + request, metadata = self._interceptor.pre_list_security_profiles( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfiles._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfiles._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.networksecurity_v1.SecurityProfileGroupServiceClient.ListSecurityProfiles", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListSecurityProfiles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._ListSecurityProfiles._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 = security_profile_group_service.ListSecurityProfilesResponse() + pb_resp = security_profile_group_service.ListSecurityProfilesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_security_profiles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_security_profiles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = security_profile_group_service.ListSecurityProfilesResponse.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.networksecurity_v1.SecurityProfileGroupServiceClient.list_security_profiles", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListSecurityProfiles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSecurityProfile( + _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.UpdateSecurityProfile" + ) + + @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: security_profile_group_service.UpdateSecurityProfileRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update security profile method over HTTP. + + Args: + request (~.security_profile_group_service.UpdateSecurityProfileRequest): + The request object. Request used by the + UpdateSecurityProfile 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile._get_http_options() + + request, metadata = self._interceptor.pre_update_security_profile( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile._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.networksecurity_v1.SecurityProfileGroupServiceClient.UpdateSecurityProfile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "UpdateSecurityProfile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._UpdateSecurityProfile._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_update_security_profile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_security_profile_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.networksecurity_v1.SecurityProfileGroupServiceClient.update_security_profile", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "UpdateSecurityProfile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSecurityProfileGroup( + _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash( + "SecurityProfileGroupServiceRestTransport.UpdateSecurityProfileGroup" + ) + + @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: security_profile_group_service.UpdateSecurityProfileGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update security profile + group method over HTTP. + + Args: + request (~.security_profile_group_service.UpdateSecurityProfileGroupRequest): + The request object. Request used by the + UpdateSecurityProfileGroup 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup._get_http_options() + + request, metadata = self._interceptor.pre_update_security_profile_group( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup._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.networksecurity_v1.SecurityProfileGroupServiceClient.UpdateSecurityProfileGroup", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "UpdateSecurityProfileGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._UpdateSecurityProfileGroup._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_update_security_profile_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_security_profile_group_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.networksecurity_v1.SecurityProfileGroupServiceClient.update_security_profile_group", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "UpdateSecurityProfileGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileRequest], + 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._CreateSecurityProfile(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.CreateSecurityProfileGroupRequest], + 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._CreateSecurityProfileGroup( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileRequest], + 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._DeleteSecurityProfile(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.DeleteSecurityProfileGroupRequest], + 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._DeleteSecurityProfileGroup( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileRequest], + security_profile_group.SecurityProfile, + ]: + # 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._GetSecurityProfile(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.GetSecurityProfileGroupRequest], + security_profile_group.SecurityProfileGroup, + ]: + # 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._GetSecurityProfileGroup( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_security_profile_groups( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfileGroupsRequest], + security_profile_group_service.ListSecurityProfileGroupsResponse, + ]: + # 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._ListSecurityProfileGroups( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_security_profiles( + self, + ) -> Callable[ + [security_profile_group_service.ListSecurityProfilesRequest], + security_profile_group_service.ListSecurityProfilesResponse, + ]: + # 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._ListSecurityProfiles(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_profile( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileRequest], + 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._UpdateSecurityProfile(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_profile_group( + self, + ) -> Callable[ + [security_profile_group_service.UpdateSecurityProfileGroupRequest], + 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._UpdateSecurityProfileGroup( + 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( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetLocation, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.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 = _BaseSecurityProfileGroupServiceRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "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( + _BaseSecurityProfileGroupServiceRestTransport._BaseListLocations, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.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 = _BaseSecurityProfileGroupServiceRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetIamPolicy, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.GetIamPolicy") + + @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: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseGetIamPolicy._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.networksecurity_v1.SecurityProfileGroupServiceClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._GetIamPolicy._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 = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSecurityProfileGroupServiceRestTransport._BaseSetIamPolicy, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.SetIamPolicy") + + @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: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseSetIamPolicy._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.networksecurity_v1.SecurityProfileGroupServiceClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._SetIamPolicy._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) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSecurityProfileGroupServiceRestTransport._BaseTestIamPermissions, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.TestIamPermissions") + + @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: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseTestIamPermissions._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.networksecurity_v1.SecurityProfileGroupServiceClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecurityProfileGroupServiceRestTransport._TestIamPermissions._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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "TestIamPermissions", + "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( + _BaseSecurityProfileGroupServiceRestTransport._BaseCancelOperation, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseSecurityProfileGroupServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteOperation, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.SecurityProfileGroupServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetOperation, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.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 = _BaseSecurityProfileGroupServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "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( + _BaseSecurityProfileGroupServiceRestTransport._BaseListOperations, + SecurityProfileGroupServiceRestStub, + ): + def __hash__(self): + return hash("SecurityProfileGroupServiceRestTransport.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 = _BaseSecurityProfileGroupServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseSecurityProfileGroupServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecurityProfileGroupServiceRestTransport._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.networksecurity_v1.SecurityProfileGroupServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "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__ = ("SecurityProfileGroupServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest_base.py new file mode 100644 index 000000000000..e89b1b578174 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/security_profile_group_service/transports/rest_base.py @@ -0,0 +1,979 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.network_security_v1.types import ( + security_profile_group, + security_profile_group_service, +) + +from .base import DEFAULT_CLIENT_INFO, SecurityProfileGroupServiceTransport + + +class _BaseSecurityProfileGroupServiceRestTransport( + SecurityProfileGroupServiceTransport +): + """Base REST backend transport for SecurityProfileGroupService. + + 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 = "networksecurity.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: 'networksecurity.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 _BaseCreateSecurityProfile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "securityProfileId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/securityProfiles", + "body": "security_profile", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = security_profile_group_service.CreateSecurityProfileRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfile._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSecurityProfileGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "securityProfileGroupId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/securityProfileGroups", + "body": "security_profile_group", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + security_profile_group_service.CreateSecurityProfileGroupRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseCreateSecurityProfileGroup._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSecurityProfile: + 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": "/v1/{name=projects/*/locations/*/securityProfiles/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = security_profile_group_service.DeleteSecurityProfileRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfile._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSecurityProfileGroup: + 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": "/v1/{name=projects/*/locations/*/securityProfileGroups/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + security_profile_group_service.DeleteSecurityProfileGroupRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseDeleteSecurityProfileGroup._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSecurityProfile: + 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": "/v1/{name=projects/*/locations/*/securityProfiles/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = security_profile_group_service.GetSecurityProfileRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfile._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSecurityProfileGroup: + 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": "/v1/{name=projects/*/locations/*/securityProfileGroups/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + security_profile_group_service.GetSecurityProfileGroupRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseGetSecurityProfileGroup._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSecurityProfileGroups: + 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": "/v1/{parent=projects/*/locations/*}/securityProfileGroups", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + security_profile_group_service.ListSecurityProfileGroupsRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfileGroups._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSecurityProfiles: + 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": "/v1/{parent=projects/*/locations/*}/securityProfiles", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = security_profile_group_service.ListSecurityProfilesRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseListSecurityProfiles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSecurityProfile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v1/{security_profile.name=projects/*/locations/*/securityProfiles/*}", + "body": "security_profile", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = security_profile_group_service.UpdateSecurityProfileRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfile._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSecurityProfileGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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": "/v1/{security_profile_group.name=projects/*/locations/*/securityProfileGroups/*}", + "body": "security_profile_group", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + security_profile_group_service.UpdateSecurityProfileGroupRequest.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( + _BaseSecurityProfileGroupServiceRestTransport._BaseUpdateSecurityProfileGroup._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": "/v1/{name=projects/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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": "/v1/{name=projects/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*}/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 _BaseGetIamPolicy: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:getIamPolicy", + }, + ] + 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 _BaseSetIamPolicy: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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__ = ("_BaseSecurityProfileGroupServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/__init__.py new file mode 100644 index 000000000000..4bf4882d291c --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SSERealmServiceAsyncClient +from .client import SSERealmServiceClient + +__all__ = ( + "SSERealmServiceClient", + "SSERealmServiceAsyncClient", +) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/async_client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/async_client.py new file mode 100644 index 000000000000..83562eae2840 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/async_client.py @@ -0,0 +1,2058 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_security_v1.services.sse_realm_service import pagers +from google.cloud.network_security_v1.types import common, sse_realm + +from .client import SSERealmServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SSERealmServiceTransport +from .transports.grpc_asyncio import SSERealmServiceGrpcAsyncIOTransport + +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 SSERealmServiceAsyncClient: + """Service describing handlers for resources""" + + _client: SSERealmServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SSERealmServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SSERealmServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SSERealmServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SSERealmServiceClient._DEFAULT_UNIVERSE + + sac_attachment_path = staticmethod(SSERealmServiceClient.sac_attachment_path) + parse_sac_attachment_path = staticmethod( + SSERealmServiceClient.parse_sac_attachment_path + ) + sac_realm_path = staticmethod(SSERealmServiceClient.sac_realm_path) + parse_sac_realm_path = staticmethod(SSERealmServiceClient.parse_sac_realm_path) + common_billing_account_path = staticmethod( + SSERealmServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SSERealmServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SSERealmServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SSERealmServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SSERealmServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SSERealmServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SSERealmServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SSERealmServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SSERealmServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SSERealmServiceClient.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: + SSERealmServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SSERealmServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SSERealmServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SSERealmServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SSERealmServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SSERealmServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SSERealmServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SSERealmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SSERealmServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = SSERealmServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, SSERealmServiceTransport, Callable[..., SSERealmServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sse realm service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SSERealmServiceTransport,Callable[..., SSERealmServiceTransport]]]): + 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 SSERealmServiceTransport 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 = SSERealmServiceClient( + 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.networksecurity_v1.SSERealmServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "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.networksecurity.v1.SSERealmService", + "credentialsType": None, + }, + ) + + async def list_sac_realms( + self, + request: Optional[Union[sse_realm.ListSACRealmsRequest, 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.ListSACRealmsAsyncPager: + r"""Lists SACRealms in a given project. + + .. 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 network_security_v1 + + async def sample_list_sac_realms(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACRealmsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_realms(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListSACRealmsRequest, dict]]): + The request object. Request for ``ListSACRealms`` method. + parent (:class:`str`): + Required. The parent, in the form + ``projects/{project}/locations/global``. + + 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.network_security_v1.services.sse_realm_service.pagers.ListSACRealmsAsyncPager: + Response for ListSACRealms method. + + 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, sse_realm.ListSACRealmsRequest): + request = sse_realm.ListSACRealmsRequest(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_sac_realms + ] + + # 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.ListSACRealmsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_sac_realm( + self, + request: Optional[Union[sse_realm.GetSACRealmRequest, 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]]] = (), + ) -> sse_realm.SACRealm: + r"""Returns the specified realm. + + .. 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 network_security_v1 + + async def sample_get_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACRealmRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sac_realm(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetSACRealmRequest, dict]]): + The request object. Request for ``GetSACRealm`` method. + name (:class:`str`): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + + 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.network_security_v1.types.SACRealm: + Represents a Secure Access Connect + (SAC) realm resource. + A Secure Access Connect realm + establishes a connection between your + Google Cloud project and an SSE 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, sse_realm.GetSACRealmRequest): + request = sse_realm.GetSACRealmRequest(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_sac_realm + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sac_realm( + self, + request: Optional[Union[sse_realm.CreateSACRealmRequest, dict]] = None, + *, + parent: Optional[str] = None, + sac_realm: Optional[sse_realm.SACRealm] = None, + sac_realm_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new SACRealm in a given project. + + .. 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 network_security_v1 + + async def sample_create_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + + # Make the request + operation = await client.create_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateSACRealmRequest, dict]]): + The request object. Request for ``CreateSACRealm`` method. + parent (:class:`str`): + Required. The parent, in the form + ``projects/{project}/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_realm (:class:`google.cloud.network_security_v1.types.SACRealm`): + Required. The resource being created. + This corresponds to the ``sac_realm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_realm_id (:class:`str`): + Required. ID of the created realm. The ID must be 1-63 + characters long, and comply with RFC1035. Specifically, + it must be 1-63 characters long and match the regular + expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means + the first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``sac_realm_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.SACRealm` + Represents a Secure Access Connect (SAC) realm resource. + + A Secure Access Connect realm establishes a + connection between your Google Cloud project and an + SSE 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, sac_realm, sac_realm_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, sse_realm.CreateSACRealmRequest): + request = sse_realm.CreateSACRealmRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sac_realm is not None: + request.sac_realm = sac_realm + if sac_realm_id is not None: + request.sac_realm_id = sac_realm_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_sac_realm + ] + + # 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, + sse_realm.SACRealm, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_sac_realm( + self, + request: Optional[Union[sse_realm.DeleteSACRealmRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified realm. + + .. 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 network_security_v1 + + async def sample_delete_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACRealmRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteSACRealmRequest, dict]]): + The request object. Request for ``DeleteSACRealm`` method. + name (:class:`str`): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sse_realm.DeleteSACRealmRequest): + request = sse_realm.DeleteSACRealmRequest(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_sac_realm + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_sac_attachments( + self, + request: Optional[Union[sse_realm.ListSACAttachmentsRequest, 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.ListSACAttachmentsAsyncPager: + r"""Lists SACAttachments in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_sac_attachments(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACAttachmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_attachments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListSACAttachmentsRequest, dict]]): + The request object. Request for ``ListSACAttachments`` method. + parent (:class:`str`): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + + 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.network_security_v1.services.sse_realm_service.pagers.ListSACAttachmentsAsyncPager: + Response for ListSACAttachments method. + + 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, sse_realm.ListSACAttachmentsRequest): + request = sse_realm.ListSACAttachmentsRequest(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_sac_attachments + ] + + # 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.ListSACAttachmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_sac_attachment( + self, + request: Optional[Union[sse_realm.GetSACAttachmentRequest, 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]]] = (), + ) -> sse_realm.SACAttachment: + r"""Returns the specified attachment. + + .. 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 network_security_v1 + + async def sample_get_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sac_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetSACAttachmentRequest, dict]]): + The request object. Request for ``GetSACAttachment`` method. + name (:class:`str`): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + + 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.network_security_v1.types.SACAttachment: + Represents a Secure Access Connect + (SAC) attachment resource. + A Secure Access Connect attachment + enables NCC Gateway to process traffic + with an SSE product. + + """ + # 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, sse_realm.GetSACAttachmentRequest): + request = sse_realm.GetSACAttachmentRequest(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_sac_attachment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sac_attachment( + self, + request: Optional[Union[sse_realm.CreateSACAttachmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + sac_attachment: Optional[sse_realm.SACAttachment] = None, + sac_attachment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new SACAttachment in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + sac_attachment = network_security_v1.SACAttachment() + sac_attachment.sac_realm = "sac_realm_value" + sac_attachment.ncc_gateway = "ncc_gateway_value" + + request = network_security_v1.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + sac_attachment=sac_attachment, + ) + + # Make the request + operation = await client.create_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateSACAttachmentRequest, dict]]): + The request object. Request for ``CreateSACAttachment`` method. + parent (:class:`str`): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_attachment (:class:`google.cloud.network_security_v1.types.SACAttachment`): + Required. The resource being created. + This corresponds to the ``sac_attachment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_attachment_id (:class:`str`): + Required. ID of the created attachment. The ID must be + 1-63 characters long, and comply with RFC1035. + Specifically, it must be 1-63 characters long and match + the regular expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` + which means the first character must be a lowercase + letter, and all following characters must be a dash, + lowercase letter, or digit, except the last character, + which cannot be a dash. + + This corresponds to the ``sac_attachment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.SACAttachment` + Represents a Secure Access Connect (SAC) attachment + resource. + + A Secure Access Connect attachment enables NCC + Gateway to process traffic with an SSE product. + + """ + # 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, sac_attachment, sac_attachment_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, sse_realm.CreateSACAttachmentRequest): + request = sse_realm.CreateSACAttachmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sac_attachment is not None: + request.sac_attachment = sac_attachment + if sac_attachment_id is not None: + request.sac_attachment_id = sac_attachment_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_sac_attachment + ] + + # 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, + sse_realm.SACAttachment, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_sac_attachment( + self, + request: Optional[Union[sse_realm.DeleteSACAttachmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified attachment. + + .. 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 network_security_v1 + + async def sample_delete_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACAttachmentRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteSACAttachmentRequest, dict]]): + The request object. Request for ``DeleteSACAttachment`` method. + name (:class:`str`): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sse_realm.DeleteSACAttachmentRequest): + request = sse_realm.DeleteSACAttachmentRequest(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_sac_attachment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[Union[locations_pb2.ListLocationsRequest, dict]] = 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SSERealmServiceAsyncClient": + 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__ = ("SSERealmServiceAsyncClient",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/client.py new file mode 100644 index 000000000000..dc237cac0948 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/client.py @@ -0,0 +1,2518 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_security_v1.services.sse_realm_service import pagers +from google.cloud.network_security_v1.types import common, sse_realm + +from .transports.base import DEFAULT_CLIENT_INFO, SSERealmServiceTransport +from .transports.grpc import SSERealmServiceGrpcTransport +from .transports.grpc_asyncio import SSERealmServiceGrpcAsyncIOTransport +from .transports.rest import SSERealmServiceRestTransport + + +class SSERealmServiceClientMeta(type): + """Metaclass for the SSERealmService 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[SSERealmServiceTransport]] + _transport_registry["grpc"] = SSERealmServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SSERealmServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SSERealmServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SSERealmServiceTransport]: + """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 SSERealmServiceClient(metaclass=SSERealmServiceClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{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: + SSERealmServiceClient: 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: + SSERealmServiceClient: 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) -> SSERealmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SSERealmServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def sac_attachment_path( + project: str, + location: str, + sac_attachment: str, + ) -> str: + """Returns a fully-qualified sac_attachment string.""" + return "projects/{project}/locations/{location}/sacAttachments/{sac_attachment}".format( + project=project, + location=location, + sac_attachment=sac_attachment, + ) + + @staticmethod + def parse_sac_attachment_path(path: str) -> Dict[str, str]: + """Parses a sac_attachment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sacAttachments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def sac_realm_path( + project: str, + location: str, + sac_realm: str, + ) -> str: + """Returns a fully-qualified sac_realm string.""" + return "projects/{project}/locations/{location}/sacRealms/{sac_realm}".format( + project=project, + location=location, + sac_realm=sac_realm, + ) + + @staticmethod + def parse_sac_realm_path(path: str) -> Dict[str, str]: + """Parses a sac_realm path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sacRealms/(?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 = SSERealmServiceClient._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 = SSERealmServiceClient._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 + ) -> str: + """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 = SSERealmServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SSERealmServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SSERealmServiceClient._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 = SSERealmServiceClient._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) -> str: + """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, SSERealmServiceTransport, Callable[..., SSERealmServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sse realm service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SSERealmServiceTransport,Callable[..., SSERealmServiceTransport]]]): + 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 SSERealmServiceTransport 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 = ( + SSERealmServiceClient._read_environment_variables() + ) + self._client_cert_source = SSERealmServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SSERealmServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, SSERealmServiceTransport) + if transport_provided: + # transport is a SSERealmServiceTransport 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(SSERealmServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SSERealmServiceClient._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[SSERealmServiceTransport], Callable[..., SSERealmServiceTransport] + ] = ( + SSERealmServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SSERealmServiceTransport], 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.networksecurity_v1.SSERealmServiceClient`.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "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.networksecurity.v1.SSERealmService", + "credentialsType": None, + }, + ) + + def list_sac_realms( + self, + request: Optional[Union[sse_realm.ListSACRealmsRequest, 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.ListSACRealmsPager: + r"""Lists SACRealms in a given project. + + .. 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 network_security_v1 + + def sample_list_sac_realms(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACRealmsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_realms(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListSACRealmsRequest, dict]): + The request object. Request for ``ListSACRealms`` method. + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/global``. + + 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.network_security_v1.services.sse_realm_service.pagers.ListSACRealmsPager: + Response for ListSACRealms method. + + 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, sse_realm.ListSACRealmsRequest): + request = sse_realm.ListSACRealmsRequest(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_sac_realms] + + # 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.ListSACRealmsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_sac_realm( + self, + request: Optional[Union[sse_realm.GetSACRealmRequest, 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]]] = (), + ) -> sse_realm.SACRealm: + r"""Returns the specified realm. + + .. 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 network_security_v1 + + def sample_get_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACRealmRequest( + name="name_value", + ) + + # Make the request + response = client.get_sac_realm(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetSACRealmRequest, dict]): + The request object. Request for ``GetSACRealm`` method. + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + + 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.network_security_v1.types.SACRealm: + Represents a Secure Access Connect + (SAC) realm resource. + A Secure Access Connect realm + establishes a connection between your + Google Cloud project and an SSE 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, sse_realm.GetSACRealmRequest): + request = sse_realm.GetSACRealmRequest(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_sac_realm] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sac_realm( + self, + request: Optional[Union[sse_realm.CreateSACRealmRequest, dict]] = None, + *, + parent: Optional[str] = None, + sac_realm: Optional[sse_realm.SACRealm] = None, + sac_realm_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new SACRealm in a given project. + + .. 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 network_security_v1 + + def sample_create_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + + # Make the request + operation = client.create_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateSACRealmRequest, dict]): + The request object. Request for ``CreateSACRealm`` method. + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/global``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_realm (google.cloud.network_security_v1.types.SACRealm): + Required. The resource being created. + This corresponds to the ``sac_realm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_realm_id (str): + Required. ID of the created realm. The ID must be 1-63 + characters long, and comply with RFC1035. Specifically, + it must be 1-63 characters long and match the regular + expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means + the first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + + This corresponds to the ``sac_realm_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.SACRealm` + Represents a Secure Access Connect (SAC) realm resource. + + A Secure Access Connect realm establishes a + connection between your Google Cloud project and an + SSE 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, sac_realm, sac_realm_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, sse_realm.CreateSACRealmRequest): + request = sse_realm.CreateSACRealmRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sac_realm is not None: + request.sac_realm = sac_realm + if sac_realm_id is not None: + request.sac_realm_id = sac_realm_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sac_realm] + + # 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, + sse_realm.SACRealm, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_sac_realm( + self, + request: Optional[Union[sse_realm.DeleteSACRealmRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified realm. + + .. 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 network_security_v1 + + def sample_delete_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACRealmRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteSACRealmRequest, dict]): + The request object. Request for ``DeleteSACRealm`` method. + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sse_realm.DeleteSACRealmRequest): + request = sse_realm.DeleteSACRealmRequest(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_sac_realm] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_sac_attachments( + self, + request: Optional[Union[sse_realm.ListSACAttachmentsRequest, 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.ListSACAttachmentsPager: + r"""Lists SACAttachments in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_sac_attachments(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACAttachmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_attachments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListSACAttachmentsRequest, dict]): + The request object. Request for ``ListSACAttachments`` method. + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + + 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.network_security_v1.services.sse_realm_service.pagers.ListSACAttachmentsPager: + Response for ListSACAttachments method. + + 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, sse_realm.ListSACAttachmentsRequest): + request = sse_realm.ListSACAttachmentsRequest(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_sac_attachments] + + # 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.ListSACAttachmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_sac_attachment( + self, + request: Optional[Union[sse_realm.GetSACAttachmentRequest, 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]]] = (), + ) -> sse_realm.SACAttachment: + r"""Returns the specified attachment. + + .. 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 network_security_v1 + + def sample_get_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_sac_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetSACAttachmentRequest, dict]): + The request object. Request for ``GetSACAttachment`` method. + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + + 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.network_security_v1.types.SACAttachment: + Represents a Secure Access Connect + (SAC) attachment resource. + A Secure Access Connect attachment + enables NCC Gateway to process traffic + with an SSE product. + + """ + # 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, sse_realm.GetSACAttachmentRequest): + request = sse_realm.GetSACAttachmentRequest(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_sac_attachment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sac_attachment( + self, + request: Optional[Union[sse_realm.CreateSACAttachmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + sac_attachment: Optional[sse_realm.SACAttachment] = None, + sac_attachment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new SACAttachment in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + sac_attachment = network_security_v1.SACAttachment() + sac_attachment.sac_realm = "sac_realm_value" + sac_attachment.ncc_gateway = "ncc_gateway_value" + + request = network_security_v1.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + sac_attachment=sac_attachment, + ) + + # Make the request + operation = client.create_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateSACAttachmentRequest, dict]): + The request object. Request for ``CreateSACAttachment`` method. + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_attachment (google.cloud.network_security_v1.types.SACAttachment): + Required. The resource being created. + This corresponds to the ``sac_attachment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sac_attachment_id (str): + Required. ID of the created attachment. The ID must be + 1-63 characters long, and comply with RFC1035. + Specifically, it must be 1-63 characters long and match + the regular expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` + which means the first character must be a lowercase + letter, and all following characters must be a dash, + lowercase letter, or digit, except the last character, + which cannot be a dash. + + This corresponds to the ``sac_attachment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.network_security_v1.types.SACAttachment` + Represents a Secure Access Connect (SAC) attachment + resource. + + A Secure Access Connect attachment enables NCC + Gateway to process traffic with an SSE product. + + """ + # 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, sac_attachment, sac_attachment_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, sse_realm.CreateSACAttachmentRequest): + request = sse_realm.CreateSACAttachmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sac_attachment is not None: + request.sac_attachment = sac_attachment + if sac_attachment_id is not None: + request.sac_attachment_id = sac_attachment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sac_attachment] + + # 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, + sse_realm.SACAttachment, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_sac_attachment( + self, + request: Optional[Union[sse_realm.DeleteSACAttachmentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified attachment. + + .. 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 network_security_v1 + + def sample_delete_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACAttachmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteSACAttachmentRequest, dict]): + The request object. Request for ``DeleteSACAttachment`` method. + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, sse_realm.DeleteSACAttachmentRequest): + request = sse_realm.DeleteSACAttachmentRequest(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_sac_attachment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SSERealmServiceClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = 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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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[Union[operations_pb2.GetOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # 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 request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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 test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` 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 request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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_location( + self, + request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = 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 request is None: + request_pb = locations_pb2.GetLocationRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.GetLocationRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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[Union[locations_pb2.ListLocationsRequest, dict]] = 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 request is None: + request_pb = locations_pb2.ListLocationsRequest() + elif isinstance(request, dict): + request_pb = locations_pb2.ListLocationsRequest(**request) + else: + request_pb = 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_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + 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__ = ("SSERealmServiceClient",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/pagers.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/pagers.py new file mode 100644 index 000000000000..dcef235e9efb --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/pagers.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from 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.network_security_v1.types import sse_realm + + +class ListSACRealmsPager: + """A pager for iterating through ``list_sac_realms`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSACRealmsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sac_realms`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSACRealms`` requests and continue to iterate + through the ``sac_realms`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSACRealmsResponse` + 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[..., sse_realm.ListSACRealmsResponse], + request: sse_realm.ListSACRealmsRequest, + response: sse_realm.ListSACRealmsResponse, + *, + 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.network_security_v1.types.ListSACRealmsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSACRealmsResponse): + 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 = sse_realm.ListSACRealmsRequest(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[sse_realm.ListSACRealmsResponse]: + 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[sse_realm.SACRealm]: + for page in self.pages: + yield from page.sac_realms + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSACRealmsAsyncPager: + """A pager for iterating through ``list_sac_realms`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSACRealmsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sac_realms`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSACRealms`` requests and continue to iterate + through the ``sac_realms`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSACRealmsResponse` + 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[sse_realm.ListSACRealmsResponse]], + request: sse_realm.ListSACRealmsRequest, + response: sse_realm.ListSACRealmsResponse, + *, + 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.network_security_v1.types.ListSACRealmsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSACRealmsResponse): + 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 = sse_realm.ListSACRealmsRequest(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[sse_realm.ListSACRealmsResponse]: + 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[sse_realm.SACRealm]: + async def async_generator(): + async for page in self.pages: + for response in page.sac_realms: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSACAttachmentsPager: + """A pager for iterating through ``list_sac_attachments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSACAttachmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sac_attachments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSACAttachments`` requests and continue to iterate + through the ``sac_attachments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSACAttachmentsResponse` + 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[..., sse_realm.ListSACAttachmentsResponse], + request: sse_realm.ListSACAttachmentsRequest, + response: sse_realm.ListSACAttachmentsResponse, + *, + 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.network_security_v1.types.ListSACAttachmentsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSACAttachmentsResponse): + 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 = sse_realm.ListSACAttachmentsRequest(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[sse_realm.ListSACAttachmentsResponse]: + 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[sse_realm.SACAttachment]: + for page in self.pages: + yield from page.sac_attachments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSACAttachmentsAsyncPager: + """A pager for iterating through ``list_sac_attachments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListSACAttachmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sac_attachments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSACAttachments`` requests and continue to iterate + through the ``sac_attachments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListSACAttachmentsResponse` + 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[sse_realm.ListSACAttachmentsResponse]], + request: sse_realm.ListSACAttachmentsRequest, + response: sse_realm.ListSACAttachmentsResponse, + *, + 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.network_security_v1.types.ListSACAttachmentsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListSACAttachmentsResponse): + 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 = sse_realm.ListSACAttachmentsRequest(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[sse_realm.ListSACAttachmentsResponse]: + 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[sse_realm.SACAttachment]: + async def async_generator(): + async for page in self.pages: + for response in page.sac_attachments: + 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-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/README.rst b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/README.rst new file mode 100644 index 000000000000..8a25b7b14758 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``SSERealmServiceTransport`` is the ABC for all transports. + +- public child ``SSERealmServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``SSERealmServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseSSERealmServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``SSERealmServiceRestTransport`` 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-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/__init__.py new file mode 100644 index 000000000000..cf867abe90a9 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SSERealmServiceTransport +from .grpc import SSERealmServiceGrpcTransport +from .grpc_asyncio import SSERealmServiceGrpcAsyncIOTransport +from .rest import SSERealmServiceRestInterceptor, SSERealmServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SSERealmServiceTransport]] +_transport_registry["grpc"] = SSERealmServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SSERealmServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SSERealmServiceRestTransport + +__all__ = ( + "SSERealmServiceTransport", + "SSERealmServiceGrpcTransport", + "SSERealmServiceGrpcAsyncIOTransport", + "SSERealmServiceRestTransport", + "SSERealmServiceRestInterceptor", +) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/base.py new file mode 100644 index 000000000000..e0ac7676b3b8 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/base.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.network_security_v1 import gapic_version as package_version +from google.cloud.network_security_v1.types import sse_realm + +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 SSERealmServiceTransport(abc.ABC): + """Abstract transport class for SSERealmService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_sac_realms: gapic_v1.method.wrap_method( + self.list_sac_realms, + default_timeout=None, + client_info=client_info, + ), + self.get_sac_realm: gapic_v1.method.wrap_method( + self.get_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.create_sac_realm: gapic_v1.method.wrap_method( + self.create_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.delete_sac_realm: gapic_v1.method.wrap_method( + self.delete_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.list_sac_attachments: gapic_v1.method.wrap_method( + self.list_sac_attachments, + default_timeout=None, + client_info=client_info, + ), + self.get_sac_attachment: gapic_v1.method.wrap_method( + self.get_sac_attachment, + default_timeout=None, + client_info=client_info, + ), + self.create_sac_attachment: gapic_v1.method.wrap_method( + self.create_sac_attachment, + default_timeout=None, + client_info=client_info, + ), + self.delete_sac_attachment: gapic_v1.method.wrap_method( + self.delete_sac_attachment, + 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.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_sac_realms( + self, + ) -> Callable[ + [sse_realm.ListSACRealmsRequest], + Union[ + sse_realm.ListSACRealmsResponse, Awaitable[sse_realm.ListSACRealmsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_sac_realm( + self, + ) -> Callable[ + [sse_realm.GetSACRealmRequest], + Union[sse_realm.SACRealm, Awaitable[sse_realm.SACRealm]], + ]: + raise NotImplementedError() + + @property + def create_sac_realm( + self, + ) -> Callable[ + [sse_realm.CreateSACRealmRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_sac_realm( + self, + ) -> Callable[ + [sse_realm.DeleteSACRealmRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_sac_attachments( + self, + ) -> Callable[ + [sse_realm.ListSACAttachmentsRequest], + Union[ + sse_realm.ListSACAttachmentsResponse, + Awaitable[sse_realm.ListSACAttachmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_sac_attachment( + self, + ) -> Callable[ + [sse_realm.GetSACAttachmentRequest], + Union[sse_realm.SACAttachment, Awaitable[sse_realm.SACAttachment]], + ]: + raise NotImplementedError() + + @property + def create_sac_attachment( + self, + ) -> Callable[ + [sse_realm.CreateSACAttachmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_sac_attachment( + self, + ) -> Callable[ + [sse_realm.DeleteSACAttachmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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__ = ("SSERealmServiceTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc.py new file mode 100644 index 000000000000..80ad599ec4e7 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc.py @@ -0,0 +1,756 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.network_security_v1.types import sse_realm + +from .base import DEFAULT_CLIENT_INFO, SSERealmServiceTransport + +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)!r}" + + 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.networksecurity.v1.SSERealmService", + "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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SSERealmServiceGrpcTransport(SSERealmServiceTransport): + """gRPC backend transport for SSERealmService. + + Service describing handlers for resources + + 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 = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + 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 = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_sac_realms( + self, + ) -> Callable[[sse_realm.ListSACRealmsRequest], sse_realm.ListSACRealmsResponse]: + r"""Return a callable for the list sac realms method over gRPC. + + Lists SACRealms in a given project. + + Returns: + Callable[[~.ListSACRealmsRequest], + ~.ListSACRealmsResponse]: + 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_sac_realms" not in self._stubs: + self._stubs["list_sac_realms"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/ListSACRealms", + request_serializer=sse_realm.ListSACRealmsRequest.serialize, + response_deserializer=sse_realm.ListSACRealmsResponse.deserialize, + ) + return self._stubs["list_sac_realms"] + + @property + def get_sac_realm( + self, + ) -> Callable[[sse_realm.GetSACRealmRequest], sse_realm.SACRealm]: + r"""Return a callable for the get sac realm method over gRPC. + + Returns the specified realm. + + Returns: + Callable[[~.GetSACRealmRequest], + ~.SACRealm]: + 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_sac_realm" not in self._stubs: + self._stubs["get_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/GetSACRealm", + request_serializer=sse_realm.GetSACRealmRequest.serialize, + response_deserializer=sse_realm.SACRealm.deserialize, + ) + return self._stubs["get_sac_realm"] + + @property + def create_sac_realm( + self, + ) -> Callable[[sse_realm.CreateSACRealmRequest], operations_pb2.Operation]: + r"""Return a callable for the create sac realm method over gRPC. + + Creates a new SACRealm in a given project. + + Returns: + Callable[[~.CreateSACRealmRequest], + ~.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_sac_realm" not in self._stubs: + self._stubs["create_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/CreateSACRealm", + request_serializer=sse_realm.CreateSACRealmRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sac_realm"] + + @property + def delete_sac_realm( + self, + ) -> Callable[[sse_realm.DeleteSACRealmRequest], operations_pb2.Operation]: + r"""Return a callable for the delete sac realm method over gRPC. + + Deletes the specified realm. + + Returns: + Callable[[~.DeleteSACRealmRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sac_realm" not in self._stubs: + self._stubs["delete_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/DeleteSACRealm", + request_serializer=sse_realm.DeleteSACRealmRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sac_realm"] + + @property + def list_sac_attachments( + self, + ) -> Callable[ + [sse_realm.ListSACAttachmentsRequest], sse_realm.ListSACAttachmentsResponse + ]: + r"""Return a callable for the list sac attachments method over gRPC. + + Lists SACAttachments in a given project and location. + + Returns: + Callable[[~.ListSACAttachmentsRequest], + ~.ListSACAttachmentsResponse]: + 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_sac_attachments" not in self._stubs: + self._stubs["list_sac_attachments"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/ListSACAttachments", + request_serializer=sse_realm.ListSACAttachmentsRequest.serialize, + response_deserializer=sse_realm.ListSACAttachmentsResponse.deserialize, + ) + return self._stubs["list_sac_attachments"] + + @property + def get_sac_attachment( + self, + ) -> Callable[[sse_realm.GetSACAttachmentRequest], sse_realm.SACAttachment]: + r"""Return a callable for the get sac attachment method over gRPC. + + Returns the specified attachment. + + Returns: + Callable[[~.GetSACAttachmentRequest], + ~.SACAttachment]: + 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_sac_attachment" not in self._stubs: + self._stubs["get_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/GetSACAttachment", + request_serializer=sse_realm.GetSACAttachmentRequest.serialize, + response_deserializer=sse_realm.SACAttachment.deserialize, + ) + return self._stubs["get_sac_attachment"] + + @property + def create_sac_attachment( + self, + ) -> Callable[[sse_realm.CreateSACAttachmentRequest], operations_pb2.Operation]: + r"""Return a callable for the create sac attachment method over gRPC. + + Creates a new SACAttachment in a given project and + location. + + Returns: + Callable[[~.CreateSACAttachmentRequest], + ~.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_sac_attachment" not in self._stubs: + self._stubs["create_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/CreateSACAttachment", + request_serializer=sse_realm.CreateSACAttachmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sac_attachment"] + + @property + def delete_sac_attachment( + self, + ) -> Callable[[sse_realm.DeleteSACAttachmentRequest], operations_pb2.Operation]: + r"""Return a callable for the delete sac attachment method over gRPC. + + Deletes the specified attachment. + + Returns: + Callable[[~.DeleteSACAttachmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sac_attachment" not in self._stubs: + self._stubs["delete_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/DeleteSACAttachment", + request_serializer=sse_realm.DeleteSACAttachmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sac_attachment"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SSERealmServiceGrpcTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc_asyncio.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..18b4eac4de99 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/grpc_asyncio.py @@ -0,0 +1,872 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, 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.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.network_security_v1.types import sse_realm + +from .base import DEFAULT_CLIENT_INFO, SSERealmServiceTransport +from .grpc import SSERealmServiceGrpcTransport + +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)!r}" + + 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.networksecurity.v1.SSERealmService", + "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)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SSERealmServiceGrpcAsyncIOTransport(SSERealmServiceTransport): + """gRPC AsyncIO backend transport for SSERealmService. + + Service describing handlers for resources + + 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 = "networksecurity.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 = "networksecurity.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: 'networksecurity.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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_sac_realms( + self, + ) -> Callable[ + [sse_realm.ListSACRealmsRequest], Awaitable[sse_realm.ListSACRealmsResponse] + ]: + r"""Return a callable for the list sac realms method over gRPC. + + Lists SACRealms in a given project. + + Returns: + Callable[[~.ListSACRealmsRequest], + Awaitable[~.ListSACRealmsResponse]]: + 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_sac_realms" not in self._stubs: + self._stubs["list_sac_realms"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/ListSACRealms", + request_serializer=sse_realm.ListSACRealmsRequest.serialize, + response_deserializer=sse_realm.ListSACRealmsResponse.deserialize, + ) + return self._stubs["list_sac_realms"] + + @property + def get_sac_realm( + self, + ) -> Callable[[sse_realm.GetSACRealmRequest], Awaitable[sse_realm.SACRealm]]: + r"""Return a callable for the get sac realm method over gRPC. + + Returns the specified realm. + + Returns: + Callable[[~.GetSACRealmRequest], + Awaitable[~.SACRealm]]: + 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_sac_realm" not in self._stubs: + self._stubs["get_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/GetSACRealm", + request_serializer=sse_realm.GetSACRealmRequest.serialize, + response_deserializer=sse_realm.SACRealm.deserialize, + ) + return self._stubs["get_sac_realm"] + + @property + def create_sac_realm( + self, + ) -> Callable[ + [sse_realm.CreateSACRealmRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create sac realm method over gRPC. + + Creates a new SACRealm in a given project. + + Returns: + Callable[[~.CreateSACRealmRequest], + 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_sac_realm" not in self._stubs: + self._stubs["create_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/CreateSACRealm", + request_serializer=sse_realm.CreateSACRealmRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sac_realm"] + + @property + def delete_sac_realm( + self, + ) -> Callable[ + [sse_realm.DeleteSACRealmRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete sac realm method over gRPC. + + Deletes the specified realm. + + Returns: + Callable[[~.DeleteSACRealmRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sac_realm" not in self._stubs: + self._stubs["delete_sac_realm"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/DeleteSACRealm", + request_serializer=sse_realm.DeleteSACRealmRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sac_realm"] + + @property + def list_sac_attachments( + self, + ) -> Callable[ + [sse_realm.ListSACAttachmentsRequest], + Awaitable[sse_realm.ListSACAttachmentsResponse], + ]: + r"""Return a callable for the list sac attachments method over gRPC. + + Lists SACAttachments in a given project and location. + + Returns: + Callable[[~.ListSACAttachmentsRequest], + Awaitable[~.ListSACAttachmentsResponse]]: + 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_sac_attachments" not in self._stubs: + self._stubs["list_sac_attachments"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/ListSACAttachments", + request_serializer=sse_realm.ListSACAttachmentsRequest.serialize, + response_deserializer=sse_realm.ListSACAttachmentsResponse.deserialize, + ) + return self._stubs["list_sac_attachments"] + + @property + def get_sac_attachment( + self, + ) -> Callable[ + [sse_realm.GetSACAttachmentRequest], Awaitable[sse_realm.SACAttachment] + ]: + r"""Return a callable for the get sac attachment method over gRPC. + + Returns the specified attachment. + + Returns: + Callable[[~.GetSACAttachmentRequest], + Awaitable[~.SACAttachment]]: + 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_sac_attachment" not in self._stubs: + self._stubs["get_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/GetSACAttachment", + request_serializer=sse_realm.GetSACAttachmentRequest.serialize, + response_deserializer=sse_realm.SACAttachment.deserialize, + ) + return self._stubs["get_sac_attachment"] + + @property + def create_sac_attachment( + self, + ) -> Callable[ + [sse_realm.CreateSACAttachmentRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create sac attachment method over gRPC. + + Creates a new SACAttachment in a given project and + location. + + Returns: + Callable[[~.CreateSACAttachmentRequest], + 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_sac_attachment" not in self._stubs: + self._stubs["create_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/CreateSACAttachment", + request_serializer=sse_realm.CreateSACAttachmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_sac_attachment"] + + @property + def delete_sac_attachment( + self, + ) -> Callable[ + [sse_realm.DeleteSACAttachmentRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete sac attachment method over gRPC. + + Deletes the specified attachment. + + Returns: + Callable[[~.DeleteSACAttachmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_sac_attachment" not in self._stubs: + self._stubs["delete_sac_attachment"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.SSERealmService/DeleteSACAttachment", + request_serializer=sse_realm.DeleteSACAttachmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_sac_attachment"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_sac_realms: self._wrap_method( + self.list_sac_realms, + default_timeout=None, + client_info=client_info, + ), + self.get_sac_realm: self._wrap_method( + self.get_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.create_sac_realm: self._wrap_method( + self.create_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.delete_sac_realm: self._wrap_method( + self.delete_sac_realm, + default_timeout=None, + client_info=client_info, + ), + self.list_sac_attachments: self._wrap_method( + self.list_sac_attachments, + default_timeout=None, + client_info=client_info, + ), + self.get_sac_attachment: self._wrap_method( + self.get_sac_attachment, + default_timeout=None, + client_info=client_info, + ), + self.create_sac_attachment: self._wrap_method( + self.create_sac_attachment, + default_timeout=None, + client_info=client_info, + ), + self.delete_sac_attachment: self._wrap_method( + self.delete_sac_attachment, + 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.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SSERealmServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest.py new file mode 100644 index 000000000000..6774b3e86467 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest.py @@ -0,0 +1,3394 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.network_security_v1.types import sse_realm + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSSERealmServiceRestTransport + +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 SSERealmServiceRestInterceptor: + """Interceptor for SSERealmService. + + 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 SSERealmServiceRestTransport. + + .. code-block:: python + class MyCustomSSERealmServiceInterceptor(SSERealmServiceRestInterceptor): + def pre_create_sac_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sac_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_sac_realm(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sac_realm(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sac_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_sac_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sac_realm(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_sac_realm(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_sac_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sac_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_sac_realm(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sac_realm(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sac_attachments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sac_attachments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sac_realms(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sac_realms(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SSERealmServiceRestTransport(interceptor=MyCustomSSERealmServiceInterceptor()) + client = SSERealmServiceClient(transport=transport) + + + """ + + def pre_create_sac_attachment( + self, + request: sse_realm.CreateSACAttachmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.CreateSACAttachmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_sac_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_create_sac_attachment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_sac_attachment + + DEPRECATED. Please use the `post_create_sac_attachment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_create_sac_attachment` interceptor runs + before the `post_create_sac_attachment_with_metadata` interceptor. + """ + return response + + def post_create_sac_attachment_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_sac_attachment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_create_sac_attachment_with_metadata` + interceptor in new development instead of the `post_create_sac_attachment` interceptor. + When both interceptors are used, this `post_create_sac_attachment_with_metadata` interceptor runs after the + `post_create_sac_attachment` interceptor. The (possibly modified) response returned by + `post_create_sac_attachment` will be passed to + `post_create_sac_attachment_with_metadata`. + """ + return response, metadata + + def pre_create_sac_realm( + self, + request: sse_realm.CreateSACRealmRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.CreateSACRealmRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_sac_realm + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_create_sac_realm( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_sac_realm + + DEPRECATED. Please use the `post_create_sac_realm_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_create_sac_realm` interceptor runs + before the `post_create_sac_realm_with_metadata` interceptor. + """ + return response + + def post_create_sac_realm_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_sac_realm + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_create_sac_realm_with_metadata` + interceptor in new development instead of the `post_create_sac_realm` interceptor. + When both interceptors are used, this `post_create_sac_realm_with_metadata` interceptor runs after the + `post_create_sac_realm` interceptor. The (possibly modified) response returned by + `post_create_sac_realm` will be passed to + `post_create_sac_realm_with_metadata`. + """ + return response, metadata + + def pre_delete_sac_attachment( + self, + request: sse_realm.DeleteSACAttachmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.DeleteSACAttachmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_sac_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_delete_sac_attachment( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_sac_attachment + + DEPRECATED. Please use the `post_delete_sac_attachment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_delete_sac_attachment` interceptor runs + before the `post_delete_sac_attachment_with_metadata` interceptor. + """ + return response + + def post_delete_sac_attachment_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_sac_attachment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_delete_sac_attachment_with_metadata` + interceptor in new development instead of the `post_delete_sac_attachment` interceptor. + When both interceptors are used, this `post_delete_sac_attachment_with_metadata` interceptor runs after the + `post_delete_sac_attachment` interceptor. The (possibly modified) response returned by + `post_delete_sac_attachment` will be passed to + `post_delete_sac_attachment_with_metadata`. + """ + return response, metadata + + def pre_delete_sac_realm( + self, + request: sse_realm.DeleteSACRealmRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.DeleteSACRealmRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_sac_realm + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_delete_sac_realm( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_sac_realm + + DEPRECATED. Please use the `post_delete_sac_realm_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_delete_sac_realm` interceptor runs + before the `post_delete_sac_realm_with_metadata` interceptor. + """ + return response + + def post_delete_sac_realm_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_sac_realm + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_delete_sac_realm_with_metadata` + interceptor in new development instead of the `post_delete_sac_realm` interceptor. + When both interceptors are used, this `post_delete_sac_realm_with_metadata` interceptor runs after the + `post_delete_sac_realm` interceptor. The (possibly modified) response returned by + `post_delete_sac_realm` will be passed to + `post_delete_sac_realm_with_metadata`. + """ + return response, metadata + + def pre_get_sac_attachment( + self, + request: sse_realm.GetSACAttachmentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.GetSACAttachmentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_sac_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_get_sac_attachment( + self, response: sse_realm.SACAttachment + ) -> sse_realm.SACAttachment: + """Post-rpc interceptor for get_sac_attachment + + DEPRECATED. Please use the `post_get_sac_attachment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_get_sac_attachment` interceptor runs + before the `post_get_sac_attachment_with_metadata` interceptor. + """ + return response + + def post_get_sac_attachment_with_metadata( + self, + response: sse_realm.SACAttachment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sse_realm.SACAttachment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_sac_attachment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_get_sac_attachment_with_metadata` + interceptor in new development instead of the `post_get_sac_attachment` interceptor. + When both interceptors are used, this `post_get_sac_attachment_with_metadata` interceptor runs after the + `post_get_sac_attachment` interceptor. The (possibly modified) response returned by + `post_get_sac_attachment` will be passed to + `post_get_sac_attachment_with_metadata`. + """ + return response, metadata + + def pre_get_sac_realm( + self, + request: sse_realm.GetSACRealmRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sse_realm.GetSACRealmRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_sac_realm + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_get_sac_realm(self, response: sse_realm.SACRealm) -> sse_realm.SACRealm: + """Post-rpc interceptor for get_sac_realm + + DEPRECATED. Please use the `post_get_sac_realm_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_get_sac_realm` interceptor runs + before the `post_get_sac_realm_with_metadata` interceptor. + """ + return response + + def post_get_sac_realm_with_metadata( + self, + response: sse_realm.SACRealm, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sse_realm.SACRealm, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_sac_realm + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_get_sac_realm_with_metadata` + interceptor in new development instead of the `post_get_sac_realm` interceptor. + When both interceptors are used, this `post_get_sac_realm_with_metadata` interceptor runs after the + `post_get_sac_realm` interceptor. The (possibly modified) response returned by + `post_get_sac_realm` will be passed to + `post_get_sac_realm_with_metadata`. + """ + return response, metadata + + def pre_list_sac_attachments( + self, + request: sse_realm.ListSACAttachmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.ListSACAttachmentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_sac_attachments + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_list_sac_attachments( + self, response: sse_realm.ListSACAttachmentsResponse + ) -> sse_realm.ListSACAttachmentsResponse: + """Post-rpc interceptor for list_sac_attachments + + DEPRECATED. Please use the `post_list_sac_attachments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_list_sac_attachments` interceptor runs + before the `post_list_sac_attachments_with_metadata` interceptor. + """ + return response + + def post_list_sac_attachments_with_metadata( + self, + response: sse_realm.ListSACAttachmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.ListSACAttachmentsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_sac_attachments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_list_sac_attachments_with_metadata` + interceptor in new development instead of the `post_list_sac_attachments` interceptor. + When both interceptors are used, this `post_list_sac_attachments_with_metadata` interceptor runs after the + `post_list_sac_attachments` interceptor. The (possibly modified) response returned by + `post_list_sac_attachments` will be passed to + `post_list_sac_attachments_with_metadata`. + """ + return response, metadata + + def pre_list_sac_realms( + self, + request: sse_realm.ListSACRealmsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sse_realm.ListSACRealmsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_sac_realms + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_list_sac_realms( + self, response: sse_realm.ListSACRealmsResponse + ) -> sse_realm.ListSACRealmsResponse: + """Post-rpc interceptor for list_sac_realms + + DEPRECATED. Please use the `post_list_sac_realms_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. This `post_list_sac_realms` interceptor runs + before the `post_list_sac_realms_with_metadata` interceptor. + """ + return response + + def post_list_sac_realms_with_metadata( + self, + response: sse_realm.ListSACRealmsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sse_realm.ListSACRealmsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_sac_realms + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SSERealmService server but before it is returned to user code. + + We recommend only using this `post_list_sac_realms_with_metadata` + interceptor in new development instead of the `post_list_sac_realms` interceptor. + When both interceptors are used, this `post_list_sac_realms_with_metadata` interceptor runs after the + `post_list_sac_realms` interceptor. The (possibly modified) response returned by + `post_list_sac_realms` will be passed to + `post_list_sac_realms_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 SSERealmService 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 SSERealmService 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 SSERealmService 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 SSERealmService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SSERealmService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the SSERealmService 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 SSERealmService 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 SSERealmService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SSERealmService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the SSERealmService 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 SSERealmService 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 SSERealmService 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 SSERealmService 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 SSERealmService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SSERealmServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SSERealmServiceRestInterceptor + + +class SSERealmServiceRestTransport(_BaseSSERealmServiceRestTransport): + """REST backend synchronous transport for SSERealmService. + + Service describing handlers for resources + + 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 = "networksecurity.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[SSERealmServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.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. + interceptor (Optional[SSERealmServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 SSERealmServiceRestInterceptor() + 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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateSACAttachment( + _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment, + SSERealmServiceRestStub, + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.CreateSACAttachment") + + @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: sse_realm.CreateSACAttachmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create sac attachment method over HTTP. + + Args: + request (~.sse_realm.CreateSACAttachmentRequest): + The request object. Request for ``CreateSACAttachment`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment._get_http_options() + + request, metadata = self._interceptor.pre_create_sac_attachment( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment._get_transcoded_request( + http_options, request + ) + + body = _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment._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.networksecurity_v1.SSERealmServiceClient.CreateSACAttachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "CreateSACAttachment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._CreateSACAttachment._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_sac_attachment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_sac_attachment_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.networksecurity_v1.SSERealmServiceClient.create_sac_attachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "CreateSACAttachment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSACRealm( + _BaseSSERealmServiceRestTransport._BaseCreateSACRealm, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.CreateSACRealm") + + @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: sse_realm.CreateSACRealmRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create sac realm method over HTTP. + + Args: + request (~.sse_realm.CreateSACRealmRequest): + The request object. Request for ``CreateSACRealm`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseCreateSACRealm._get_http_options() + + request, metadata = self._interceptor.pre_create_sac_realm( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseCreateSACRealm._get_transcoded_request( + http_options, request + ) + + body = _BaseSSERealmServiceRestTransport._BaseCreateSACRealm._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseCreateSACRealm._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.networksecurity_v1.SSERealmServiceClient.CreateSACRealm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "CreateSACRealm", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._CreateSACRealm._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_sac_realm(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_sac_realm_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.networksecurity_v1.SSERealmServiceClient.create_sac_realm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "CreateSACRealm", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSACAttachment( + _BaseSSERealmServiceRestTransport._BaseDeleteSACAttachment, + SSERealmServiceRestStub, + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.DeleteSACAttachment") + + @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: sse_realm.DeleteSACAttachmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete sac attachment method over HTTP. + + Args: + request (~.sse_realm.DeleteSACAttachmentRequest): + The request object. Request for ``DeleteSACAttachment`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseDeleteSACAttachment._get_http_options() + + request, metadata = self._interceptor.pre_delete_sac_attachment( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseDeleteSACAttachment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseDeleteSACAttachment._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.networksecurity_v1.SSERealmServiceClient.DeleteSACAttachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "DeleteSACAttachment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._DeleteSACAttachment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_sac_attachment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_sac_attachment_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.networksecurity_v1.SSERealmServiceClient.delete_sac_attachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "DeleteSACAttachment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSACRealm( + _BaseSSERealmServiceRestTransport._BaseDeleteSACRealm, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.DeleteSACRealm") + + @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: sse_realm.DeleteSACRealmRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete sac realm method over HTTP. + + Args: + request (~.sse_realm.DeleteSACRealmRequest): + The request object. Request for ``DeleteSACRealm`` 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: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseDeleteSACRealm._get_http_options() + + request, metadata = self._interceptor.pre_delete_sac_realm( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseDeleteSACRealm._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseDeleteSACRealm._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.networksecurity_v1.SSERealmServiceClient.DeleteSACRealm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "DeleteSACRealm", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._DeleteSACRealm._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_sac_realm(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_sac_realm_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.networksecurity_v1.SSERealmServiceClient.delete_sac_realm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "DeleteSACRealm", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSACAttachment( + _BaseSSERealmServiceRestTransport._BaseGetSACAttachment, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.GetSACAttachment") + + @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: sse_realm.GetSACAttachmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sse_realm.SACAttachment: + r"""Call the get sac attachment method over HTTP. + + Args: + request (~.sse_realm.GetSACAttachmentRequest): + The request object. Request for ``GetSACAttachment`` 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: + ~.sse_realm.SACAttachment: + Represents a Secure Access Connect + (SAC) attachment resource. + A Secure Access Connect attachment + enables NCC Gateway to process traffic + with an SSE product. + + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseGetSACAttachment._get_http_options() + + request, metadata = self._interceptor.pre_get_sac_attachment( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseGetSACAttachment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseGetSACAttachment._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.networksecurity_v1.SSERealmServiceClient.GetSACAttachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetSACAttachment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._GetSACAttachment._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 = sse_realm.SACAttachment() + pb_resp = sse_realm.SACAttachment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_sac_attachment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_sac_attachment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sse_realm.SACAttachment.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.networksecurity_v1.SSERealmServiceClient.get_sac_attachment", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetSACAttachment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSACRealm( + _BaseSSERealmServiceRestTransport._BaseGetSACRealm, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.GetSACRealm") + + @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: sse_realm.GetSACRealmRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sse_realm.SACRealm: + r"""Call the get sac realm method over HTTP. + + Args: + request (~.sse_realm.GetSACRealmRequest): + The request object. Request for ``GetSACRealm`` 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: + ~.sse_realm.SACRealm: + Represents a Secure Access Connect + (SAC) realm resource. + A Secure Access Connect realm + establishes a connection between your + Google Cloud project and an SSE service. + + """ + + http_options = ( + _BaseSSERealmServiceRestTransport._BaseGetSACRealm._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_sac_realm(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseGetSACRealm._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseGetSACRealm._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.networksecurity_v1.SSERealmServiceClient.GetSACRealm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetSACRealm", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._GetSACRealm._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 = sse_realm.SACRealm() + pb_resp = sse_realm.SACRealm.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_sac_realm(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_sac_realm_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sse_realm.SACRealm.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.networksecurity_v1.SSERealmServiceClient.get_sac_realm", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetSACRealm", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSACAttachments( + _BaseSSERealmServiceRestTransport._BaseListSACAttachments, + SSERealmServiceRestStub, + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.ListSACAttachments") + + @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: sse_realm.ListSACAttachmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sse_realm.ListSACAttachmentsResponse: + r"""Call the list sac attachments method over HTTP. + + Args: + request (~.sse_realm.ListSACAttachmentsRequest): + The request object. Request for ``ListSACAttachments`` 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: + ~.sse_realm.ListSACAttachmentsResponse: + Response for ``ListSACAttachments`` method. + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseListSACAttachments._get_http_options() + + request, metadata = self._interceptor.pre_list_sac_attachments( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseListSACAttachments._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseListSACAttachments._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.networksecurity_v1.SSERealmServiceClient.ListSACAttachments", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListSACAttachments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._ListSACAttachments._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 = sse_realm.ListSACAttachmentsResponse() + pb_resp = sse_realm.ListSACAttachmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sac_attachments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sac_attachments_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sse_realm.ListSACAttachmentsResponse.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.networksecurity_v1.SSERealmServiceClient.list_sac_attachments", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListSACAttachments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSACRealms( + _BaseSSERealmServiceRestTransport._BaseListSACRealms, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.ListSACRealms") + + @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: sse_realm.ListSACRealmsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sse_realm.ListSACRealmsResponse: + r"""Call the list sac realms method over HTTP. + + Args: + request (~.sse_realm.ListSACRealmsRequest): + The request object. Request for ``ListSACRealms`` 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: + ~.sse_realm.ListSACRealmsResponse: + Response for ``ListSACRealms`` method. + """ + + http_options = ( + _BaseSSERealmServiceRestTransport._BaseListSACRealms._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_sac_realms(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseListSACRealms._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseListSACRealms._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.networksecurity_v1.SSERealmServiceClient.ListSACRealms", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListSACRealms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._ListSACRealms._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 = sse_realm.ListSACRealmsResponse() + pb_resp = sse_realm.ListSACRealmsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sac_realms(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sac_realms_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sse_realm.ListSACRealmsResponse.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.networksecurity_v1.SSERealmServiceClient.list_sac_realms", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListSACRealms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_sac_attachment( + self, + ) -> Callable[[sse_realm.CreateSACAttachmentRequest], 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._CreateSACAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_sac_realm( + self, + ) -> Callable[[sse_realm.CreateSACRealmRequest], 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._CreateSACRealm(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sac_attachment( + self, + ) -> Callable[[sse_realm.DeleteSACAttachmentRequest], 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._DeleteSACAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sac_realm( + self, + ) -> Callable[[sse_realm.DeleteSACRealmRequest], 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._DeleteSACRealm(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sac_attachment( + self, + ) -> Callable[[sse_realm.GetSACAttachmentRequest], sse_realm.SACAttachment]: + # 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._GetSACAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sac_realm( + self, + ) -> Callable[[sse_realm.GetSACRealmRequest], sse_realm.SACRealm]: + # 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._GetSACRealm(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sac_attachments( + self, + ) -> Callable[ + [sse_realm.ListSACAttachmentsRequest], sse_realm.ListSACAttachmentsResponse + ]: + # 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._ListSACAttachments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sac_realms( + self, + ) -> Callable[[sse_realm.ListSACRealmsRequest], sse_realm.ListSACRealmsResponse]: + # 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._ListSACRealms(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( + _BaseSSERealmServiceRestTransport._BaseGetLocation, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.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 = ( + _BaseSSERealmServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "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( + _BaseSSERealmServiceRestTransport._BaseListLocations, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.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 = ( + _BaseSSERealmServiceRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSSERealmServiceRestTransport._BaseGetIamPolicy, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.GetIamPolicy") + + @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: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy 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: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseSSERealmServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseGetIamPolicy._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.networksecurity_v1.SSERealmServiceClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._GetIamPolicy._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 = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(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.networksecurity_v1.SSERealmServiceAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSSERealmServiceRestTransport._BaseSetIamPolicy, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.SetIamPolicy") + + @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: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy 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: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseSSERealmServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseSSERealmServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseSetIamPolicy._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.networksecurity_v1.SSERealmServiceClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._SetIamPolicy._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) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(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.networksecurity_v1.SSERealmServiceAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSSERealmServiceRestTransport._BaseTestIamPermissions, + SSERealmServiceRestStub, + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.TestIamPermissions") + + @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: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions 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: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSSERealmServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseTestIamPermissions._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.networksecurity_v1.SSERealmServiceClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._TestIamPermissions._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) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(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.networksecurity_v1.SSERealmServiceAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "TestIamPermissions", + "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( + _BaseSSERealmServiceRestTransport._BaseCancelOperation, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseSSERealmServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseSSERealmServiceRestTransport._BaseDeleteOperation, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSSERealmServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.SSERealmServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSSERealmServiceRestTransport._BaseGetOperation, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.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 = ( + _BaseSSERealmServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "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( + _BaseSSERealmServiceRestTransport._BaseListOperations, SSERealmServiceRestStub + ): + def __hash__(self): + return hash("SSERealmServiceRestTransport.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 = _BaseSSERealmServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseSSERealmServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SSERealmServiceRestTransport._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.networksecurity_v1.SSERealmServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.networksecurity.v1.SSERealmService", + "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__ = ("SSERealmServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest_base.py new file mode 100644 index 000000000000..05bec2084188 --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/sse_realm_service/transports/rest_base.py @@ -0,0 +1,826 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.network_security_v1.types import sse_realm + +from .base import DEFAULT_CLIENT_INFO, SSERealmServiceTransport + + +class _BaseSSERealmServiceRestTransport(SSERealmServiceTransport): + """Base REST backend transport for SSERealmService. + + 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 = "networksecurity.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: 'networksecurity.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 _BaseCreateSACAttachment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sacAttachmentId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/sacAttachments", + "body": "sac_attachment", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.CreateSACAttachmentRequest.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( + _BaseSSERealmServiceRestTransport._BaseCreateSACAttachment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSACRealm: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "sacRealmId": "", + } + + @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": "/v1/{parent=projects/*/locations/*}/sacRealms", + "body": "sac_realm", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.CreateSACRealmRequest.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( + _BaseSSERealmServiceRestTransport._BaseCreateSACRealm._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSACAttachment: + 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": "/v1/{name=projects/*/locations/*/sacAttachments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.DeleteSACAttachmentRequest.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( + _BaseSSERealmServiceRestTransport._BaseDeleteSACAttachment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSACRealm: + 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": "/v1/{name=projects/*/locations/*/sacRealms/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.DeleteSACRealmRequest.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( + _BaseSSERealmServiceRestTransport._BaseDeleteSACRealm._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSACAttachment: + 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": "/v1/{name=projects/*/locations/*/sacAttachments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.GetSACAttachmentRequest.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( + _BaseSSERealmServiceRestTransport._BaseGetSACAttachment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSACRealm: + 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": "/v1/{name=projects/*/locations/*/sacRealms/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.GetSACRealmRequest.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( + _BaseSSERealmServiceRestTransport._BaseGetSACRealm._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSACAttachments: + 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": "/v1/{parent=projects/*/locations/*}/sacAttachments", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.ListSACAttachmentsRequest.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( + _BaseSSERealmServiceRestTransport._BaseListSACAttachments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSACRealms: + 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": "/v1/{parent=projects/*/locations/*}/sacRealms", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sse_realm.ListSACRealmsRequest.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( + _BaseSSERealmServiceRestTransport._BaseListSACRealms._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": "/v1/{name=projects/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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": "/v1/{name=projects/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*}/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 _BaseGetIamPolicy: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:getIamPolicy", + }, + ] + 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 _BaseSetIamPolicy: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + 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": "/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authzPolicies/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/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__ = ("_BaseSSERealmServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py index 312438f4f335..6bcd6ffe236a 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py @@ -218,6 +218,20 @@ ServerTlsPolicy, UpdateServerTlsPolicyRequest, ) +from .sse_realm import ( + CreateSACAttachmentRequest, + CreateSACRealmRequest, + DeleteSACAttachmentRequest, + DeleteSACRealmRequest, + GetSACAttachmentRequest, + GetSACRealmRequest, + ListSACAttachmentsRequest, + ListSACAttachmentsResponse, + ListSACRealmsRequest, + ListSACRealmsResponse, + SACAttachment, + SACRealm, +) from .tls import ( CertificateProvider, CertificateProviderInstance, @@ -411,6 +425,18 @@ "ListServerTlsPoliciesResponse", "ServerTlsPolicy", "UpdateServerTlsPolicyRequest", + "CreateSACAttachmentRequest", + "CreateSACRealmRequest", + "DeleteSACAttachmentRequest", + "DeleteSACRealmRequest", + "GetSACAttachmentRequest", + "GetSACRealmRequest", + "ListSACAttachmentsRequest", + "ListSACAttachmentsResponse", + "ListSACRealmsRequest", + "ListSACRealmsResponse", + "SACAttachment", + "SACRealm", "CertificateProvider", "CertificateProviderInstance", "GrpcEndpoint", diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/authz_policy.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/authz_policy.py index 313aac499d57..cebbe5e5d576 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/authz_policy.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/authz_policy.py @@ -70,6 +70,15 @@ class AuthzPolicy(proto.Message): in the policy. At least one HTTP Rule is required for Allow or Deny Action. Limited to 5 rules. + network_rules (MutableSequence[google.cloud.network_security_v1.types.AuthzPolicy.AuthzRule]): + Optional. A list of authorization network + rules to match against the incoming request. A + policy match occurs when at least one network + rule matches the request. + At least one network rule is required for Allow + or Deny Action if no HTTP rules are provided. + Network rules are mutually exclusive with HTTP + rules. Limited to 5 rules. action (google.cloud.network_security_v1.types.AuthzPolicy.AuthzAction): Required. Can be one of ``ALLOW``, ``DENY``, ``CUSTOM``. @@ -195,13 +204,17 @@ class Target(proto.Message): load_balancing_scheme (google.cloud.network_security_v1.types.AuthzPolicy.LoadBalancingScheme): Optional. All gateways and forwarding rules referenced by this policy and extensions must share the same load - balancing scheme. Supported values: ``INTERNAL_MANAGED`` and - ``EXTERNAL_MANAGED``. For more information, refer to - `Backend services + balancing scheme. Required only when targeting forwarding + rules. If targeting Secure Web Proxy, this field must be + ``INTERNAL_MANAGED`` or not specified. Must not be specified + when targeting Agent Gateway. Supported values: + ``INTERNAL_MANAGED`` and ``EXTERNAL_MANAGED``. For more + information, refer to `Backend services overview `__. resources (MutableSequence[str]): Required. A list of references to the - Forwarding Rules on which this policy will be + Forwarding Rules, Secure Web Proxy Gateways, or + Agent Gateways on which this policy will be applied. """ @@ -624,6 +637,14 @@ class RequestOperation(proto.Message): body cannot be successfully parsed, the request will be denied. This field can be set only for AuthzPolicies targeting AgentGateway resources. + snis (MutableSequence[google.cloud.network_security_v1.types.AuthzPolicy.AuthzRule.StringMatch]): + Optional. A list of SNIs to match against. + The match can be one of exact, prefix, suffix, + or contains (substring match). If there is no + SNI (i.e. plaintext HTTP traffic), the request + will be denied. Matches are always case + sensitive unless the ignoreCase is set. Limited + to 10 SNIs per Authorization Policy. """ class BaseProtocolMethodsOption(proto.Enum): @@ -769,6 +790,13 @@ class MCP(proto.Message): number=5, message="AuthzPolicy.AuthzRule.To.RequestOperation.MCP", ) + snis: MutableSequence["AuthzPolicy.AuthzRule.StringMatch"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=7, + message="AuthzPolicy.AuthzRule.StringMatch", + ) + ) operations: MutableSequence["AuthzPolicy.AuthzRule.To.RequestOperation"] = ( proto.RepeatedField( @@ -892,6 +920,11 @@ class AuthzExtension(proto.Message): number=7, message=AuthzRule, ) + network_rules: MutableSequence[AuthzRule] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=AuthzRule, + ) action: AuthzAction = proto.Field( proto.ENUM, number=8, diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/firewall_activation.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/firewall_activation.py index 753f68b3b2c1..345e6f9e811a 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/firewall_activation.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/firewall_activation.py @@ -66,9 +66,9 @@ class FirewallEndpoint(proto.Message): progress, recommended per https://google.aip.dev/128. associated_networks (MutableSequence[str]): - Output only. List of networks that are - associated with this endpoint in the local zone. - This is a projection of the + Output only. Deprecated: List of networks + that are associated with this endpoint in the + local zone. This is a projection of the FirewallEndpointAssociations pointing at this endpoint. A network will only appear in this list after traffic routing is fully configured. diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/sse_realm.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/sse_realm.py new file mode 100644 index 000000000000..ab5aedeeab4d --- /dev/null +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/sse_realm.py @@ -0,0 +1,636 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.networksecurity.v1", + manifest={ + "SACRealm", + "ListSACRealmsRequest", + "ListSACRealmsResponse", + "GetSACRealmRequest", + "CreateSACRealmRequest", + "DeleteSACRealmRequest", + "SACAttachment", + "ListSACAttachmentsRequest", + "ListSACAttachmentsResponse", + "GetSACAttachmentRequest", + "CreateSACAttachmentRequest", + "DeleteSACAttachmentRequest", + }, +) + + +class SACRealm(proto.Message): + r"""Represents a Secure Access Connect (SAC) realm resource. + + A Secure Access Connect realm establishes a connection between + your Google Cloud project and an SSE service. + + Attributes: + name (str): + Identifier. Resource name, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the realm was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the realm was + last updated. + labels (MutableMapping[str, str]): + Optional. Optional list of labels applied to + the resource. + security_service (google.cloud.network_security_v1.types.SACRealm.SecurityService): + Immutable. SSE service provider associated + with the realm. + pairing_key (google.cloud.network_security_v1.types.SACRealm.PairingKey): + Output only. Key to be shared with SSE + service provider during pairing. + state (google.cloud.network_security_v1.types.SACRealm.State): + Output only. State of the realm. + """ + + class SecurityService(proto.Enum): + r"""SSE service provider + + Values: + SECURITY_SERVICE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + PALO_ALTO_PRISMA_ACCESS (1): + `Palo Alto Networks Prisma + Access `__. + """ + + SECURITY_SERVICE_UNSPECIFIED = 0 + PALO_ALTO_PRISMA_ACCESS = 1 + + class State(proto.Enum): + r"""State of the realm. + + Values: + STATE_UNSPECIFIED (0): + No state specified. This should not be used. + PENDING_PARTNER_ATTACHMENT (7): + Has never been attached to a partner. + Used only for Prisma Access. + PARTNER_ATTACHED (1): + Currently attached to a partner. + PARTNER_DETACHED (2): + Was once attached to a partner but has been + detached. + KEY_EXPIRED (3): + Is not attached to a partner and has an + expired pairing key. Used only for Prisma + Access. + """ + + STATE_UNSPECIFIED = 0 + PENDING_PARTNER_ATTACHMENT = 7 + PARTNER_ATTACHED = 1 + PARTNER_DETACHED = 2 + KEY_EXPIRED = 3 + + class PairingKey(proto.Message): + r"""Key to be shared with SSE service provider to establish + global handshake. + + Attributes: + key (str): + Output only. Key value. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp in UTC of when this + resource is considered expired. It expires 7 + days after creation. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + security_service: SecurityService = proto.Field( + proto.ENUM, + number=5, + enum=SecurityService, + ) + pairing_key: PairingKey = proto.Field( + proto.MESSAGE, + number=6, + message=PairingKey, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + + +class ListSACRealmsRequest(proto.Message): + r"""Request for ``ListSACRealms`` method. + + Attributes: + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/global``. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. An expression that filters the list + of results. + order_by (str): + Optional. Sort the results by a certain + order. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSACRealmsResponse(proto.Message): + r"""Response for ``ListSACRealms`` method. + + Attributes: + sac_realms (MutableSequence[google.cloud.network_security_v1.types.SACRealm]): + The list of SACRealms. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + sac_realms: MutableSequence["SACRealm"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SACRealm", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetSACRealmRequest(proto.Message): + r"""Request for ``GetSACRealm`` method. + + Attributes: + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSACRealmRequest(proto.Message): + r"""Request for ``CreateSACRealm`` method. + + Attributes: + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/global``. + sac_realm_id (str): + Required. ID of the created realm. The ID must be 1-63 + characters long, and comply with RFC1035. Specifically, it + must be 1-63 characters long and match the regular + expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, or + digit, except the last character, which cannot be a dash. + sac_realm (google.cloud.network_security_v1.types.SACRealm): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sac_realm_id: str = proto.Field( + proto.STRING, + number=2, + ) + sac_realm: "SACRealm" = proto.Field( + proto.MESSAGE, + number=3, + message="SACRealm", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteSACRealmRequest(proto.Message): + r"""Request for ``DeleteSACRealm`` method. + + Attributes: + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/global/sacRealms/{sacRealm}``. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SACAttachment(proto.Message): + r"""Represents a Secure Access Connect (SAC) attachment resource. + + A Secure Access Connect attachment enables NCC Gateway to + process traffic with an SSE product. + + Attributes: + name (str): + Identifier. Resource name, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the attachment + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the attachment + was last updated. + labels (MutableMapping[str, str]): + Optional. Optional list of labels applied to + the resource. + sac_realm (str): + Required. SAC Realm which owns the attachment. This can be + input as an ID or a full resource name. The output always + has the form + ``projects/{project_number}/locations/{location}/sacRealms/{sac_realm}``. + ncc_gateway (str): + Required. NCC Gateway associated with the attachment. This + can be input as an ID or a full resource name. The output + always has the form + ``projects/{project_number}/locations/{location}/spokes/{ncc_gateway}``. + state (google.cloud.network_security_v1.types.SACAttachment.State): + Output only. State of the attachment. + """ + + class State(proto.Enum): + r"""State of the attachment. + + Values: + STATE_UNSPECIFIED (0): + No state specified. This should not be used. + PENDING_PARTNER_ATTACHMENT (1): + Has never been attached to a partner. + PARTNER_ATTACHED (2): + Currently attached to a partner. + PARTNER_DETACHED (3): + Was once attached to a partner but has been + detached. + """ + + STATE_UNSPECIFIED = 0 + PENDING_PARTNER_ATTACHMENT = 1 + PARTNER_ATTACHED = 2 + PARTNER_DETACHED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + sac_realm: str = proto.Field( + proto.STRING, + number=5, + ) + ncc_gateway: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + + +class ListSACAttachmentsRequest(proto.Message): + r"""Request for ``ListSACAttachments`` method. + + Attributes: + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. An expression that filters the list + of results. + order_by (str): + Optional. Sort the results by a certain + order. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSACAttachmentsResponse(proto.Message): + r"""Response for ``ListSACAttachments`` method. + + Attributes: + sac_attachments (MutableSequence[google.cloud.network_security_v1.types.SACAttachment]): + The list of SACAttachments. + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + sac_attachments: MutableSequence["SACAttachment"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SACAttachment", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetSACAttachmentRequest(proto.Message): + r"""Request for ``GetSACAttachment`` method. + + Attributes: + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSACAttachmentRequest(proto.Message): + r"""Request for ``CreateSACAttachment`` method. + + Attributes: + parent (str): + Required. The parent, in the form + ``projects/{project}/locations/{location}``. + sac_attachment_id (str): + Required. ID of the created attachment. The ID must be 1-63 + characters long, and comply with RFC1035. Specifically, it + must be 1-63 characters long and match the regular + expression ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, or + digit, except the last character, which cannot be a dash. + sac_attachment (google.cloud.network_security_v1.types.SACAttachment): + Required. The resource being created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sac_attachment_id: str = proto.Field( + proto.STRING, + number=2, + ) + sac_attachment: "SACAttachment" = proto.Field( + proto.MESSAGE, + number=3, + message="SACAttachment", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeleteSACAttachmentRequest(proto.Message): + r"""Request for ``DeleteSACAttachment`` method. + + Attributes: + name (str): + Required. Name of the resource, in the form + ``projects/{project}/locations/{location}/sacAttachments/{sac_attachment}``. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_async.py new file mode 100644 index 000000000000..942950c7b64d --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_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 network_security_v1 + + +async def sample_create_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = await client.create_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_sync.py new file mode 100644 index 000000000000..3782b84e84b7 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_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 network_security_v1 + + +def sample_create_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + # Make the request + operation = client.create_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_async.py new file mode 100644 index 000000000000..9f1e11e2d552 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_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 network_security_v1 + + +async def sample_delete_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_sync.py new file mode 100644 index 000000000000..36c1b309238b --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_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 network_security_v1 + + +def sample_delete_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_async.py new file mode 100644 index 000000000000..fb8a70dfaafa --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_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 network_security_v1 + + +async def sample_get_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = await client.get_project_firewall_endpoint(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_sync.py new file mode 100644 index 000000000000..cf60f08e9a45 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_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 network_security_v1 + + +def sample_get_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.GetFirewallEndpointRequest( + name="name_value", + ) + + # Make the request + response = client.get_project_firewall_endpoint(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_async.py new file mode 100644 index 000000000000..7a4fc67e0217 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProjectFirewallEndpoints +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_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 network_security_v1 + + +async def sample_list_project_firewall_endpoints(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListFirewallEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_project_firewall_endpoints(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_sync.py new file mode 100644 index 000000000000..0771f27d387e --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListProjectFirewallEndpoints +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_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 network_security_v1 + + +def sample_list_project_firewall_endpoints(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.ListFirewallEndpointsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_project_firewall_endpoints(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_async.py new file mode 100644 index 000000000000..cde87bde78ba --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_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 network_security_v1 + + +async def sample_update_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateFirewallEndpointRequest() + + # Make the request + operation = await client.update_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_sync.py new file mode 100644 index 000000000000..c5ea0cfb5b90 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProjectFirewallEndpoint +# 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-network-security + + +# [START networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_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 network_security_v1 + + +def sample_update_project_firewall_endpoint(): + # Create a client + client = network_security_v1.FirewallActivationClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateFirewallEndpointRequest() + + # Make the request + operation = client.update_project_firewall_endpoint(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_async.py new file mode 100644 index 000000000000..60135f1ca7b1 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_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 network_security_v1 + + +async def sample_create_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + + # Make the request + operation = await client.create_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_async.py new file mode 100644 index 000000000000..a0bf59d7c297 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_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 network_security_v1 + + +async def sample_create_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + + # Make the request + operation = await client.create_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_sync.py new file mode 100644 index 000000000000..0b7c36af495a --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_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 network_security_v1 + + +def sample_create_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + + # Make the request + operation = client.create_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_sync.py new file mode 100644 index 000000000000..9c53bc2dfcc0 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_create_security_profile_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_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 network_security_v1 + + +def sample_create_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + + # Make the request + operation = client.create_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_async.py new file mode 100644 index 000000000000..880e7d6d5fac --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_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 network_security_v1 + + +async def sample_delete_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_async.py new file mode 100644 index 000000000000..dd72ba95c4aa --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_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 network_security_v1 + + +async def sample_delete_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_sync.py new file mode 100644 index 000000000000..061a118ce8a6 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_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 network_security_v1 + + +def sample_delete_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_sync.py new file mode 100644 index 000000000000..72b217e913ab --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_delete_security_profile_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_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 network_security_v1 + + +def sample_delete_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSecurityProfileRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_async.py new file mode 100644 index 000000000000..6c5af8abf895 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_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 network_security_v1 + + +async def sample_get_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_profile(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_async.py new file mode 100644 index 000000000000..412bf9cb3aad --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_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 network_security_v1 + + +async def sample_get_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_security_profile_group(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_sync.py new file mode 100644 index 000000000000..89ef0c8bd120 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_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 network_security_v1 + + +def sample_get_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_profile_group(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_sync.py new file mode 100644 index 000000000000..44b7e61ccc18 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_get_security_profile_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_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 network_security_v1 + + +def sample_get_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSecurityProfileRequest( + name="name_value", + ) + + # Make the request + response = client.get_security_profile(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_async.py new file mode 100644 index 000000000000..08c0bea02293 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSecurityProfileGroups +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_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 network_security_v1 + + +async def sample_list_security_profile_groups(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfileGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profile_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_sync.py new file mode 100644 index 000000000000..943098488e89 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSecurityProfileGroups +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_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 network_security_v1 + + +def sample_list_security_profile_groups(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfileGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profile_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_async.py new file mode 100644 index 000000000000..e7c4c0e8a892 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSecurityProfiles +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_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 network_security_v1 + + +async def sample_list_security_profiles(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfilesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profiles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_sync.py new file mode 100644 index 000000000000..3793a2fd9c82 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_list_security_profiles_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSecurityProfiles +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_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 network_security_v1 + + +def sample_list_security_profiles(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSecurityProfilesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_security_profiles(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_async.py new file mode 100644 index 000000000000..220d92f9f7fd --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_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 network_security_v1 + + +async def sample_update_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileRequest() + + # Make the request + operation = await client.update_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_async.py new file mode 100644 index 000000000000..ca4115ea86d8 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_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 network_security_v1 + + +async def sample_update_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileGroupRequest() + + # Make the request + operation = await client.update_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_sync.py new file mode 100644 index 000000000000..94bb53c36260 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSecurityProfileGroup +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_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 network_security_v1 + + +def sample_update_security_profile_group(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileGroupRequest() + + # Make the request + operation = client.update_security_profile_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_sync.py new file mode 100644 index 000000000000..b3b735f83be7 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_security_profile_group_service_update_security_profile_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSecurityProfile +# 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-network-security + + +# [START networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_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 network_security_v1 + + +def sample_update_security_profile(): + # Create a client + client = network_security_v1.SecurityProfileGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.UpdateSecurityProfileRequest() + + # Make the request + operation = client.update_security_profile(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_async.py new file mode 100644 index 000000000000..ddd5f4507584 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_CreateSACAttachment_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 network_security_v1 + + +async def sample_create_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + sac_attachment = network_security_v1.SACAttachment() + sac_attachment.sac_realm = "sac_realm_value" + sac_attachment.ncc_gateway = "ncc_gateway_value" + + request = network_security_v1.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + sac_attachment=sac_attachment, + ) + + # Make the request + operation = await client.create_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_CreateSACAttachment_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_sync.py new file mode 100644 index 000000000000..18d097271db8 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_attachment_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_CreateSACAttachment_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 network_security_v1 + + +def sample_create_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + sac_attachment = network_security_v1.SACAttachment() + sac_attachment.sac_realm = "sac_realm_value" + sac_attachment.ncc_gateway = "ncc_gateway_value" + + request = network_security_v1.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + sac_attachment=sac_attachment, + ) + + # Make the request + operation = client.create_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_CreateSACAttachment_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_async.py new file mode 100644 index 000000000000..c237e5137ea8 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_CreateSACRealm_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 network_security_v1 + + +async def sample_create_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + + # Make the request + operation = await client.create_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_CreateSACRealm_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_sync.py new file mode 100644 index 000000000000..44be01835770 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_create_sac_realm_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_CreateSACRealm_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 network_security_v1 + + +def sample_create_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + + # Make the request + operation = client.create_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_CreateSACRealm_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_async.py new file mode 100644 index 000000000000..cc546ccaab05 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_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 network_security_v1 + + +async def sample_delete_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACAttachmentRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_sync.py new file mode 100644 index 000000000000..1208623c55eb --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_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 network_security_v1 + + +def sample_delete_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACAttachmentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sac_attachment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_async.py new file mode 100644 index 000000000000..ca9c8c2eee71 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_DeleteSACRealm_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 network_security_v1 + + +async def sample_delete_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACRealmRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_DeleteSACRealm_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_sync.py new file mode 100644 index 000000000000..3e24c2fd2245 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_delete_sac_realm_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_DeleteSACRealm_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 network_security_v1 + + +def sample_delete_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteSACRealmRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_sac_realm(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_DeleteSACRealm_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_async.py new file mode 100644 index 000000000000..d87d07336793 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_GetSACAttachment_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 network_security_v1 + + +async def sample_get_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sac_attachment(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_GetSACAttachment_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_sync.py new file mode 100644 index 000000000000..d718d84372d8 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_attachment_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSACAttachment +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_GetSACAttachment_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 network_security_v1 + + +def sample_get_sac_attachment(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_sac_attachment(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_GetSACAttachment_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_async.py new file mode 100644 index 000000000000..83fa4c41fb05 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_GetSACRealm_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 network_security_v1 + + +async def sample_get_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACRealmRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sac_realm(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_GetSACRealm_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_sync.py new file mode 100644 index 000000000000..0b82e76e66eb --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_get_sac_realm_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSACRealm +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_GetSACRealm_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 network_security_v1 + + +def sample_get_sac_realm(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetSACRealmRequest( + name="name_value", + ) + + # Make the request + response = client.get_sac_realm(request=request) + + # Handle the response + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_GetSACRealm_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_async.py new file mode 100644 index 000000000000..3e9bb9b093d1 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSACAttachments +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_ListSACAttachments_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 network_security_v1 + + +async def sample_list_sac_attachments(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACAttachmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_attachments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_ListSACAttachments_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_sync.py new file mode 100644 index 000000000000..dddca2e849b2 --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_attachments_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSACAttachments +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_ListSACAttachments_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 network_security_v1 + + +def sample_list_sac_attachments(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACAttachmentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_attachments(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_ListSACAttachments_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_async.py new file mode 100644 index 000000000000..af3dd1e78e9d --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSACRealms +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_ListSACRealms_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 network_security_v1 + + +async def sample_list_sac_realms(): + # Create a client + client = network_security_v1.SSERealmServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACRealmsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_realms(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_ListSACRealms_async] diff --git a/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_sync.py new file mode 100644 index 000000000000..7561f4fb05be --- /dev/null +++ b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_sse_realm_service_list_sac_realms_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSACRealms +# 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-network-security + + +# [START networksecurity_v1_generated_SSERealmService_ListSACRealms_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 network_security_v1 + + +def sample_list_sac_realms(): + # Create a client + client = network_security_v1.SSERealmServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListSACRealmsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sac_realms(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END networksecurity_v1_generated_SSERealmService_ListSACRealms_sync] diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json index f7f44fcedfbd..f5bccf332a53 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json @@ -2693,22 +2693,30 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.delete_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.create_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.CreateProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "DeleteFirewallEndpointAssociation" + "shortName": "CreateProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateFirewallEndpointRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + }, + { + "name": "firewall_endpoint_id", "type": "str" }, { @@ -2725,21 +2733,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_firewall_endpoint_association" + "shortName": "create_project_firewall_endpoint" }, - "description": "Sample for DeleteFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_async.py", + "description": "Sample for CreateProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpointAssociation_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_async", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2749,22 +2757,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_async.py" + "title": "networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_async.py" }, { "canonical": true, @@ -2773,22 +2781,30 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.delete_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.create_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.CreateProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "DeleteFirewallEndpointAssociation" + "shortName": "CreateProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateFirewallEndpointRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + }, + { + "name": "firewall_endpoint_id", "type": "str" }, { @@ -2805,21 +2821,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_firewall_endpoint_association" + "shortName": "create_project_firewall_endpoint" }, - "description": "Sample for DeleteFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_sync.py", + "description": "Sample for CreateProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpointAssociation_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_CreateProjectFirewallEndpoint_sync", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2829,22 +2845,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_create_project_firewall_endpoint_sync.py" }, { "canonical": true, @@ -2854,19 +2870,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.delete_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.delete_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpointAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "DeleteFirewallEndpoint" + "shortName": "DeleteFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointAssociationRequest" }, { "name": "name", @@ -2886,13 +2902,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_firewall_endpoint" + "shortName": "delete_firewall_endpoint_association" }, - "description": "Sample for DeleteFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_async.py", + "description": "Sample for DeleteFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpoint_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpointAssociation_async", "segments": [ { "end": 55, @@ -2925,7 +2941,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_async.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_async.py" }, { "canonical": true, @@ -2934,19 +2950,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.delete_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.delete_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpointAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "DeleteFirewallEndpoint" + "shortName": "DeleteFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointAssociationRequest" }, { "name": "name", @@ -2966,13 +2982,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_firewall_endpoint" + "shortName": "delete_firewall_endpoint_association" }, - "description": "Sample for DeleteFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_sync.py", + "description": "Sample for DeleteFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpoint_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpointAssociation_sync", "segments": [ { "end": 55, @@ -3005,7 +3021,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_association_sync.py" }, { "canonical": true, @@ -3015,19 +3031,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.get_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.delete_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "GetFirewallEndpointAssociation" + "shortName": "DeleteFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetFirewallEndpointAssociationRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" }, { "name": "name", @@ -3046,22 +3062,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.FirewallEndpointAssociation", - "shortName": "get_firewall_endpoint_association" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_firewall_endpoint" }, - "description": "Sample for GetFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_async.py", + "description": "Sample for DeleteFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpointAssociation_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpoint_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3076,17 +3092,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_async.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_async.py" }, { "canonical": true, @@ -3095,19 +3111,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.get_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.delete_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "GetFirewallEndpointAssociation" + "shortName": "DeleteFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetFirewallEndpointAssociationRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" }, { "name": "name", @@ -3126,22 +3142,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.FirewallEndpointAssociation", - "shortName": "get_firewall_endpoint_association" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_firewall_endpoint" }, - "description": "Sample for GetFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_sync.py", + "description": "Sample for DeleteFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpointAssociation_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteFirewallEndpoint_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3156,17 +3172,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_firewall_endpoint_sync.py" }, { "canonical": true, @@ -3176,19 +3192,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.get_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.delete_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "GetFirewallEndpoint" + "shortName": "DeleteProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" }, { "name": "name", @@ -3207,22 +3223,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", - "shortName": "get_firewall_endpoint" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_project_firewall_endpoint" }, - "description": "Sample for GetFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_async.py", + "description": "Sample for DeleteProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpoint_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3237,17 +3253,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_async.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_async.py" }, { "canonical": true, @@ -3256,19 +3272,19 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.get_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.delete_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.DeleteProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "GetFirewallEndpoint" + "shortName": "DeleteProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" + "type": "google.cloud.network_security_v1.types.DeleteFirewallEndpointRequest" }, { "name": "name", @@ -3287,22 +3303,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", - "shortName": "get_firewall_endpoint" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_project_firewall_endpoint" }, - "description": "Sample for GetFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_sync.py", + "description": "Sample for DeleteProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpoint_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_DeleteProjectFirewallEndpoint_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3317,17 +3333,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_delete_project_firewall_endpoint_sync.py" }, { "canonical": true, @@ -3337,22 +3353,22 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.list_firewall_endpoint_associations", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.get_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpointAssociations", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpointAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "ListFirewallEndpointAssociations" + "shortName": "GetFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListFirewallEndpointAssociationsRequest" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointAssociationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3368,22 +3384,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointAssociationsAsyncPager", - "shortName": "list_firewall_endpoint_associations" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpointAssociation", + "shortName": "get_firewall_endpoint_association" }, - "description": "Sample for ListFirewallEndpointAssociations", - "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_async.py", + "description": "Sample for GetFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpointAssociations_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpointAssociation_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3403,12 +3419,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_async.py" + "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_async.py" }, { "canonical": true, @@ -3417,22 +3433,22 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.list_firewall_endpoint_associations", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.get_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpointAssociations", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpointAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "ListFirewallEndpointAssociations" + "shortName": "GetFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListFirewallEndpointAssociationsRequest" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointAssociationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3448,22 +3464,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointAssociationsPager", - "shortName": "list_firewall_endpoint_associations" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpointAssociation", + "shortName": "get_firewall_endpoint_association" }, - "description": "Sample for ListFirewallEndpointAssociations", - "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_sync.py", + "description": "Sample for GetFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpointAssociations_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpointAssociation_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3483,12 +3499,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_association_sync.py" }, { "canonical": true, @@ -3498,22 +3514,22 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.list_firewall_endpoints", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.get_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpoints", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "ListFirewallEndpoints" + "shortName": "GetFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3529,22 +3545,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointsAsyncPager", - "shortName": "list_firewall_endpoints" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", + "shortName": "get_firewall_endpoint" }, - "description": "Sample for ListFirewallEndpoints", - "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_async.py", + "description": "Sample for GetFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpoints_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpoint_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3564,12 +3580,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_async.py" + "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_async.py" }, { "canonical": true, @@ -3578,22 +3594,22 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.list_firewall_endpoints", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.get_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpoints", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "ListFirewallEndpoints" + "shortName": "GetFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3609,22 +3625,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointsPager", - "shortName": "list_firewall_endpoints" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", + "shortName": "get_firewall_endpoint" }, - "description": "Sample for ListFirewallEndpoints", - "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_sync.py", + "description": "Sample for GetFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpoints_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetFirewallEndpoint_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3644,12 +3660,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_get_firewall_endpoint_sync.py" }, { "canonical": true, @@ -3659,27 +3675,23 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.update_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.get_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "UpdateFirewallEndpointAssociation" + "shortName": "GetProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointAssociationRequest" - }, - { - "name": "firewall_endpoint_association", - "type": "google.cloud.network_security_v1.types.FirewallEndpointAssociation" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -3694,22 +3706,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_firewall_endpoint_association" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", + "shortName": "get_project_firewall_endpoint" }, - "description": "Sample for UpdateFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_async.py", + "description": "Sample for GetProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpointAssociation_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_async", "segments": [ { - "end": 59, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3719,22 +3731,22 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_async.py" + "title": "networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_async.py" }, { "canonical": true, @@ -3743,27 +3755,23 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.update_firewall_endpoint_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.get_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpointAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.GetProjectFirewallEndpoint", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "UpdateFirewallEndpointAssociation" + "shortName": "GetProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointAssociationRequest" - }, - { - "name": "firewall_endpoint_association", - "type": "google.cloud.network_security_v1.types.FirewallEndpointAssociation" + "type": "google.cloud.network_security_v1.types.GetFirewallEndpointRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -3778,22 +3786,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_firewall_endpoint_association" + "resultType": "google.cloud.network_security_v1.types.FirewallEndpoint", + "shortName": "get_project_firewall_endpoint" }, - "description": "Sample for UpdateFirewallEndpointAssociation", - "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_sync.py", + "description": "Sample for GetProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpointAssociation_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_GetProjectFirewallEndpoint_sync", "segments": [ { - "end": 59, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3803,22 +3811,22 @@ "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": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_get_project_firewall_endpoint_sync.py" }, { "canonical": true, @@ -3828,27 +3836,23 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.update_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.list_firewall_endpoint_associations", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpointAssociations", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "UpdateFirewallEndpoint" + "shortName": "ListFirewallEndpointAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" - }, - { - "name": "firewall_endpoint", - "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointAssociationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -3863,22 +3867,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_firewall_endpoint" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointAssociationsAsyncPager", + "shortName": "list_firewall_endpoint_associations" }, - "description": "Sample for UpdateFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_async.py", + "description": "Sample for ListFirewallEndpointAssociations", + "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpoint_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpointAssociations_async", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3888,22 +3892,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_async.py" + "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_async.py" }, { "canonical": true, @@ -3912,27 +3916,23 @@ "fullName": "google.cloud.network_security_v1.FirewallActivationClient", "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.FirewallActivationClient.update_firewall_endpoint", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.list_firewall_endpoint_associations", "method": { - "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpoint", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpointAssociations", "service": { "fullName": "google.cloud.networksecurity.v1.FirewallActivation", "shortName": "FirewallActivation" }, - "shortName": "UpdateFirewallEndpoint" + "shortName": "ListFirewallEndpointAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" - }, - { - "name": "firewall_endpoint", - "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointAssociationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -3947,22 +3947,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_firewall_endpoint" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointAssociationsPager", + "shortName": "list_firewall_endpoint_associations" }, - "description": "Sample for UpdateFirewallEndpoint", - "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_sync.py", + "description": "Sample for ListFirewallEndpointAssociations", + "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpoint_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpointAssociations_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3972,57 +3972,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoint_associations_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", - "shortName": "InterceptAsyncClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", + "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.list_firewall_endpoints", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpoints", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptDeploymentGroup" + "shortName": "ListFirewallEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "intercept_deployment_group", - "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" - }, - { - "name": "intercept_deployment_group_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4036,22 +4028,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_intercept_deployment_group" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointsAsyncPager", + "shortName": "list_firewall_endpoints" }, - "description": "Sample for CreateInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_async.py", + "description": "Sample for ListFirewallEndpoints", + "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpoints_async", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4061,56 +4053,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_async.py" + "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.InterceptClient", - "shortName": "InterceptClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationClient", + "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.list_firewall_endpoints", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListFirewallEndpoints", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptDeploymentGroup" + "shortName": "ListFirewallEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "intercept_deployment_group", - "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" - }, - { - "name": "intercept_deployment_group_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4124,22 +4108,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_intercept_deployment_group" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListFirewallEndpointsPager", + "shortName": "list_firewall_endpoints" }, - "description": "Sample for CreateInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_sync.py", + "description": "Sample for ListFirewallEndpoints", + "file": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListFirewallEndpoints_sync", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4149,57 +4133,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_list_firewall_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", - "shortName": "InterceptAsyncClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", + "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_deployment", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.list_project_firewall_endpoints", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListProjectFirewallEndpoints", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptDeployment" + "shortName": "ListProjectFirewallEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "intercept_deployment", - "type": "google.cloud.network_security_v1.types.InterceptDeployment" - }, - { - "name": "intercept_deployment_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4213,22 +4189,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_intercept_deployment" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListProjectFirewallEndpointsAsyncPager", + "shortName": "list_project_firewall_endpoints" }, - "description": "Sample for CreateInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_async.py", + "description": "Sample for ListProjectFirewallEndpoints", + "file": "networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeployment_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_async", "segments": [ { - "end": 61, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4238,56 +4214,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_async.py" + "title": "networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.InterceptClient", - "shortName": "InterceptClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationClient", + "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_deployment", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.list_project_firewall_endpoints", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.ListProjectFirewallEndpoints", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptDeployment" + "shortName": "ListProjectFirewallEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.ListFirewallEndpointsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "intercept_deployment", - "type": "google.cloud.network_security_v1.types.InterceptDeployment" - }, - { - "name": "intercept_deployment_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4301,22 +4269,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_intercept_deployment" + "resultType": "google.cloud.network_security_v1.services.firewall_activation.pagers.ListProjectFirewallEndpointsPager", + "shortName": "list_project_firewall_endpoints" }, - "description": "Sample for CreateInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_sync.py", + "description": "Sample for ListProjectFirewallEndpoints", + "file": "networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeployment_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_ListProjectFirewallEndpoints_sync", "segments": [ { - "end": 61, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4326,56 +4294,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_list_project_firewall_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", - "shortName": "InterceptAsyncClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", + "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.update_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpointAssociation", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptEndpointGroupAssociation" + "shortName": "UpdateFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupAssociationRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointAssociationRequest" }, { - "name": "intercept_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + "name": "firewall_endpoint_association", + "type": "google.cloud.network_security_v1.types.FirewallEndpointAssociation" }, { - "name": "intercept_endpoint_group_association_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4391,21 +4355,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_intercept_endpoint_group_association" + "shortName": "update_firewall_endpoint_association" }, - "description": "Sample for CreateInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_async.py", + "description": "Sample for UpdateFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpointAssociation_async", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -4415,55 +4379,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.InterceptClient", - "shortName": "InterceptClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationClient", + "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.update_firewall_endpoint_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpointAssociation", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptEndpointGroupAssociation" + "shortName": "UpdateFirewallEndpointAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupAssociationRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointAssociationRequest" }, { - "name": "intercept_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + "name": "firewall_endpoint_association", + "type": "google.cloud.network_security_v1.types.FirewallEndpointAssociation" }, { - "name": "intercept_endpoint_group_association_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4479,21 +4439,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_intercept_endpoint_group_association" + "shortName": "update_firewall_endpoint_association" }, - "description": "Sample for CreateInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_sync.py", + "description": "Sample for UpdateFirewallEndpointAssociation", + "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpointAssociation_sync", "segments": [ { - "end": 60, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 59, "start": 27, "type": "SHORT" }, @@ -4503,56 +4463,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_association_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", - "shortName": "InterceptAsyncClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", + "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.update_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpoint", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptEndpointGroup" + "shortName": "UpdateFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" }, { - "name": "intercept_endpoint_group", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" }, { - "name": "intercept_endpoint_group_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4568,21 +4524,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_intercept_endpoint_group" + "shortName": "update_firewall_endpoint" }, - "description": "Sample for CreateInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_async.py", + "description": "Sample for UpdateFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpoint_async", "segments": [ { - "end": 60, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 54, "start": 27, "type": "SHORT" }, @@ -4592,55 +4548,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_async.py" + "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.InterceptClient", - "shortName": "InterceptClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationClient", + "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.update_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateFirewallEndpoint", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "CreateInterceptEndpointGroup" + "shortName": "UpdateFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" }, { - "name": "intercept_endpoint_group", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" }, { - "name": "intercept_endpoint_group_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4656,21 +4608,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_intercept_endpoint_group" + "shortName": "update_firewall_endpoint" }, - "description": "Sample for CreateInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_sync.py", + "description": "Sample for UpdateFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateFirewallEndpoint_sync", "segments": [ { - "end": 60, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 54, "start": 27, "type": "SHORT" }, @@ -4680,48 +4632,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_update_firewall_endpoint_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", - "shortName": "InterceptAsyncClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient", + "shortName": "FirewallActivationAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationAsyncClient.update_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateProjectFirewallEndpoint", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "DeleteInterceptDeploymentGroup" + "shortName": "UpdateProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" }, { - "name": "name", - "type": "str" + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4737,21 +4693,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_intercept_deployment_group" + "shortName": "update_project_firewall_endpoint" }, - "description": "Sample for DeleteInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_async.py", + "description": "Sample for UpdateProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -4761,47 +4717,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_async.py" + "title": "networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.InterceptClient", - "shortName": "InterceptClient" + "fullName": "google.cloud.network_security_v1.FirewallActivationClient", + "shortName": "FirewallActivationClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.FirewallActivationClient.update_project_firewall_endpoint", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.FirewallActivation.UpdateProjectFirewallEndpoint", "service": { - "fullName": "google.cloud.networksecurity.v1.Intercept", - "shortName": "Intercept" + "fullName": "google.cloud.networksecurity.v1.FirewallActivation", + "shortName": "FirewallActivation" }, - "shortName": "DeleteInterceptDeploymentGroup" + "shortName": "UpdateProjectFirewallEndpoint" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.UpdateFirewallEndpointRequest" }, { - "name": "name", - "type": "str" + "name": "firewall_endpoint", + "type": "google.cloud.network_security_v1.types.FirewallEndpoint" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -4817,21 +4777,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_intercept_deployment_group" + "shortName": "update_project_firewall_endpoint" }, - "description": "Sample for DeleteInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_sync.py", + "description": "Sample for UpdateProjectFirewallEndpoint", + "file": "networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_FirewallActivation_UpdateProjectFirewallEndpoint_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -4841,22 +4801,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_sync.py" + "title": "networksecurity_v1_generated_firewall_activation_update_project_firewall_endpoint_sync.py" }, { "canonical": true, @@ -4866,22 +4826,30 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptDeployment" + "shortName": "CreateInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_deployment_group", + "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" + }, + { + "name": "intercept_deployment_group_id", "type": "str" }, { @@ -4898,21 +4866,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_intercept_deployment" + "shortName": "create_intercept_deployment_group" }, - "description": "Sample for DeleteInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_async.py", + "description": "Sample for CreateInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeployment_async", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeploymentGroup_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -4922,22 +4890,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_async.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_async.py" }, { "canonical": true, @@ -4946,22 +4914,30 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptDeployment" + "shortName": "CreateInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_deployment_group", + "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" + }, + { + "name": "intercept_deployment_group_id", "type": "str" }, { @@ -4978,21 +4954,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_intercept_deployment" + "shortName": "create_intercept_deployment_group" }, - "description": "Sample for DeleteInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_sync.py", + "description": "Sample for CreateInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeployment_sync", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeploymentGroup_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -5002,22 +4978,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_sync.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_group_sync.py" }, { "canonical": true, @@ -5027,22 +5003,30 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptEndpointGroupAssociation" + "shortName": "CreateInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_deployment", + "type": "google.cloud.network_security_v1.types.InterceptDeployment" + }, + { + "name": "intercept_deployment_id", "type": "str" }, { @@ -5059,21 +5043,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_intercept_endpoint_group_association" + "shortName": "create_intercept_deployment" }, - "description": "Sample for DeleteInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_async.py", + "description": "Sample for CreateInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeployment_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -5083,22 +5067,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_async.py" }, { "canonical": true, @@ -5107,22 +5091,30 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptEndpointGroupAssociation" + "shortName": "CreateInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptDeploymentRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_deployment", + "type": "google.cloud.network_security_v1.types.InterceptDeployment" + }, + { + "name": "intercept_deployment_id", "type": "str" }, { @@ -5139,21 +5131,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_intercept_endpoint_group_association" + "shortName": "create_intercept_deployment" }, - "description": "Sample for DeleteInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_sync.py", + "description": "Sample for CreateInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_create_intercept_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptDeployment_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -5163,22 +5155,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_deployment_sync.py" }, { "canonical": true, @@ -5188,22 +5180,30 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptEndpointGroup" + "shortName": "CreateInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + }, + { + "name": "intercept_endpoint_group_association_id", "type": "str" }, { @@ -5220,21 +5220,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_intercept_endpoint_group" + "shortName": "create_intercept_endpoint_group_association" }, - "description": "Sample for DeleteInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_async.py", + "description": "Sample for CreateInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroupAssociation_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -5244,22 +5244,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_async.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_async.py" }, { "canonical": true, @@ -5268,22 +5268,30 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "DeleteInterceptEndpointGroup" + "shortName": "CreateInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + }, + { + "name": "intercept_endpoint_group_association_id", "type": "str" }, { @@ -5300,21 +5308,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_intercept_endpoint_group" + "shortName": "create_intercept_endpoint_group_association" }, - "description": "Sample for DeleteInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_sync.py", + "description": "Sample for CreateInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroupAssociation_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -5324,22 +5332,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_association_sync.py" }, { "canonical": true, @@ -5349,22 +5357,30 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.create_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptDeploymentGroup" + "shortName": "CreateInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_endpoint_group", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + }, + { + "name": "intercept_endpoint_group_id", "type": "str" }, { @@ -5380,22 +5396,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptDeploymentGroup", - "shortName": "get_intercept_deployment_group" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_intercept_endpoint_group" }, - "description": "Sample for GetInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_async.py", + "description": "Sample for CreateInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroup_async", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -5405,22 +5421,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_async.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_async.py" }, { "canonical": true, @@ -5429,22 +5445,30 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.create_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.CreateInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptDeploymentGroup" + "shortName": "CreateInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateInterceptEndpointGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "intercept_endpoint_group", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + }, + { + "name": "intercept_endpoint_group_id", "type": "str" }, { @@ -5460,22 +5484,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptDeploymentGroup", - "shortName": "get_intercept_deployment_group" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_intercept_endpoint_group" }, - "description": "Sample for GetInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_sync.py", + "description": "Sample for CreateInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_CreateInterceptEndpointGroup_sync", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -5485,22 +5509,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_sync.py" + "title": "networksecurity_v1_generated_intercept_create_intercept_endpoint_group_sync.py" }, { "canonical": true, @@ -5510,19 +5534,19 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptDeployment" + "shortName": "DeleteInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentGroupRequest" }, { "name": "name", @@ -5541,22 +5565,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptDeployment", - "shortName": "get_intercept_deployment" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_intercept_deployment_group" }, - "description": "Sample for GetInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_async.py", + "description": "Sample for DeleteInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeployment_async", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeploymentGroup_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5571,17 +5595,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_async.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_async.py" }, { "canonical": true, @@ -5590,19 +5614,19 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptDeployment" + "shortName": "DeleteInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentGroupRequest" }, { "name": "name", @@ -5621,22 +5645,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptDeployment", - "shortName": "get_intercept_deployment" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_intercept_deployment_group" }, - "description": "Sample for GetInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_sync.py", + "description": "Sample for DeleteInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeployment_sync", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeploymentGroup_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5651,17 +5675,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_sync.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_group_sync.py" }, { "canonical": true, @@ -5671,19 +5695,19 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptEndpointGroupAssociation" + "shortName": "DeleteInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentRequest" }, { "name": "name", @@ -5702,22 +5726,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation", - "shortName": "get_intercept_endpoint_group_association" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_intercept_deployment" }, - "description": "Sample for GetInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_async.py", + "description": "Sample for DeleteInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeployment_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5732,17 +5756,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_async.py" }, { "canonical": true, @@ -5751,19 +5775,19 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptEndpointGroupAssociation" + "shortName": "DeleteInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptDeploymentRequest" }, { "name": "name", @@ -5782,22 +5806,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation", - "shortName": "get_intercept_endpoint_group_association" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_intercept_deployment" }, - "description": "Sample for GetInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_sync.py", + "description": "Sample for DeleteInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_delete_intercept_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptDeployment_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5812,17 +5836,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_deployment_sync.py" }, { "canonical": true, @@ -5832,19 +5856,19 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptEndpointGroup" + "shortName": "DeleteInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupAssociationRequest" }, { "name": "name", @@ -5863,22 +5887,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroup", - "shortName": "get_intercept_endpoint_group" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_intercept_endpoint_group_association" }, - "description": "Sample for GetInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_async.py", + "description": "Sample for DeleteInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroupAssociation_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5893,17 +5917,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_async.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_async.py" }, { "canonical": true, @@ -5912,19 +5936,19 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "GetInterceptEndpointGroup" + "shortName": "DeleteInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupAssociationRequest" }, { "name": "name", @@ -5943,22 +5967,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroup", - "shortName": "get_intercept_endpoint_group" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_intercept_endpoint_group_association" }, - "description": "Sample for GetInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_sync.py", + "description": "Sample for DeleteInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroupAssociation_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5973,17 +5997,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_association_sync.py" }, { "canonical": true, @@ -5993,22 +6017,22 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_deployment_groups", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.delete_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeploymentGroups", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptDeploymentGroups" + "shortName": "DeleteInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6024,22 +6048,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentGroupsAsyncPager", - "shortName": "list_intercept_deployment_groups" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_intercept_endpoint_group" }, - "description": "Sample for ListInterceptDeploymentGroups", - "file": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_async.py", + "description": "Sample for DeleteInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeploymentGroups_async", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroup_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6054,17 +6078,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_async.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_async.py" }, { "canonical": true, @@ -6073,22 +6097,22 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_deployment_groups", + "fullName": "google.cloud.network_security_v1.InterceptClient.delete_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeploymentGroups", + "fullName": "google.cloud.networksecurity.v1.Intercept.DeleteInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptDeploymentGroups" + "shortName": "DeleteInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteInterceptEndpointGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6104,22 +6128,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentGroupsPager", - "shortName": "list_intercept_deployment_groups" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_intercept_endpoint_group" }, - "description": "Sample for ListInterceptDeploymentGroups", - "file": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_sync.py", + "description": "Sample for DeleteInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeploymentGroups_sync", + "regionTag": "networksecurity_v1_generated_Intercept_DeleteInterceptEndpointGroup_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6134,17 +6158,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_sync.py" + "title": "networksecurity_v1_generated_intercept_delete_intercept_endpoint_group_sync.py" }, { "canonical": true, @@ -6154,22 +6178,22 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_deployments", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeployments", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptDeployments" + "shortName": "GetInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6185,22 +6209,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentsAsyncPager", - "shortName": "list_intercept_deployments" + "resultType": "google.cloud.network_security_v1.types.InterceptDeploymentGroup", + "shortName": "get_intercept_deployment_group" }, - "description": "Sample for ListInterceptDeployments", - "file": "networksecurity_v1_generated_intercept_list_intercept_deployments_async.py", + "description": "Sample for GetInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeployments_async", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeploymentGroup_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6220,12 +6244,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_deployments_async.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_async.py" }, { "canonical": true, @@ -6234,22 +6258,22 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_deployments", + "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeployments", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptDeployments" + "shortName": "GetInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6265,22 +6289,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentsPager", - "shortName": "list_intercept_deployments" + "resultType": "google.cloud.network_security_v1.types.InterceptDeploymentGroup", + "shortName": "get_intercept_deployment_group" }, - "description": "Sample for ListInterceptDeployments", - "file": "networksecurity_v1_generated_intercept_list_intercept_deployments_sync.py", + "description": "Sample for GetInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeployments_sync", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeploymentGroup_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6300,12 +6324,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_deployments_sync.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_group_sync.py" }, { "canonical": true, @@ -6315,22 +6339,22 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_endpoint_group_associations", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroupAssociations", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptEndpointGroupAssociations" + "shortName": "GetInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupAssociationsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6346,22 +6370,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupAssociationsAsyncPager", - "shortName": "list_intercept_endpoint_group_associations" + "resultType": "google.cloud.network_security_v1.types.InterceptDeployment", + "shortName": "get_intercept_deployment" }, - "description": "Sample for ListInterceptEndpointGroupAssociations", - "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_async.py", + "description": "Sample for GetInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroupAssociations_async", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeployment_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6381,12 +6405,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_async.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_async.py" }, { "canonical": true, @@ -6395,22 +6419,22 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_endpoint_group_associations", + "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroupAssociations", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptEndpointGroupAssociations" + "shortName": "GetInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupAssociationsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptDeploymentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6426,22 +6450,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupAssociationsPager", - "shortName": "list_intercept_endpoint_group_associations" + "resultType": "google.cloud.network_security_v1.types.InterceptDeployment", + "shortName": "get_intercept_deployment" }, - "description": "Sample for ListInterceptEndpointGroupAssociations", - "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_sync.py", + "description": "Sample for GetInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_get_intercept_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroupAssociations_sync", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptDeployment_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6461,12 +6485,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_sync.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_deployment_sync.py" }, { "canonical": true, @@ -6476,22 +6500,22 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_endpoint_groups", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroups", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptEndpointGroups" + "shortName": "GetInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupAssociationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6507,22 +6531,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupsAsyncPager", - "shortName": "list_intercept_endpoint_groups" + "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation", + "shortName": "get_intercept_endpoint_group_association" }, - "description": "Sample for ListInterceptEndpointGroups", - "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_async.py", + "description": "Sample for GetInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroups_async", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroupAssociation_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6542,12 +6566,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_async.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_async.py" }, { "canonical": true, @@ -6556,22 +6580,22 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_endpoint_groups", + "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroups", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "ListInterceptEndpointGroups" + "shortName": "GetInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupsRequest" + "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupAssociationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6587,22 +6611,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupsPager", - "shortName": "list_intercept_endpoint_groups" + "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation", + "shortName": "get_intercept_endpoint_group_association" }, - "description": "Sample for ListInterceptEndpointGroups", - "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_sync.py", + "description": "Sample for GetInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroups_sync", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroupAssociation_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6622,12 +6646,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_sync.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_association_sync.py" }, { "canonical": true, @@ -6637,27 +6661,23 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.get_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptDeploymentGroup" + "shortName": "GetInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentGroupRequest" - }, - { - "name": "intercept_deployment_group", - "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" + "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -6672,22 +6692,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_intercept_deployment_group" + "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroup", + "shortName": "get_intercept_endpoint_group" }, - "description": "Sample for UpdateInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_async.py", + "description": "Sample for GetInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroup_async", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6697,22 +6717,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_async.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_async.py" }, { "canonical": true, @@ -6721,27 +6741,23 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.get_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.GetInterceptEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptDeploymentGroup" + "shortName": "GetInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentGroupRequest" - }, - { - "name": "intercept_deployment_group", - "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" + "type": "google.cloud.network_security_v1.types.GetInterceptEndpointGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -6756,22 +6772,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_intercept_deployment_group" + "resultType": "google.cloud.network_security_v1.types.InterceptEndpointGroup", + "shortName": "get_intercept_endpoint_group" }, - "description": "Sample for UpdateInterceptDeploymentGroup", - "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_sync.py", + "description": "Sample for GetInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_GetInterceptEndpointGroup_sync", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6781,22 +6797,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_sync.py" + "title": "networksecurity_v1_generated_intercept_get_intercept_endpoint_group_sync.py" }, { "canonical": true, @@ -6806,27 +6822,23 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_deployment_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeploymentGroups", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptDeployment" + "shortName": "ListInterceptDeploymentGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentRequest" + "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentGroupsRequest" }, { - "name": "intercept_deployment", - "type": "google.cloud.network_security_v1.types.InterceptDeployment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -6841,22 +6853,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_intercept_deployment" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentGroupsAsyncPager", + "shortName": "list_intercept_deployment_groups" }, - "description": "Sample for UpdateInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_async.py", + "description": "Sample for ListInterceptDeploymentGroups", + "file": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeployment_async", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeploymentGroups_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6866,22 +6878,22 @@ "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": "networksecurity_v1_generated_intercept_update_intercept_deployment_async.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_async.py" }, { "canonical": true, @@ -6890,27 +6902,23 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_deployment", + "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_deployment_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeploymentGroups", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptDeployment" + "shortName": "ListInterceptDeploymentGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentRequest" - }, - { - "name": "intercept_deployment", - "type": "google.cloud.network_security_v1.types.InterceptDeployment" + "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentGroupsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -6925,22 +6933,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_intercept_deployment" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentGroupsPager", + "shortName": "list_intercept_deployment_groups" }, - "description": "Sample for UpdateInterceptDeployment", - "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_sync.py", + "description": "Sample for ListInterceptDeploymentGroups", + "file": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeployment_sync", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeploymentGroups_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6950,22 +6958,22 @@ "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": "networksecurity_v1_generated_intercept_update_intercept_deployment_sync.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_deployment_groups_sync.py" }, { "canonical": true, @@ -6975,27 +6983,23 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_deployments", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeployments", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptEndpointGroupAssociation" + "shortName": "ListInterceptDeployments" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupAssociationRequest" - }, - { - "name": "intercept_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7010,22 +7014,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_intercept_endpoint_group_association" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentsAsyncPager", + "shortName": "list_intercept_deployments" }, - "description": "Sample for UpdateInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_async.py", + "description": "Sample for ListInterceptDeployments", + "file": "networksecurity_v1_generated_intercept_list_intercept_deployments_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeployments_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7035,22 +7039,22 @@ "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": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_deployments_async.py" }, { "canonical": true, @@ -7059,27 +7063,23 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_deployments", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptDeployments", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptEndpointGroupAssociation" + "shortName": "ListInterceptDeployments" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupAssociationRequest" - }, - { - "name": "intercept_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" + "type": "google.cloud.network_security_v1.types.ListInterceptDeploymentsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7094,22 +7094,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_intercept_endpoint_group_association" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptDeploymentsPager", + "shortName": "list_intercept_deployments" }, - "description": "Sample for UpdateInterceptEndpointGroupAssociation", - "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_sync.py", + "description": "Sample for ListInterceptDeployments", + "file": "networksecurity_v1_generated_intercept_list_intercept_deployments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptDeployments_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7119,22 +7119,22 @@ "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": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_deployments_sync.py" }, { "canonical": true, @@ -7144,27 +7144,23 @@ "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_endpoint_group_associations", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroupAssociations", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptEndpointGroup" + "shortName": "ListInterceptEndpointGroupAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupRequest" - }, - { - "name": "intercept_endpoint_group", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupAssociationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7179,22 +7175,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_intercept_endpoint_group" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupAssociationsAsyncPager", + "shortName": "list_intercept_endpoint_group_associations" }, - "description": "Sample for UpdateInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_async.py", + "description": "Sample for ListInterceptEndpointGroupAssociations", + "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroupAssociations_async", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7204,22 +7200,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_async.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_async.py" }, { "canonical": true, @@ -7228,27 +7224,23 @@ "fullName": "google.cloud.network_security_v1.InterceptClient", "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_endpoint_group_associations", "method": { - "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroupAssociations", "service": { "fullName": "google.cloud.networksecurity.v1.Intercept", "shortName": "Intercept" }, - "shortName": "UpdateInterceptEndpointGroup" + "shortName": "ListInterceptEndpointGroupAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupRequest" - }, - { - "name": "intercept_endpoint_group", - "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupAssociationsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -7263,22 +7255,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_intercept_endpoint_group" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupAssociationsPager", + "shortName": "list_intercept_endpoint_group_associations" }, - "description": "Sample for UpdateInterceptEndpointGroup", - "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_sync.py", + "description": "Sample for ListInterceptEndpointGroupAssociations", + "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroupAssociations_sync", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7288,57 +7280,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_group_associations_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", + "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.list_intercept_endpoint_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringDeploymentGroup" + "shortName": "ListInterceptEndpointGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "mirroring_deployment_group", - "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" - }, - { - "name": "mirroring_deployment_group_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7352,22 +7336,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_mirroring_deployment_group" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupsAsyncPager", + "shortName": "list_intercept_endpoint_groups" }, - "description": "Sample for CreateMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_async.py", + "description": "Sample for ListInterceptEndpointGroups", + "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroups_async", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7377,56 +7361,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_async.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.InterceptClient", + "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.list_intercept_endpoint_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.ListInterceptEndpointGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringDeploymentGroup" + "shortName": "ListInterceptEndpointGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.ListInterceptEndpointGroupsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "mirroring_deployment_group", - "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" - }, - { - "name": "mirroring_deployment_group_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7440,22 +7416,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_mirroring_deployment_group" + "resultType": "google.cloud.network_security_v1.services.intercept.pagers.ListInterceptEndpointGroupsPager", + "shortName": "list_intercept_endpoint_groups" }, - "description": "Sample for CreateMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_sync.py", + "description": "Sample for ListInterceptEndpointGroups", + "file": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_ListInterceptEndpointGroups_sync", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7465,56 +7441,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_sync.py" + "title": "networksecurity_v1_generated_intercept_list_intercept_endpoint_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", + "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeploymentGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringDeployment" + "shortName": "UpdateInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentGroupRequest" }, { - "name": "mirroring_deployment", - "type": "google.cloud.network_security_v1.types.MirroringDeployment" + "name": "intercept_deployment_group", + "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" }, { - "name": "mirroring_deployment_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7530,21 +7502,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_mirroring_deployment" + "shortName": "update_intercept_deployment_group" }, - "description": "Sample for CreateMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_async.py", + "description": "Sample for UpdateInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeployment_async", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeploymentGroup_async", "segments": [ { - "end": 61, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 58, "start": 27, "type": "SHORT" }, @@ -7554,55 +7526,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_async.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.InterceptClient", + "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeploymentGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringDeployment" + "shortName": "UpdateInterceptDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentGroupRequest" }, { - "name": "mirroring_deployment", - "type": "google.cloud.network_security_v1.types.MirroringDeployment" + "name": "intercept_deployment_group", + "type": "google.cloud.network_security_v1.types.InterceptDeploymentGroup" }, { - "name": "mirroring_deployment_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7618,21 +7586,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_mirroring_deployment" + "shortName": "update_intercept_deployment_group" }, - "description": "Sample for CreateMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_sync.py", + "description": "Sample for UpdateInterceptDeploymentGroup", + "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeployment_sync", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeploymentGroup_sync", "segments": [ { - "end": 61, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 58, "start": 27, "type": "SHORT" }, @@ -7642,56 +7610,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_sync.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", + "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeployment", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringEndpointGroupAssociation" + "shortName": "UpdateInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupAssociationRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentRequest" }, { - "name": "mirroring_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + "name": "intercept_deployment", + "type": "google.cloud.network_security_v1.types.InterceptDeployment" }, { - "name": "mirroring_endpoint_group_association_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7707,21 +7671,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_mirroring_endpoint_group_association" + "shortName": "update_intercept_deployment" }, - "description": "Sample for CreateMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_async.py", + "description": "Sample for UpdateInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeployment_async", "segments": [ { - "end": 55, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 59, "start": 27, "type": "SHORT" }, @@ -7731,55 +7695,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.InterceptClient", + "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptDeployment", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringEndpointGroupAssociation" + "shortName": "UpdateInterceptDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.UpdateInterceptDeploymentRequest" }, { - "name": "parent", - "type": "str" - }, - { - "name": "mirroring_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + "name": "intercept_deployment", + "type": "google.cloud.network_security_v1.types.InterceptDeployment" }, { - "name": "mirroring_endpoint_group_association_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7795,21 +7755,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_mirroring_endpoint_group_association" + "shortName": "update_intercept_deployment" }, - "description": "Sample for CreateMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_sync.py", + "description": "Sample for UpdateInterceptDeployment", + "file": "networksecurity_v1_generated_intercept_update_intercept_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptDeployment_sync", "segments": [ { - "end": 55, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 59, "start": 27, "type": "SHORT" }, @@ -7819,56 +7779,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_deployment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", + "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroupAssociation", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringEndpointGroup" + "shortName": "UpdateInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupAssociationRequest" }, { - "name": "mirroring_endpoint_group", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + "name": "intercept_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" }, { - "name": "mirroring_endpoint_group_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7884,21 +7840,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_mirroring_endpoint_group" + "shortName": "update_intercept_endpoint_group_association" }, - "description": "Sample for CreateMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_async.py", + "description": "Sample for UpdateInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroupAssociation_async", "segments": [ { - "end": 56, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 59, "start": 27, "type": "SHORT" }, @@ -7908,55 +7864,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_async.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.InterceptClient", + "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroupAssociation", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "CreateMirroringEndpointGroup" + "shortName": "UpdateInterceptEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupAssociationRequest" }, { - "name": "mirroring_endpoint_group", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + "name": "intercept_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroupAssociation" }, { - "name": "mirroring_endpoint_group_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -7972,21 +7924,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_mirroring_endpoint_group" + "shortName": "update_intercept_endpoint_group_association" }, - "description": "Sample for CreateMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_sync.py", + "description": "Sample for UpdateInterceptEndpointGroupAssociation", + "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroupAssociation_sync", "segments": [ { - "end": 56, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 59, "start": 27, "type": "SHORT" }, @@ -7996,48 +7948,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_association_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient", + "shortName": "InterceptAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptAsyncClient.update_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "DeleteMirroringDeploymentGroup" + "shortName": "UpdateInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupRequest" }, { - "name": "name", - "type": "str" + "name": "intercept_endpoint_group", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8053,21 +8009,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_mirroring_deployment_group" + "shortName": "update_intercept_endpoint_group" }, - "description": "Sample for DeleteMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_async.py", + "description": "Sample for UpdateInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroup_async", "segments": [ { - "end": 55, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 58, "start": 27, "type": "SHORT" }, @@ -8077,47 +8033,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_async.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.InterceptClient", + "shortName": "InterceptClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.InterceptClient.update_intercept_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Intercept.UpdateInterceptEndpointGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.Intercept", + "shortName": "Intercept" }, - "shortName": "DeleteMirroringDeploymentGroup" + "shortName": "UpdateInterceptEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.UpdateInterceptEndpointGroupRequest" }, { - "name": "name", - "type": "str" + "name": "intercept_endpoint_group", + "type": "google.cloud.network_security_v1.types.InterceptEndpointGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8133,21 +8093,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_mirroring_deployment_group" + "shortName": "update_intercept_endpoint_group" }, - "description": "Sample for DeleteMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_sync.py", + "description": "Sample for UpdateInterceptEndpointGroup", + "file": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_Intercept_UpdateInterceptEndpointGroup_sync", "segments": [ { - "end": 55, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 58, "start": 27, "type": "SHORT" }, @@ -8157,22 +8117,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_sync.py" + "title": "networksecurity_v1_generated_intercept_update_intercept_endpoint_group_sync.py" }, { "canonical": true, @@ -8182,22 +8142,30 @@ "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", "shortName": "MirroringAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringDeployment" + "shortName": "CreateMirroringDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_deployment_group", + "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + }, + { + "name": "mirroring_deployment_group_id", "type": "str" }, { @@ -8214,21 +8182,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_mirroring_deployment" + "shortName": "create_mirroring_deployment_group" }, - "description": "Sample for DeleteMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_async.py", + "description": "Sample for CreateMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeployment_async", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeploymentGroup_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -8238,22 +8206,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_async.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_async.py" }, { "canonical": true, @@ -8262,22 +8230,30 @@ "fullName": "google.cloud.network_security_v1.MirroringClient", "shortName": "MirroringClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_deployment_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeploymentGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringDeployment" + "shortName": "CreateMirroringDeploymentGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_deployment_group", + "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + }, + { + "name": "mirroring_deployment_group_id", "type": "str" }, { @@ -8294,21 +8270,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_mirroring_deployment" + "shortName": "create_mirroring_deployment_group" }, - "description": "Sample for DeleteMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_sync.py", + "description": "Sample for CreateMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeployment_sync", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeploymentGroup_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -8318,22 +8294,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_sync.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_group_sync.py" }, { "canonical": true, @@ -8343,22 +8319,30 @@ "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", "shortName": "MirroringAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringEndpointGroupAssociation" + "shortName": "CreateMirroringDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_deployment", + "type": "google.cloud.network_security_v1.types.MirroringDeployment" + }, + { + "name": "mirroring_deployment_id", "type": "str" }, { @@ -8375,21 +8359,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_mirroring_endpoint_group_association" + "shortName": "create_mirroring_deployment" }, - "description": "Sample for DeleteMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_async.py", + "description": "Sample for CreateMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeployment_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -8399,22 +8383,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_async.py" }, { "canonical": true, @@ -8423,22 +8407,30 @@ "fullName": "google.cloud.network_security_v1.MirroringClient", "shortName": "MirroringClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringEndpointGroupAssociation" + "shortName": "CreateMirroringDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringDeploymentRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_deployment", + "type": "google.cloud.network_security_v1.types.MirroringDeployment" + }, + { + "name": "mirroring_deployment_id", "type": "str" }, { @@ -8455,21 +8447,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_mirroring_endpoint_group_association" + "shortName": "create_mirroring_deployment" }, - "description": "Sample for DeleteMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_sync.py", + "description": "Sample for CreateMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringDeployment_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -8479,22 +8471,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_deployment_sync.py" }, { "canonical": true, @@ -8504,22 +8496,30 @@ "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", "shortName": "MirroringAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringEndpointGroup" + "shortName": "CreateMirroringEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + }, + { + "name": "mirroring_endpoint_group_association_id", "type": "str" }, { @@ -8536,13 +8536,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_mirroring_endpoint_group" + "shortName": "create_mirroring_endpoint_group_association" }, - "description": "Sample for DeleteMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_async.py", + "description": "Sample for CreateMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroupAssociation_async", "segments": [ { "end": 55, @@ -8575,7 +8575,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_async.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_async.py" }, { "canonical": true, @@ -8584,22 +8584,30 @@ "fullName": "google.cloud.network_security_v1.MirroringClient", "shortName": "MirroringClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_endpoint_group_association", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroupAssociation", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "DeleteMirroringEndpointGroup" + "shortName": "CreateMirroringEndpointGroupAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + }, + { + "name": "mirroring_endpoint_group_association_id", "type": "str" }, { @@ -8616,13 +8624,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_mirroring_endpoint_group" + "shortName": "create_mirroring_endpoint_group_association" }, - "description": "Sample for DeleteMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_sync.py", + "description": "Sample for CreateMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroupAssociation_sync", "segments": [ { "end": 55, @@ -8655,7 +8663,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_association_sync.py" }, { "canonical": true, @@ -8665,22 +8673,30 @@ "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", "shortName": "MirroringAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.create_mirroring_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "GetMirroringDeploymentGroup" + "shortName": "CreateMirroringEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_endpoint_group", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + }, + { + "name": "mirroring_endpoint_group_id", "type": "str" }, { @@ -8696,22 +8712,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringDeploymentGroup", - "shortName": "get_mirroring_deployment_group" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_mirroring_endpoint_group" }, - "description": "Sample for GetMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_async.py", + "description": "Sample for CreateMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroup_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -8721,22 +8737,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_async.py" + "title": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_async.py" }, { "canonical": true, @@ -8745,22 +8761,30 @@ "fullName": "google.cloud.network_security_v1.MirroringClient", "shortName": "MirroringClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.MirroringClient.create_mirroring_endpoint_group", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.Mirroring.CreateMirroringEndpointGroup", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "GetMirroringDeploymentGroup" + "shortName": "CreateMirroringEndpointGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateMirroringEndpointGroupRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "mirroring_endpoint_group", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + }, + { + "name": "mirroring_endpoint_group_id", "type": "str" }, { @@ -8776,22 +8800,103 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringDeploymentGroup", - "shortName": "get_mirroring_deployment_group" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_mirroring_endpoint_group" }, - "description": "Sample for GetMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_sync.py", + "description": "Sample for CreateMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_Mirroring_CreateMirroringEndpointGroup_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "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": "networksecurity_v1_generated_mirroring_create_mirroring_endpoint_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mirroring_deployment_group" + }, + "description": "Sample for DeleteMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeploymentGroup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, "start": 27, "type": "SHORT" }, @@ -8806,17 +8911,97 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mirroring_deployment_group" + }, + "description": "Sample for DeleteMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeploymentGroup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, { "end": 52, - "start": 49, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_sync.py" + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_group_sync.py" }, { "canonical": true, @@ -8826,19 +9011,19 @@ "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", "shortName": "MirroringAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "GetMirroringDeployment" + "shortName": "DeleteMirroringDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentRequest" + "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentRequest" }, { "name": "name", @@ -8857,22 +9042,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringDeployment", - "shortName": "get_mirroring_deployment" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mirroring_deployment" }, - "description": "Sample for GetMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_async.py", + "description": "Sample for DeleteMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeployment_async", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeployment_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -8887,17 +9072,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_async.py" + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_async.py" }, { "canonical": true, @@ -8906,19 +9091,19 @@ "fullName": "google.cloud.network_security_v1.MirroringClient", "shortName": "MirroringClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_deployment", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringDeployment", "service": { "fullName": "google.cloud.networksecurity.v1.Mirroring", "shortName": "Mirroring" }, - "shortName": "GetMirroringDeployment" + "shortName": "DeleteMirroringDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentRequest" + "type": "google.cloud.network_security_v1.types.DeleteMirroringDeploymentRequest" }, { "name": "name", @@ -8937,22 +9122,3724 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringDeployment", - "shortName": "get_mirroring_deployment" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mirroring_deployment" }, - "description": "Sample for GetMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_sync.py", + "description": "Sample for DeleteMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeployment_sync", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringDeployment_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mirroring_endpoint_group_association" + }, + "description": "Sample for DeleteMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroupAssociation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupAssociationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mirroring_endpoint_group_association" + }, + "description": "Sample for DeleteMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroupAssociation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.delete_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_mirroring_endpoint_group" + }, + "description": "Sample for DeleteMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.delete_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.DeleteMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "DeleteMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteMirroringEndpointGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_mirroring_endpoint_group" + }, + "description": "Sample for DeleteMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_DeleteMirroringEndpointGroup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_delete_mirroring_endpoint_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentGroupRequest" + }, + { + "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.network_security_v1.types.MirroringDeploymentGroup", + "shortName": "get_mirroring_deployment_group" + }, + "description": "Sample for GetMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeploymentGroup_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": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentGroupRequest" + }, + { + "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.network_security_v1.types.MirroringDeploymentGroup", + "shortName": "get_mirroring_deployment_group" + }, + "description": "Sample for GetMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeploymentGroup_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": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_deployment", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeployment", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentRequest" + }, + { + "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.network_security_v1.types.MirroringDeployment", + "shortName": "get_mirroring_deployment" + }, + "description": "Sample for GetMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeployment_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": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_deployment", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringDeployment", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringDeploymentRequest" + }, + { + "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.network_security_v1.types.MirroringDeployment", + "shortName": "get_mirroring_deployment" + }, + "description": "Sample for GetMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringDeployment_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": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupAssociationRequest" + }, + { + "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.network_security_v1.types.MirroringEndpointGroupAssociation", + "shortName": "get_mirroring_endpoint_group_association" + }, + "description": "Sample for GetMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroupAssociation_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": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupAssociationRequest" + }, + { + "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.network_security_v1.types.MirroringEndpointGroupAssociation", + "shortName": "get_mirroring_endpoint_group_association" + }, + "description": "Sample for GetMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroupAssociation_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": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupRequest" + }, + { + "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.network_security_v1.types.MirroringEndpointGroup", + "shortName": "get_mirroring_endpoint_group" + }, + "description": "Sample for GetMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroup_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": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "GetMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupRequest" + }, + { + "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.network_security_v1.types.MirroringEndpointGroup", + "shortName": "get_mirroring_endpoint_group" + }, + "description": "Sample for GetMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroup_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": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_deployment_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeploymentGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringDeploymentGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentGroupsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentGroupsAsyncPager", + "shortName": "list_mirroring_deployment_groups" + }, + "description": "Sample for ListMirroringDeploymentGroups", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeploymentGroups_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": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_deployment_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeploymentGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringDeploymentGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentGroupsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentGroupsPager", + "shortName": "list_mirroring_deployment_groups" + }, + "description": "Sample for ListMirroringDeploymentGroups", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeploymentGroups_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": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_deployments", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeployments", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentsAsyncPager", + "shortName": "list_mirroring_deployments" + }, + "description": "Sample for ListMirroringDeployments", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeployments_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": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_deployments", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeployments", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentsPager", + "shortName": "list_mirroring_deployments" + }, + "description": "Sample for ListMirroringDeployments", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeployments_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": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_endpoint_group_associations", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroupAssociations", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringEndpointGroupAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupAssociationsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupAssociationsAsyncPager", + "shortName": "list_mirroring_endpoint_group_associations" + }, + "description": "Sample for ListMirroringEndpointGroupAssociations", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroupAssociations_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": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_endpoint_group_associations", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroupAssociations", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringEndpointGroupAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupAssociationsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupAssociationsPager", + "shortName": "list_mirroring_endpoint_group_associations" + }, + "description": "Sample for ListMirroringEndpointGroupAssociations", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroupAssociations_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": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_endpoint_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringEndpointGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupsAsyncPager", + "shortName": "list_mirroring_endpoint_groups" + }, + "description": "Sample for ListMirroringEndpointGroups", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroups_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": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_endpoint_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "ListMirroringEndpointGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupsRequest" + }, + { + "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.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupsPager", + "shortName": "list_mirroring_endpoint_groups" + }, + "description": "Sample for ListMirroringEndpointGroups", + "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroups_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": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentGroupRequest" + }, + { + "name": "mirroring_deployment_group", + "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_mirroring_deployment_group" + }, + "description": "Sample for UpdateMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeploymentGroup_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_deployment_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeploymentGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringDeploymentGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentGroupRequest" + }, + { + "name": "mirroring_deployment_group", + "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_mirroring_deployment_group" + }, + "description": "Sample for UpdateMirroringDeploymentGroup", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeploymentGroup_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_deployment", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeployment", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentRequest" + }, + { + "name": "mirroring_deployment", + "type": "google.cloud.network_security_v1.types.MirroringDeployment" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_mirroring_deployment" + }, + "description": "Sample for UpdateMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeployment_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": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_deployment", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeployment", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentRequest" + }, + { + "name": "mirroring_deployment", + "type": "google.cloud.network_security_v1.types.MirroringDeployment" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_mirroring_deployment" + }, + "description": "Sample for UpdateMirroringDeployment", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeployment_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": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupAssociationRequest" + }, + { + "name": "mirroring_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_mirroring_endpoint_group_association" + }, + "description": "Sample for UpdateMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroupAssociation_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_endpoint_group_association", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroupAssociation", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringEndpointGroupAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupAssociationRequest" + }, + { + "name": "mirroring_endpoint_group_association", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_mirroring_endpoint_group_association" + }, + "description": "Sample for UpdateMirroringEndpointGroupAssociation", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroupAssociation_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", + "shortName": "MirroringAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupRequest" + }, + { + "name": "mirroring_endpoint_group", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "update_mirroring_endpoint_group" + }, + "description": "Sample for UpdateMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroup_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.MirroringClient", + "shortName": "MirroringClient" + }, + "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_endpoint_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.Mirroring", + "shortName": "Mirroring" + }, + "shortName": "UpdateMirroringEndpointGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupRequest" + }, + { + "name": "mirroring_endpoint_group", + "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + }, + { + "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.api_core.operation.Operation", + "shortName": "update_mirroring_endpoint_group" + }, + "description": "Sample for UpdateMirroringEndpointGroup", + "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroup_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authz_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthzPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthzPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthzPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authz_policy", + "type": "google.cloud.network_security_v1.types.AuthzPolicy" + }, + { + "name": "authz_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_authz_policy" + }, + "description": "Sample for CreateAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_create_authz_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthzPolicy_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authz_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authz_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthzPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthzPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthzPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authz_policy", + "type": "google.cloud.network_security_v1.types.AuthzPolicy" + }, + { + "name": "authz_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_authz_policy" + }, + "description": "Sample for CreateAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_create_authz_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthzPolicy_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authz_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_backend_authentication_config", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateBackendAuthenticationConfig", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateBackendAuthenticationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateBackendAuthenticationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backend_authentication_config", + "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + }, + { + "name": "backend_authentication_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_backend_authentication_config" + }, + "description": "Sample for CreateBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_create_backend_authentication_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateBackendAuthenticationConfig_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_backend_authentication_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_backend_authentication_config", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateBackendAuthenticationConfig", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateBackendAuthenticationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateBackendAuthenticationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backend_authentication_config", + "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + }, + { + "name": "backend_authentication_config_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_backend_authentication_config" + }, + "description": "Sample for CreateBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_create_backend_authentication_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateBackendAuthenticationConfig_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_backend_authentication_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_gateway_security_policy_rule", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicyRule", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateGatewaySecurityPolicyRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_security_policy_rule", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + }, + { + "name": "gateway_security_policy_rule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_gateway_security_policy_rule" + }, + "description": "Sample for CreateGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicyRule_async", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_gateway_security_policy_rule", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicyRule", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateGatewaySecurityPolicyRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRuleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_security_policy_rule", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + }, + { + "name": "gateway_security_policy_rule_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_gateway_security_policy_rule" + }, + "description": "Sample for CreateGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicyRule_sync", + "segments": [ + { + "end": 63, + "start": 27, + "type": "FULL" + }, + { + "end": 63, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 53, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 60, + "start": 54, + "type": "REQUEST_EXECUTION" + }, + { + "end": 64, + "start": 61, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_gateway_security_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateGatewaySecurityPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_security_policy", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + }, + { + "name": "gateway_security_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_gateway_security_policy" + }, + "description": "Sample for CreateGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_gateway_security_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateGatewaySecurityPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_security_policy", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + }, + { + "name": "gateway_security_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_gateway_security_policy" + }, + "description": "Sample for CreateGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_tls_inspection_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateTlsInspectionPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateTlsInspectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateTlsInspectionPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tls_inspection_policy", + "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + }, + { + "name": "tls_inspection_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_tls_inspection_policy" + }, + "description": "Sample for CreateTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateTlsInspectionPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_tls_inspection_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateTlsInspectionPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateTlsInspectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateTlsInspectionPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tls_inspection_policy", + "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + }, + { + "name": "tls_inspection_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_tls_inspection_policy" + }, + "description": "Sample for CreateTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateTlsInspectionPolicy_sync", "segments": [ { - "end": 51, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 61, "start": 27, "type": "SHORT" }, @@ -8962,47 +12849,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_deployment_sync.py" + "title": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateUrlList", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "GetMirroringEndpointGroupAssociation" + "shortName": "CreateUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateUrlListRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "url_list", + "type": "google.cloud.network_security_v1.types.UrlList" + }, + { + "name": "url_list_id", "type": "str" }, { @@ -9018,22 +12913,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation", - "shortName": "get_mirroring_endpoint_group_association" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_url_list" }, - "description": "Sample for GetMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_async.py", + "description": "Sample for CreateUrlList", + "file": "networksecurity_v1_generated_network_security_create_url_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateUrlList_async", "segments": [ { - "end": 51, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 61, "start": 27, "type": "SHORT" }, @@ -9043,46 +12938,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_network_security_create_url_list_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateUrlList", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "GetMirroringEndpointGroupAssociation" + "shortName": "CreateUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupAssociationRequest" + "type": "google.cloud.network_security_v1.types.CreateUrlListRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "url_list", + "type": "google.cloud.network_security_v1.types.UrlList" + }, + { + "name": "url_list_id", "type": "str" }, { @@ -9098,22 +13001,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation", - "shortName": "get_mirroring_endpoint_group_association" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_url_list" }, - "description": "Sample for GetMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_sync.py", + "description": "Sample for CreateUrlList", + "file": "networksecurity_v1_generated_network_security_create_url_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateUrlList_sync", "segments": [ { - "end": 51, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 61, "start": 27, "type": "SHORT" }, @@ -9123,44 +13026,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_network_security_create_url_list_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.get_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "GetMirroringEndpointGroup" + "shortName": "DeleteAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" }, { "name": "name", @@ -9179,22 +13082,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringEndpointGroup", - "shortName": "get_mirroring_endpoint_group" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_authorization_policy" }, - "description": "Sample for GetMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_async.py", + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9209,38 +13112,38 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_async.py" + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.get_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.GetMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "GetMirroringEndpointGroup" + "shortName": "DeleteAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetMirroringEndpointGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" }, { "name": "name", @@ -9259,22 +13162,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.MirroringEndpointGroup", - "shortName": "get_mirroring_endpoint_group" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_authorization_policy" }, - "description": "Sample for GetMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_sync.py", + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_GetMirroringEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9289,42 +13192,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_get_mirroring_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_deployment_groups", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeploymentGroups", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthzPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringDeploymentGroups" + "shortName": "DeleteAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteAuthzPolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9340,22 +13243,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentGroupsAsyncPager", - "shortName": "list_mirroring_deployment_groups" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_authz_policy" }, - "description": "Sample for ListMirroringDeploymentGroups", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_async.py", + "description": "Sample for DeleteAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authz_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeploymentGroups_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthzPolicy_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9370,41 +13273,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_async.py" + "title": "networksecurity_v1_generated_network_security_delete_authz_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_deployment_groups", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeploymentGroups", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthzPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringDeploymentGroups" + "shortName": "DeleteAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteAuthzPolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9420,22 +13323,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentGroupsPager", - "shortName": "list_mirroring_deployment_groups" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_authz_policy" }, - "description": "Sample for ListMirroringDeploymentGroups", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_sync.py", + "description": "Sample for DeleteAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authz_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeploymentGroups_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthzPolicy_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9450,42 +13353,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_deployment_groups_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_authz_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_deployments", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeployments", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteBackendAuthenticationConfig", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringDeployments" + "shortName": "DeleteBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentsRequest" + "type": "google.cloud.network_security_v1.types.DeleteBackendAuthenticationConfigRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9501,22 +13404,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentsAsyncPager", - "shortName": "list_mirroring_deployments" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backend_authentication_config" }, - "description": "Sample for ListMirroringDeployments", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_async.py", + "description": "Sample for DeleteBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeployments_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteBackendAuthenticationConfig_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9531,41 +13434,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_async.py" + "title": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_deployments", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringDeployments", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteBackendAuthenticationConfig", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringDeployments" + "shortName": "DeleteBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringDeploymentsRequest" + "type": "google.cloud.network_security_v1.types.DeleteBackendAuthenticationConfigRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9581,22 +13484,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringDeploymentsPager", - "shortName": "list_mirroring_deployments" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backend_authentication_config" }, - "description": "Sample for ListMirroringDeployments", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_sync.py", + "description": "Sample for DeleteBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringDeployments_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteBackendAuthenticationConfig_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9611,42 +13514,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_deployments_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_endpoint_group_associations", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroupAssociations", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringEndpointGroupAssociations" + "shortName": "DeleteClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupAssociationsRequest" + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9662,22 +13565,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupAssociationsAsyncPager", - "shortName": "list_mirroring_endpoint_group_associations" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_client_tls_policy" }, - "description": "Sample for ListMirroringEndpointGroupAssociations", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_async.py", + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroupAssociations_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9692,41 +13595,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_async.py" + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_endpoint_group_associations", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroupAssociations", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringEndpointGroupAssociations" + "shortName": "DeleteClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupAssociationsRequest" + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9742,22 +13645,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupAssociationsPager", - "shortName": "list_mirroring_endpoint_group_associations" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_client_tls_policy" }, - "description": "Sample for ListMirroringEndpointGroupAssociations", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_sync.py", + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroupAssociations_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9772,42 +13675,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_group_associations_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.list_mirroring_endpoint_groups", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroups", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicyRule", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringEndpointGroups" + "shortName": "DeleteGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRuleRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9823,22 +13726,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupsAsyncPager", - "shortName": "list_mirroring_endpoint_groups" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_gateway_security_policy_rule" }, - "description": "Sample for ListMirroringEndpointGroups", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_async.py", + "description": "Sample for DeleteGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroups_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicyRule_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9853,41 +13756,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_async.py" + "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.list_mirroring_endpoint_groups", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.ListMirroringEndpointGroups", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicyRule", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "ListMirroringEndpointGroups" + "shortName": "DeleteGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListMirroringEndpointGroupsRequest" + "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRuleRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -9903,22 +13806,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.mirroring.pagers.ListMirroringEndpointGroupsPager", - "shortName": "list_mirroring_endpoint_groups" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_gateway_security_policy_rule" }, - "description": "Sample for ListMirroringEndpointGroups", - "file": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_sync.py", + "description": "Sample for DeleteGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_ListMirroringEndpointGroups_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicyRule_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9933,47 +13836,43 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_list_mirroring_endpoint_groups_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringDeploymentGroup" + "shortName": "DeleteGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentGroupRequest" - }, - { - "name": "mirroring_deployment_group", - "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -9989,21 +13888,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_mirroring_deployment_group" + "shortName": "delete_gateway_security_policy" }, - "description": "Sample for UpdateMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_async.py", + "description": "Sample for DeleteGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeploymentGroup_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicy_async", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10013,51 +13912,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_async.py" + "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_deployment_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeploymentGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringDeploymentGroup" + "shortName": "DeleteGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentGroupRequest" - }, - { - "name": "mirroring_deployment_group", - "type": "google.cloud.network_security_v1.types.MirroringDeploymentGroup" + "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10073,21 +13968,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_mirroring_deployment_group" + "shortName": "delete_gateway_security_policy" }, - "description": "Sample for UpdateMirroringDeploymentGroup", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_sync.py", + "description": "Sample for DeleteGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeploymentGroup_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicy_sync", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10097,52 +13992,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_group_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringDeployment" + "shortName": "DeleteServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentRequest" - }, - { - "name": "mirroring_deployment", - "type": "google.cloud.network_security_v1.types.MirroringDeployment" + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10158,21 +14049,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_mirroring_deployment" + "shortName": "delete_server_tls_policy" }, - "description": "Sample for UpdateMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_async.py", + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeployment_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", "segments": [ { - "end": 59, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10182,51 +14073,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_async.py" + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_deployment", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringDeployment", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringDeployment" + "shortName": "DeleteServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringDeploymentRequest" - }, - { - "name": "mirroring_deployment", - "type": "google.cloud.network_security_v1.types.MirroringDeployment" + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10242,21 +14129,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_mirroring_deployment" + "shortName": "delete_server_tls_policy" }, - "description": "Sample for UpdateMirroringDeployment", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_sync.py", + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringDeployment_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", "segments": [ { - "end": 59, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10266,52 +14153,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_deployment_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteTlsInspectionPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringEndpointGroupAssociation" + "shortName": "DeleteTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupAssociationRequest" - }, - { - "name": "mirroring_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + "type": "google.cloud.network_security_v1.types.DeleteTlsInspectionPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10327,21 +14210,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_mirroring_endpoint_group_association" + "shortName": "delete_tls_inspection_policy" }, - "description": "Sample for UpdateMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_async.py", + "description": "Sample for DeleteTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroupAssociation_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteTlsInspectionPolicy_async", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10351,51 +14234,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_async.py" + "title": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_endpoint_group_association", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroupAssociation", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteTlsInspectionPolicy", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringEndpointGroupAssociation" + "shortName": "DeleteTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupAssociationRequest" - }, - { - "name": "mirroring_endpoint_group_association", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroupAssociation" + "type": "google.cloud.network_security_v1.types.DeleteTlsInspectionPolicyRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10411,21 +14290,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_mirroring_endpoint_group_association" + "shortName": "delete_tls_inspection_policy" }, - "description": "Sample for UpdateMirroringEndpointGroupAssociation", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_sync.py", + "description": "Sample for DeleteTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroupAssociation_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteTlsInspectionPolicy_sync", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10435,52 +14314,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_association_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient", - "shortName": "MirroringAsyncClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.MirroringAsyncClient.update_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteUrlList", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringEndpointGroup" + "shortName": "DeleteUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupRequest" - }, - { - "name": "mirroring_endpoint_group", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + "type": "google.cloud.network_security_v1.types.DeleteUrlListRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10496,21 +14371,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_mirroring_endpoint_group" + "shortName": "delete_url_list" }, - "description": "Sample for UpdateMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_async.py", + "description": "Sample for DeleteUrlList", + "file": "networksecurity_v1_generated_network_security_delete_url_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroup_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteUrlList_async", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10520,51 +14395,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_async.py" + "title": "networksecurity_v1_generated_network_security_delete_url_list_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.MirroringClient", - "shortName": "MirroringClient" + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.MirroringClient.update_mirroring_endpoint_group", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.Mirroring.UpdateMirroringEndpointGroup", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteUrlList", "service": { - "fullName": "google.cloud.networksecurity.v1.Mirroring", - "shortName": "Mirroring" + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" }, - "shortName": "UpdateMirroringEndpointGroup" + "shortName": "DeleteUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateMirroringEndpointGroupRequest" - }, - { - "name": "mirroring_endpoint_group", - "type": "google.cloud.network_security_v1.types.MirroringEndpointGroup" + "type": "google.cloud.network_security_v1.types.DeleteUrlListRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -10580,21 +14451,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_mirroring_endpoint_group" + "shortName": "delete_url_list" }, - "description": "Sample for UpdateMirroringEndpointGroup", - "file": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_sync.py", + "description": "Sample for DeleteUrlList", + "file": "networksecurity_v1_generated_network_security_delete_url_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_Mirroring_UpdateMirroringEndpointGroup_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteUrlList_sync", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10604,22 +14475,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_mirroring_update_mirroring_endpoint_group_sync.py" + "title": "networksecurity_v1_generated_network_security_delete_url_list_sync.py" }, { "canonical": true, @@ -10629,30 +14500,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateAuthorizationPolicy" + "shortName": "GetAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" }, { - "name": "authorization_policy_id", + "name": "name", "type": "str" }, { @@ -10668,22 +14531,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_authorization_policy" + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10693,22 +14556,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" }, { "canonical": true, @@ -10717,30 +14580,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateAuthorizationPolicy" + "shortName": "GetAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" }, { - "name": "authorization_policy_id", + "name": "name", "type": "str" }, { @@ -10756,22 +14611,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_authorization_policy" + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10781,22 +14636,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" }, { "canonical": true, @@ -10806,30 +14661,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthzPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateAuthzPolicy" + "shortName": "GetAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthzPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authz_policy", - "type": "google.cloud.network_security_v1.types.AuthzPolicy" + "type": "google.cloud.network_security_v1.types.GetAuthzPolicyRequest" }, { - "name": "authz_policy_id", + "name": "name", "type": "str" }, { @@ -10845,22 +14692,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_authz_policy" + "resultType": "google.cloud.network_security_v1.types.AuthzPolicy", + "shortName": "get_authz_policy" }, - "description": "Sample for CreateAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_create_authz_policy_async.py", + "description": "Sample for GetAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_get_authz_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthzPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthzPolicy_async", "segments": [ { - "end": 62, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10870,22 +14717,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authz_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_authz_policy_async.py" }, { "canonical": true, @@ -10894,30 +14741,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthzPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateAuthzPolicy" + "shortName": "GetAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthzPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authz_policy", - "type": "google.cloud.network_security_v1.types.AuthzPolicy" + "type": "google.cloud.network_security_v1.types.GetAuthzPolicyRequest" }, { - "name": "authz_policy_id", + "name": "name", "type": "str" }, { @@ -10933,22 +14772,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_authz_policy" + "resultType": "google.cloud.network_security_v1.types.AuthzPolicy", + "shortName": "get_authz_policy" }, - "description": "Sample for CreateAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_create_authz_policy_sync.py", + "description": "Sample for GetAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_get_authz_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthzPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthzPolicy_sync", "segments": [ { - "end": 62, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10958,22 +14797,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authz_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_authz_policy_sync.py" }, { "canonical": true, @@ -10983,30 +14822,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetBackendAuthenticationConfig", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateBackendAuthenticationConfig" + "shortName": "GetBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateBackendAuthenticationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "backend_authentication_config", - "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + "type": "google.cloud.network_security_v1.types.GetBackendAuthenticationConfigRequest" }, { - "name": "backend_authentication_config_id", + "name": "name", "type": "str" }, { @@ -11022,22 +14853,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_backend_authentication_config" + "resultType": "google.cloud.network_security_v1.types.BackendAuthenticationConfig", + "shortName": "get_backend_authentication_config" }, - "description": "Sample for CreateBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_create_backend_authentication_config_async.py", + "description": "Sample for GetBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_get_backend_authentication_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateBackendAuthenticationConfig_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetBackendAuthenticationConfig_async", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11047,22 +14878,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_backend_authentication_config_async.py" + "title": "networksecurity_v1_generated_network_security_get_backend_authentication_config_async.py" }, { "canonical": true, @@ -11071,30 +14902,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetBackendAuthenticationConfig", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateBackendAuthenticationConfig" + "shortName": "GetBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateBackendAuthenticationConfigRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "backend_authentication_config", - "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + "type": "google.cloud.network_security_v1.types.GetBackendAuthenticationConfigRequest" }, { - "name": "backend_authentication_config_id", + "name": "name", "type": "str" }, { @@ -11110,22 +14933,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_backend_authentication_config" + "resultType": "google.cloud.network_security_v1.types.BackendAuthenticationConfig", + "shortName": "get_backend_authentication_config" }, - "description": "Sample for CreateBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_create_backend_authentication_config_sync.py", + "description": "Sample for GetBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_get_backend_authentication_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateBackendAuthenticationConfig_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetBackendAuthenticationConfig_sync", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11135,22 +14958,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_backend_authentication_config_sync.py" + "title": "networksecurity_v1_generated_network_security_get_backend_authentication_config_sync.py" }, { "canonical": true, @@ -11160,30 +14983,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateClientTlsPolicy" + "shortName": "GetClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" }, { - "name": "client_tls_policy_id", + "name": "name", "type": "str" }, { @@ -11199,22 +15014,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_client_tls_policy" + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11224,22 +15039,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" }, { "canonical": true, @@ -11248,30 +15063,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateClientTlsPolicy" + "shortName": "GetClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" }, { - "name": "client_tls_policy_id", + "name": "name", "type": "str" }, { @@ -11287,22 +15094,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_client_tls_policy" + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11312,22 +15119,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" }, { "canonical": true, @@ -11337,30 +15144,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicyRule", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateGatewaySecurityPolicyRule" + "shortName": "GetGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_security_policy_rule", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRuleRequest" }, { - "name": "gateway_security_policy_rule_id", + "name": "name", "type": "str" }, { @@ -11376,22 +15175,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule", + "shortName": "get_gateway_security_policy_rule" }, - "description": "Sample for CreateGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_async.py", + "description": "Sample for GetGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicyRule_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicyRule_async", "segments": [ { - "end": 63, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11401,22 +15200,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_async.py" + "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_async.py" }, { "canonical": true, @@ -11425,30 +15224,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicyRule", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateGatewaySecurityPolicyRule" + "shortName": "GetGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRuleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_security_policy_rule", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRuleRequest" }, { - "name": "gateway_security_policy_rule_id", + "name": "name", "type": "str" }, { @@ -11464,22 +15255,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule", + "shortName": "get_gateway_security_policy_rule" }, - "description": "Sample for CreateGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_sync.py", + "description": "Sample for GetGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicyRule_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicyRule_sync", "segments": [ { - "end": 63, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 63, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11489,22 +15280,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 53, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 60, - "start": 54, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 64, - "start": 61, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_rule_sync.py" + "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_sync.py" }, { "canonical": true, @@ -11514,30 +15305,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateGatewaySecurityPolicy" + "shortName": "GetGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_security_policy", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRequest" }, { - "name": "gateway_security_policy_id", + "name": "name", "type": "str" }, { @@ -11553,22 +15336,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicy", + "shortName": "get_gateway_security_policy" }, - "description": "Sample for CreateGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_async.py", + "description": "Sample for GetGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicy_async", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11578,22 +15361,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_async.py" }, { "canonical": true, @@ -11602,30 +15385,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateGatewaySecurityPolicy" + "shortName": "GetGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateGatewaySecurityPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_security_policy", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRequest" }, { - "name": "gateway_security_policy_id", + "name": "name", "type": "str" }, { @@ -11641,22 +15416,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicy", + "shortName": "get_gateway_security_policy" }, - "description": "Sample for CreateGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_create_gateway_security_policy_sync.py", + "description": "Sample for GetGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateGatewaySecurityPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicy_sync", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11666,22 +15441,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_gateway_security_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_sync.py" }, { "canonical": true, @@ -11691,30 +15466,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateServerTlsPolicy" + "shortName": "GetServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" }, { - "name": "server_tls_policy_id", + "name": "name", "type": "str" }, { @@ -11730,22 +15497,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_server_tls_policy" + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11755,22 +15522,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" }, { "canonical": true, @@ -11779,30 +15546,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateServerTlsPolicy" + "shortName": "GetServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" }, { - "name": "server_tls_policy_id", + "name": "name", "type": "str" }, { @@ -11818,22 +15577,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_server_tls_policy" + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", "segments": [ { - "end": 60, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11843,22 +15602,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" }, { "canonical": true, @@ -11868,30 +15627,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetTlsInspectionPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateTlsInspectionPolicy" + "shortName": "GetTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateTlsInspectionPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tls_inspection_policy", - "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + "type": "google.cloud.network_security_v1.types.GetTlsInspectionPolicyRequest" }, { - "name": "tls_inspection_policy_id", + "name": "name", "type": "str" }, { @@ -11907,22 +15658,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.types.TlsInspectionPolicy", + "shortName": "get_tls_inspection_policy" }, - "description": "Sample for CreateTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_async.py", + "description": "Sample for GetTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateTlsInspectionPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetTlsInspectionPolicy_async", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11932,22 +15683,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_async.py" + "title": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_async.py" }, { "canonical": true, @@ -11956,30 +15707,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetTlsInspectionPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateTlsInspectionPolicy" + "shortName": "GetTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateTlsInspectionPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "tls_inspection_policy", - "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + "type": "google.cloud.network_security_v1.types.GetTlsInspectionPolicyRequest" }, { - "name": "tls_inspection_policy_id", + "name": "name", "type": "str" }, { @@ -11995,22 +15738,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.types.TlsInspectionPolicy", + "shortName": "get_tls_inspection_policy" }, - "description": "Sample for CreateTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_sync.py", + "description": "Sample for GetTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateTlsInspectionPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetTlsInspectionPolicy_sync", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12020,22 +15763,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_tls_inspection_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_sync.py" }, { "canonical": true, @@ -12045,30 +15788,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetUrlList", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateUrlList" + "shortName": "GetUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateUrlListRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "url_list", - "type": "google.cloud.network_security_v1.types.UrlList" + "type": "google.cloud.network_security_v1.types.GetUrlListRequest" }, { - "name": "url_list_id", + "name": "name", "type": "str" }, { @@ -12084,22 +15819,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_url_list" + "resultType": "google.cloud.network_security_v1.types.UrlList", + "shortName": "get_url_list" }, - "description": "Sample for CreateUrlList", - "file": "networksecurity_v1_generated_network_security_create_url_list_async.py", + "description": "Sample for GetUrlList", + "file": "networksecurity_v1_generated_network_security_get_url_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateUrlList_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetUrlList_async", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12109,22 +15844,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_url_list_async.py" + "title": "networksecurity_v1_generated_network_security_get_url_list_async.py" }, { "canonical": true, @@ -12133,30 +15868,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetUrlList", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "CreateUrlList" + "shortName": "GetUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateUrlListRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "url_list", - "type": "google.cloud.network_security_v1.types.UrlList" + "type": "google.cloud.network_security_v1.types.GetUrlListRequest" }, { - "name": "url_list_id", + "name": "name", "type": "str" }, { @@ -12172,22 +15899,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_url_list" + "resultType": "google.cloud.network_security_v1.types.UrlList", + "shortName": "get_url_list" }, - "description": "Sample for CreateUrlList", - "file": "networksecurity_v1_generated_network_security_create_url_list_sync.py", + "description": "Sample for GetUrlList", + "file": "networksecurity_v1_generated_network_security_get_url_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateUrlList_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetUrlList_sync", "segments": [ { - "end": 61, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 51, "start": 27, "type": "SHORT" }, @@ -12197,22 +15924,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_url_list_sync.py" + "title": "networksecurity_v1_generated_network_security_get_url_list_sync.py" }, { "canonical": true, @@ -12222,22 +15949,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteAuthorizationPolicy" + "shortName": "ListAuthorizationPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12253,22 +15980,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", + "shortName": "list_authorization_policies" }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12283,17 +16010,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" }, { "canonical": true, @@ -12302,22 +16029,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteAuthorizationPolicy" + "shortName": "ListAuthorizationPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12333,22 +16060,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", + "shortName": "list_authorization_policies" }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12363,17 +16090,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" }, { "canonical": true, @@ -12383,22 +16110,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authz_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthzPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteAuthzPolicy" + "shortName": "ListAuthzPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAuthzPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12414,22 +16141,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_authz_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthzPoliciesAsyncPager", + "shortName": "list_authz_policies" }, - "description": "Sample for DeleteAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authz_policy_async.py", + "description": "Sample for ListAuthzPolicies", + "file": "networksecurity_v1_generated_network_security_list_authz_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthzPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthzPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12444,17 +16171,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authz_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_authz_policies_async.py" }, { "canonical": true, @@ -12463,22 +16190,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authz_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthzPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteAuthzPolicy" + "shortName": "ListAuthzPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAuthzPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12494,22 +16221,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_authz_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthzPoliciesPager", + "shortName": "list_authz_policies" }, - "description": "Sample for DeleteAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authz_policy_sync.py", + "description": "Sample for ListAuthzPolicies", + "file": "networksecurity_v1_generated_network_security_list_authz_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthzPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthzPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12524,17 +16251,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authz_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_authz_policies_sync.py" }, { "canonical": true, @@ -12544,22 +16271,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_backend_authentication_configs", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListBackendAuthenticationConfigs", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteBackendAuthenticationConfig" + "shortName": "ListBackendAuthenticationConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteBackendAuthenticationConfigRequest" + "type": "google.cloud.network_security_v1.types.ListBackendAuthenticationConfigsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12575,22 +16302,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backend_authentication_config" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListBackendAuthenticationConfigsAsyncPager", + "shortName": "list_backend_authentication_configs" }, - "description": "Sample for DeleteBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_async.py", + "description": "Sample for ListBackendAuthenticationConfigs", + "file": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteBackendAuthenticationConfig_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListBackendAuthenticationConfigs_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12605,17 +16332,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_async.py" + "title": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_async.py" }, { "canonical": true, @@ -12624,22 +16351,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_backend_authentication_configs", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListBackendAuthenticationConfigs", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteBackendAuthenticationConfig" + "shortName": "ListBackendAuthenticationConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteBackendAuthenticationConfigRequest" + "type": "google.cloud.network_security_v1.types.ListBackendAuthenticationConfigsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12655,22 +16382,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backend_authentication_config" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListBackendAuthenticationConfigsPager", + "shortName": "list_backend_authentication_configs" }, - "description": "Sample for DeleteBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_sync.py", + "description": "Sample for ListBackendAuthenticationConfigs", + "file": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteBackendAuthenticationConfig_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListBackendAuthenticationConfigs_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12685,17 +16412,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_backend_authentication_config_sync.py" + "title": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_sync.py" }, { "canonical": true, @@ -12705,22 +16432,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteClientTlsPolicy" + "shortName": "ListClientTlsPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12736,22 +16463,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_client_tls_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", + "shortName": "list_client_tls_policies" }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12766,17 +16493,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" }, { "canonical": true, @@ -12785,22 +16512,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteClientTlsPolicy" + "shortName": "ListClientTlsPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12816,22 +16543,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_client_tls_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", + "shortName": "list_client_tls_policies" }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12846,17 +16573,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" }, { "canonical": true, @@ -12866,22 +16593,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_gateway_security_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteGatewaySecurityPolicyRule" + "shortName": "ListGatewaySecurityPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRuleRequest" + "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12897,22 +16624,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPoliciesAsyncPager", + "shortName": "list_gateway_security_policies" }, - "description": "Sample for DeleteGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_async.py", + "description": "Sample for ListGatewaySecurityPolicies", + "file": "networksecurity_v1_generated_network_security_list_gateway_security_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicyRule_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12927,17 +16654,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_async.py" + "title": "networksecurity_v1_generated_network_security_list_gateway_security_policies_async.py" }, { "canonical": true, @@ -12946,22 +16673,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_gateway_security_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteGatewaySecurityPolicyRule" + "shortName": "ListGatewaySecurityPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRuleRequest" + "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -12977,22 +16704,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPoliciesPager", + "shortName": "list_gateway_security_policies" }, - "description": "Sample for DeleteGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_sync.py", + "description": "Sample for ListGatewaySecurityPolicies", + "file": "networksecurity_v1_generated_network_security_list_gateway_security_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicyRule_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13007,17 +16734,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_rule_sync.py" + "title": "networksecurity_v1_generated_network_security_list_gateway_security_policies_sync.py" }, { "canonical": true, @@ -13027,22 +16754,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_gateway_security_policy_rules", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicyRules", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteGatewaySecurityPolicy" + "shortName": "ListGatewaySecurityPolicyRules" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPolicyRulesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13058,22 +16785,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPolicyRulesAsyncPager", + "shortName": "list_gateway_security_policy_rules" }, - "description": "Sample for DeleteGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_async.py", + "description": "Sample for ListGatewaySecurityPolicyRules", + "file": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicyRules_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13088,17 +16815,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_async.py" }, { "canonical": true, @@ -13107,22 +16834,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_gateway_security_policy_rules", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicyRules", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteGatewaySecurityPolicy" + "shortName": "ListGatewaySecurityPolicyRules" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteGatewaySecurityPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPolicyRulesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13138,22 +16865,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPolicyRulesPager", + "shortName": "list_gateway_security_policy_rules" }, - "description": "Sample for DeleteGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_sync.py", + "description": "Sample for ListGatewaySecurityPolicyRules", + "file": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteGatewaySecurityPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicyRules_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13168,17 +16895,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_gateway_security_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_sync.py" }, { "canonical": true, @@ -13188,22 +16915,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteServerTlsPolicy" + "shortName": "ListServerTlsPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13219,22 +16946,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", + "shortName": "list_server_tls_policies" }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13249,17 +16976,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" }, { "canonical": true, @@ -13268,22 +16995,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteServerTlsPolicy" + "shortName": "ListServerTlsPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13299,22 +17026,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", + "shortName": "list_server_tls_policies" }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13329,17 +17056,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" }, { "canonical": true, @@ -13349,22 +17076,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_tls_inspection_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListTlsInspectionPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteTlsInspectionPolicy" + "shortName": "ListTlsInspectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteTlsInspectionPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListTlsInspectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13380,22 +17107,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListTlsInspectionPoliciesAsyncPager", + "shortName": "list_tls_inspection_policies" }, - "description": "Sample for DeleteTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_async.py", + "description": "Sample for ListTlsInspectionPolicies", + "file": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteTlsInspectionPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListTlsInspectionPolicies_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13410,17 +17137,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_async.py" + "title": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_async.py" }, { "canonical": true, @@ -13429,22 +17156,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_tls_inspection_policies", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListTlsInspectionPolicies", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteTlsInspectionPolicy" + "shortName": "ListTlsInspectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteTlsInspectionPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListTlsInspectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13460,22 +17187,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListTlsInspectionPoliciesPager", + "shortName": "list_tls_inspection_policies" }, - "description": "Sample for DeleteTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_sync.py", + "description": "Sample for ListTlsInspectionPolicies", + "file": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteTlsInspectionPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListTlsInspectionPolicies_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13490,17 +17217,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_tls_inspection_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_sync.py" }, { "canonical": true, @@ -13510,22 +17237,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_url_lists", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListUrlLists", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteUrlList" + "shortName": "ListUrlLists" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteUrlListRequest" + "type": "google.cloud.network_security_v1.types.ListUrlListsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13541,22 +17268,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_url_list" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListUrlListsAsyncPager", + "shortName": "list_url_lists" }, - "description": "Sample for DeleteUrlList", - "file": "networksecurity_v1_generated_network_security_delete_url_list_async.py", + "description": "Sample for ListUrlLists", + "file": "networksecurity_v1_generated_network_security_list_url_lists_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteUrlList_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListUrlLists_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13571,17 +17298,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_url_list_async.py" + "title": "networksecurity_v1_generated_network_security_list_url_lists_async.py" }, { "canonical": true, @@ -13590,22 +17317,22 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_url_lists", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListUrlLists", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "DeleteUrlList" + "shortName": "ListUrlLists" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteUrlListRequest" + "type": "google.cloud.network_security_v1.types.ListUrlListsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -13621,22 +17348,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_url_list" + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListUrlListsPager", + "shortName": "list_url_lists" }, - "description": "Sample for DeleteUrlList", - "file": "networksecurity_v1_generated_network_security_delete_url_list_sync.py", + "description": "Sample for ListUrlLists", + "file": "networksecurity_v1_generated_network_security_list_url_lists_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteUrlList_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListUrlLists_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13651,17 +17378,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_url_list_sync.py" + "title": "networksecurity_v1_generated_network_security_list_url_lists_sync.py" }, { "canonical": true, @@ -13671,23 +17398,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetAuthorizationPolicy" + "shortName": "UpdateAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13702,22 +17433,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_authorization_policy" }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -13727,22 +17458,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" }, { "canonical": true, @@ -13751,23 +17482,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetAuthorizationPolicy" + "shortName": "UpdateAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13782,22 +17517,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_authorization_policy" }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -13807,22 +17542,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" }, { "canonical": true, @@ -13832,23 +17567,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthzPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetAuthzPolicy" + "shortName": "UpdateAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAuthzPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "authz_policy", + "type": "google.cloud.network_security_v1.types.AuthzPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13863,22 +17602,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthzPolicy", - "shortName": "get_authz_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_authz_policy" }, - "description": "Sample for GetAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_get_authz_policy_async.py", + "description": "Sample for UpdateAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_update_authz_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthzPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthzPolicy_async", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -13888,22 +17627,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authz_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_authz_policy_async.py" }, { "canonical": true, @@ -13912,23 +17651,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authz_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authz_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthzPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetAuthzPolicy" + "shortName": "UpdateAuthzPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAuthzPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "authz_policy", + "type": "google.cloud.network_security_v1.types.AuthzPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13943,22 +17686,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthzPolicy", - "shortName": "get_authz_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_authz_policy" }, - "description": "Sample for GetAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_get_authz_policy_sync.py", + "description": "Sample for UpdateAuthzPolicy", + "file": "networksecurity_v1_generated_network_security_update_authz_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthzPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthzPolicy_sync", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -13968,22 +17711,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authz_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_authz_policy_sync.py" }, { "canonical": true, @@ -13993,23 +17736,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateBackendAuthenticationConfig", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetBackendAuthenticationConfig" + "shortName": "UpdateBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetBackendAuthenticationConfigRequest" + "type": "google.cloud.network_security_v1.types.UpdateBackendAuthenticationConfigRequest" }, { - "name": "name", - "type": "str" + "name": "backend_authentication_config", + "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14024,22 +17771,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.BackendAuthenticationConfig", - "shortName": "get_backend_authentication_config" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_backend_authentication_config" }, - "description": "Sample for GetBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_get_backend_authentication_config_async.py", + "description": "Sample for UpdateBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_update_backend_authentication_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetBackendAuthenticationConfig_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateBackendAuthenticationConfig_async", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14049,22 +17796,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_backend_authentication_config_async.py" + "title": "networksecurity_v1_generated_network_security_update_backend_authentication_config_async.py" }, { "canonical": true, @@ -14073,23 +17820,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_backend_authentication_config", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateBackendAuthenticationConfig", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetBackendAuthenticationConfig" + "shortName": "UpdateBackendAuthenticationConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetBackendAuthenticationConfigRequest" + "type": "google.cloud.network_security_v1.types.UpdateBackendAuthenticationConfigRequest" }, { - "name": "name", - "type": "str" + "name": "backend_authentication_config", + "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14104,22 +17855,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.BackendAuthenticationConfig", - "shortName": "get_backend_authentication_config" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_backend_authentication_config" }, - "description": "Sample for GetBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_get_backend_authentication_config_sync.py", + "description": "Sample for UpdateBackendAuthenticationConfig", + "file": "networksecurity_v1_generated_network_security_update_backend_authentication_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetBackendAuthenticationConfig_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateBackendAuthenticationConfig_sync", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14129,22 +17880,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_backend_authentication_config_sync.py" + "title": "networksecurity_v1_generated_network_security_update_backend_authentication_config_sync.py" }, { "canonical": true, @@ -14154,23 +17905,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetClientTlsPolicy" + "shortName": "UpdateClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14185,22 +17940,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_client_tls_policy" }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14210,22 +17965,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" }, { "canonical": true, @@ -14234,23 +17989,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetClientTlsPolicy" + "shortName": "UpdateClientTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14265,22 +18024,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_client_tls_policy" }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14290,22 +18049,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" }, { "canonical": true, @@ -14315,23 +18074,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicyRule", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetGatewaySecurityPolicyRule" + "shortName": "UpdateGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRuleRequest" + "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRuleRequest" }, { - "name": "name", - "type": "str" + "name": "gateway_security_policy_rule", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14346,22 +18109,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule", - "shortName": "get_gateway_security_policy_rule" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_gateway_security_policy_rule" }, - "description": "Sample for GetGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_async.py", + "description": "Sample for UpdateGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicyRule_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicyRule_async", "segments": [ { - "end": 51, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 62, "start": 27, "type": "SHORT" }, @@ -14371,22 +18134,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_async.py" + "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_async.py" }, { "canonical": true, @@ -14395,23 +18158,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_gateway_security_policy_rule", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicyRule", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetGatewaySecurityPolicyRule" + "shortName": "UpdateGatewaySecurityPolicyRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRuleRequest" + "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRuleRequest" }, { - "name": "name", - "type": "str" + "name": "gateway_security_policy_rule", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14426,22 +18193,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule", - "shortName": "get_gateway_security_policy_rule" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_gateway_security_policy_rule" }, - "description": "Sample for GetGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_sync.py", + "description": "Sample for UpdateGatewaySecurityPolicyRule", + "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicyRule_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicyRule_sync", "segments": [ { - "end": 51, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 62, "start": 27, "type": "SHORT" }, @@ -14451,22 +18218,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_rule_sync.py" + "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_sync.py" }, { "canonical": true, @@ -14476,23 +18243,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetGatewaySecurityPolicy" + "shortName": "UpdateGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "gateway_security_policy", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14507,22 +18278,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicy", - "shortName": "get_gateway_security_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_gateway_security_policy" }, - "description": "Sample for GetGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_async.py", + "description": "Sample for UpdateGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicy_async", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14532,22 +18303,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_async.py" }, { "canonical": true, @@ -14556,23 +18327,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_gateway_security_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetGatewaySecurityPolicy" + "shortName": "UpdateGatewaySecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetGatewaySecurityPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "gateway_security_policy", + "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14587,22 +18362,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.GatewaySecurityPolicy", - "shortName": "get_gateway_security_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_gateway_security_policy" }, - "description": "Sample for GetGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_get_gateway_security_policy_sync.py", + "description": "Sample for UpdateGatewaySecurityPolicy", + "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetGatewaySecurityPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicy_sync", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14612,22 +18387,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_gateway_security_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_sync.py" }, { "canonical": true, @@ -14637,23 +18412,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetServerTlsPolicy" + "shortName": "UpdateServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14668,22 +18447,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_server_tls_policy" }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14693,22 +18472,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" }, { "canonical": true, @@ -14717,23 +18496,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetServerTlsPolicy" + "shortName": "UpdateServerTlsPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14748,22 +18531,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_server_tls_policy" }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14773,22 +18556,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" }, { "canonical": true, @@ -14798,23 +18581,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateTlsInspectionPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetTlsInspectionPolicy" + "shortName": "UpdateTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetTlsInspectionPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateTlsInspectionPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "tls_inspection_policy", + "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14829,22 +18616,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.TlsInspectionPolicy", - "shortName": "get_tls_inspection_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_tls_inspection_policy" }, - "description": "Sample for GetTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_async.py", + "description": "Sample for UpdateTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetTlsInspectionPolicy_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateTlsInspectionPolicy_async", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -14854,22 +18641,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_async.py" + "title": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_async.py" }, { "canonical": true, @@ -14878,23 +18665,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_tls_inspection_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateTlsInspectionPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetTlsInspectionPolicy" + "shortName": "UpdateTlsInspectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetTlsInspectionPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateTlsInspectionPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "tls_inspection_policy", + "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14909,22 +18700,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.TlsInspectionPolicy", - "shortName": "get_tls_inspection_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_tls_inspection_policy" }, - "description": "Sample for GetTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_sync.py", + "description": "Sample for UpdateTlsInspectionPolicy", + "file": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetTlsInspectionPolicy_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateTlsInspectionPolicy_sync", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -14934,22 +18725,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_tls_inspection_policy_sync.py" + "title": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_sync.py" }, { "canonical": true, @@ -14959,23 +18750,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateUrlList", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetUrlList" + "shortName": "UpdateUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetUrlListRequest" + "type": "google.cloud.network_security_v1.types.UpdateUrlListRequest" }, { - "name": "name", - "type": "str" + "name": "url_list", + "type": "google.cloud.network_security_v1.types.UrlList" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14990,22 +18785,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.UrlList", - "shortName": "get_url_list" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_url_list" }, - "description": "Sample for GetUrlList", - "file": "networksecurity_v1_generated_network_security_get_url_list_async.py", + "description": "Sample for UpdateUrlList", + "file": "networksecurity_v1_generated_network_security_update_url_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetUrlList_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateUrlList_async", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -15015,22 +18810,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_url_list_async.py" + "title": "networksecurity_v1_generated_network_security_update_url_list_async.py" }, { "canonical": true, @@ -15039,23 +18834,27 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_url_list", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_url_list", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetUrlList", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateUrlList", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "GetUrlList" + "shortName": "UpdateUrlList" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetUrlListRequest" + "type": "google.cloud.network_security_v1.types.UpdateUrlListRequest" }, { - "name": "name", - "type": "str" + "name": "url_list", + "type": "google.cloud.network_security_v1.types.UrlList" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -15070,22 +18869,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.UrlList", - "shortName": "get_url_list" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_url_list" }, - "description": "Sample for GetUrlList", - "file": "networksecurity_v1_generated_network_security_get_url_list_sync.py", + "description": "Sample for UpdateUrlList", + "file": "networksecurity_v1_generated_network_security_update_url_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetUrlList_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateUrlList_sync", "segments": [ { - "end": 51, + "end": 59, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 59, "start": 27, "type": "SHORT" }, @@ -15095,49 +18894,53 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 56, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 60, + "start": 57, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_url_list_sync.py" + "title": "networksecurity_v1_generated_network_security_update_url_list_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.add_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListAuthorizationPolicies" + "shortName": "AddAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15151,22 +18954,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", - "shortName": "list_authorization_policies" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_address_group_items" }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -15176,48 +18979,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.add_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListAuthorizationPolicies" + "shortName": "AddAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15231,22 +19038,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", - "shortName": "list_authorization_policies" + "resultType": "google.api_core.operation.Operation", + "shortName": "add_address_group_items" }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -15256,47 +19063,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authz_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.clone_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthzPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListAuthzPolicies" + "shortName": "CloneAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthzPoliciesRequest" + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", "type": "str" }, { @@ -15312,22 +19123,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthzPoliciesAsyncPager", - "shortName": "list_authz_policies" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "clone_address_group_items" }, - "description": "Sample for ListAuthzPolicies", - "file": "networksecurity_v1_generated_network_security_list_authz_policies_async.py", + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthzPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -15337,46 +19148,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authz_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authz_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthzPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListAuthzPolicies" + "shortName": "CloneAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthzPoliciesRequest" + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", "type": "str" }, { @@ -15392,22 +19207,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthzPoliciesPager", - "shortName": "list_authz_policies" + "resultType": "google.api_core.operation.Operation", + "shortName": "clone_address_group_items" }, - "description": "Sample for ListAuthzPolicies", - "file": "networksecurity_v1_generated_network_security_list_authz_policies_sync.py", + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthzPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -15417,49 +19232,57 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authz_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_backend_authentication_configs", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.create_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListBackendAuthenticationConfigs", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListBackendAuthenticationConfigs" + "shortName": "CreateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListBackendAuthenticationConfigsRequest" + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" }, { "name": "parent", "type": "str" }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15473,22 +19296,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListBackendAuthenticationConfigsAsyncPager", - "shortName": "list_backend_authentication_configs" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_address_group" }, - "description": "Sample for ListBackendAuthenticationConfigs", - "file": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_async.py", + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListBackendAuthenticationConfigs_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async", "segments": [ { - "end": 52, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 62, "start": 27, "type": "SHORT" }, @@ -15498,48 +19321,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_backend_authentication_configs", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.create_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListBackendAuthenticationConfigs", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListBackendAuthenticationConfigs" + "shortName": "CreateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListBackendAuthenticationConfigsRequest" + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" }, { "name": "parent", "type": "str" }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15553,22 +19384,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListBackendAuthenticationConfigsPager", - "shortName": "list_backend_authentication_configs" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_address_group" }, - "description": "Sample for ListBackendAuthenticationConfigs", - "file": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_sync.py", + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListBackendAuthenticationConfigs_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync", "segments": [ { - "end": 52, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 62, "start": 27, "type": "SHORT" }, @@ -15578,47 +19409,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_backend_authentication_configs_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.delete_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListClientTlsPolicies" + "shortName": "DeleteAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15634,22 +19465,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", - "shortName": "list_client_tls_policies" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_address_group" }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -15664,41 +19495,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.delete_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListClientTlsPolicies" + "shortName": "DeleteAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15714,22 +19545,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", - "shortName": "list_client_tls_policies" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_address_group" }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -15744,42 +19575,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_gateway_security_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.get_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListGatewaySecurityPolicies" + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPoliciesRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15795,22 +19626,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPoliciesAsyncPager", - "shortName": "list_gateway_security_policies" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for ListGatewaySecurityPolicies", - "file": "networksecurity_v1_generated_network_security_list_gateway_security_policies_async.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15830,36 +19661,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_gateway_security_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_gateway_security_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.get_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListGatewaySecurityPolicies" + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPoliciesRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15875,22 +19706,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPoliciesPager", - "shortName": "list_gateway_security_policies" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for ListGatewaySecurityPolicies", - "file": "networksecurity_v1_generated_network_security_list_gateway_security_policies_sync.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15910,37 +19741,37 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_gateway_security_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_gateway_security_policy_rules", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicyRules", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListGatewaySecurityPolicyRules" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPolicyRulesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { @@ -15956,14 +19787,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPolicyRulesAsyncPager", - "shortName": "list_gateway_security_policy_rules" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager", + "shortName": "list_address_group_references" }, - "description": "Sample for ListGatewaySecurityPolicyRules", - "file": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_async.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicyRules_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async", "segments": [ { "end": 52, @@ -15996,31 +19827,31 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_gateway_security_policy_rules", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListGatewaySecurityPolicyRules", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListGatewaySecurityPolicyRules" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListGatewaySecurityPolicyRulesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { @@ -16036,14 +19867,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListGatewaySecurityPolicyRulesPager", - "shortName": "list_gateway_security_policy_rules" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager", + "shortName": "list_address_group_references" }, - "description": "Sample for ListGatewaySecurityPolicyRules", - "file": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_sync.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListGatewaySecurityPolicyRules_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync", "segments": [ { "end": 52, @@ -16076,29 +19907,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_gateway_security_policy_rules_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListServerTlsPolicies" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { "name": "parent", @@ -16117,14 +19948,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", - "shortName": "list_server_tls_policies" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager", + "shortName": "list_address_groups" }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async", "segments": [ { "end": 52, @@ -16157,28 +19988,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListServerTlsPolicies" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { "name": "parent", @@ -16197,14 +20028,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", - "shortName": "list_server_tls_policies" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager", + "shortName": "list_address_groups" }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync", "segments": [ { "end": 52, @@ -16237,34 +20068,38 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_tls_inspection_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListTlsInspectionPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListTlsInspectionPolicies" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListTlsInspectionPoliciesRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16278,22 +20113,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListTlsInspectionPoliciesAsyncPager", - "shortName": "list_tls_inspection_policies" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_address_group_items" }, - "description": "Sample for ListTlsInspectionPolicies", - "file": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_async.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListTlsInspectionPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16303,48 +20138,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_tls_inspection_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListTlsInspectionPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListTlsInspectionPolicies" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListTlsInspectionPoliciesRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16358,22 +20197,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListTlsInspectionPoliciesPager", - "shortName": "list_tls_inspection_policies" + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_address_group_items" }, - "description": "Sample for ListTlsInspectionPolicies", - "file": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_sync.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListTlsInspectionPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16383,48 +20222,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_tls_inspection_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_url_lists", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListUrlLists", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListUrlLists" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListUrlListsRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "parent", - "type": "str" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -16439,22 +20282,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListUrlListsAsyncPager", - "shortName": "list_url_lists" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_address_group" }, - "description": "Sample for ListUrlLists", - "file": "networksecurity_v1_generated_network_security_list_url_lists_async.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListUrlLists_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -16464,47 +20307,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_url_lists_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_url_lists", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListUrlLists", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListUrlLists" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListUrlListsRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "parent", - "type": "str" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -16519,22 +20366,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListUrlListsPager", - "shortName": "list_url_lists" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_address_group" }, - "description": "Sample for ListUrlLists", - "file": "networksecurity_v1_generated_network_security_list_url_lists_sync.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListUrlLists_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -16544,52 +20391,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_url_lists_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.create_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateAuthorizationPolicy" + "shortName": "CreateSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateSecurityProfileGroupRequest" }, { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "security_profile_group", + "type": "google.cloud.network_security_v1.types.SecurityProfileGroup" + }, + { + "name": "security_profile_group_id", + "type": "str" }, { "name": "retry", @@ -16605,21 +20456,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_authorization_policy" + "shortName": "create_security_profile_group" }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", + "description": "Sample for CreateSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfileGroup_async", "segments": [ { - "end": 59, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16629,51 +20480,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.create_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateAuthorizationPolicy" + "shortName": "CreateSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateSecurityProfileGroupRequest" }, { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "security_profile_group", + "type": "google.cloud.network_security_v1.types.SecurityProfileGroup" + }, + { + "name": "security_profile_group_id", + "type": "str" }, { "name": "retry", @@ -16689,21 +20544,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_authorization_policy" + "shortName": "create_security_profile_group" }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", + "description": "Sample for CreateSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfileGroup_sync", "segments": [ { - "end": 59, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16713,52 +20568,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authz_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.create_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateAuthzPolicy" + "shortName": "CreateSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateSecurityProfileRequest" }, { - "name": "authz_policy", - "type": "google.cloud.network_security_v1.types.AuthzPolicy" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "security_profile", + "type": "google.cloud.network_security_v1.types.SecurityProfile" + }, + { + "name": "security_profile_id", + "type": "str" }, { "name": "retry", @@ -16774,21 +20633,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_authz_policy" + "shortName": "create_security_profile" }, - "description": "Sample for UpdateAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_update_authz_policy_async.py", + "description": "Sample for CreateSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthzPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfile_async", "segments": [ { - "end": 60, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16798,51 +20657,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authz_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authz_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.create_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthzPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateAuthzPolicy" + "shortName": "CreateSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthzPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateSecurityProfileRequest" }, { - "name": "authz_policy", - "type": "google.cloud.network_security_v1.types.AuthzPolicy" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "security_profile", + "type": "google.cloud.network_security_v1.types.SecurityProfile" + }, + { + "name": "security_profile_id", + "type": "str" }, { "name": "retry", @@ -16858,21 +20721,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_authz_policy" + "shortName": "create_security_profile" }, - "description": "Sample for UpdateAuthzPolicy", - "file": "networksecurity_v1_generated_network_security_update_authz_policy_sync.py", + "description": "Sample for CreateSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthzPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfile_sync", "segments": [ { - "end": 60, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 56, "start": 27, "type": "SHORT" }, @@ -16882,52 +20745,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authz_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.delete_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateBackendAuthenticationConfig" + "shortName": "DeleteSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateBackendAuthenticationConfigRequest" - }, - { - "name": "backend_authentication_config", - "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + "type": "google.cloud.network_security_v1.types.DeleteSecurityProfileGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -16943,21 +20802,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_backend_authentication_config" + "shortName": "delete_security_profile_group" }, - "description": "Sample for UpdateBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_update_backend_authentication_config_async.py", + "description": "Sample for DeleteSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateBackendAuthenticationConfig_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfileGroup_async", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -16967,51 +20826,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_backend_authentication_config_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_backend_authentication_config", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.delete_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateBackendAuthenticationConfig", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateBackendAuthenticationConfig" + "shortName": "DeleteSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateBackendAuthenticationConfigRequest" - }, - { - "name": "backend_authentication_config", - "type": "google.cloud.network_security_v1.types.BackendAuthenticationConfig" + "type": "google.cloud.network_security_v1.types.DeleteSecurityProfileGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17027,21 +20882,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_backend_authentication_config" + "shortName": "delete_security_profile_group" }, - "description": "Sample for UpdateBackendAuthenticationConfig", - "file": "networksecurity_v1_generated_network_security_update_backend_authentication_config_sync.py", + "description": "Sample for DeleteSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateBackendAuthenticationConfig_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfileGroup_sync", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -17051,52 +20906,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_backend_authentication_config_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.delete_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateClientTlsPolicy" + "shortName": "DeleteSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "type": "google.cloud.network_security_v1.types.DeleteSecurityProfileRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17112,21 +20963,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_client_tls_policy" + "shortName": "delete_security_profile" }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", + "description": "Sample for DeleteSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfile_async", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -17136,51 +20987,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.delete_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateClientTlsPolicy" + "shortName": "DeleteSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "type": "google.cloud.network_security_v1.types.DeleteSecurityProfileRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17196,21 +21043,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_client_tls_policy" + "shortName": "delete_security_profile" }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", + "description": "Sample for DeleteSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfile_sync", "segments": [ { - "end": 58, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 55, "start": 27, "type": "SHORT" }, @@ -17220,52 +21067,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.get_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateGatewaySecurityPolicyRule" + "shortName": "GetSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRuleRequest" - }, - { - "name": "gateway_security_policy_rule", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + "type": "google.cloud.network_security_v1.types.GetSecurityProfileGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17280,22 +21123,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.types.SecurityProfileGroup", + "shortName": "get_security_profile_group" }, - "description": "Sample for UpdateGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_async.py", + "description": "Sample for GetSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicyRule_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfileGroup_async", "segments": [ { - "end": 62, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17305,51 +21148,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_gateway_security_policy_rule", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.get_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicyRule", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateGatewaySecurityPolicyRule" + "shortName": "GetSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRuleRequest" - }, - { - "name": "gateway_security_policy_rule", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicyRule" + "type": "google.cloud.network_security_v1.types.GetSecurityProfileGroupRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17364,22 +21203,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_gateway_security_policy_rule" + "resultType": "google.cloud.network_security_v1.types.SecurityProfileGroup", + "shortName": "get_security_profile_group" }, - "description": "Sample for UpdateGatewaySecurityPolicyRule", - "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_sync.py", + "description": "Sample for GetSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicyRule_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfileGroup_sync", "segments": [ { - "end": 62, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17389,52 +21228,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_rule_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.get_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateGatewaySecurityPolicy" + "shortName": "GetSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRequest" - }, - { - "name": "gateway_security_policy", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + "type": "google.cloud.network_security_v1.types.GetSecurityProfileRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17449,22 +21284,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.types.SecurityProfile", + "shortName": "get_security_profile" }, - "description": "Sample for UpdateGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_async.py", + "description": "Sample for GetSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfile_async", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17474,51 +21309,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_gateway_security_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.get_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateGatewaySecurityPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateGatewaySecurityPolicy" + "shortName": "GetSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateGatewaySecurityPolicyRequest" - }, - { - "name": "gateway_security_policy", - "type": "google.cloud.network_security_v1.types.GatewaySecurityPolicy" + "type": "google.cloud.network_security_v1.types.GetSecurityProfileRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17533,22 +21364,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_gateway_security_policy" + "resultType": "google.cloud.network_security_v1.types.SecurityProfile", + "shortName": "get_security_profile" }, - "description": "Sample for UpdateGatewaySecurityPolicy", - "file": "networksecurity_v1_generated_network_security_update_gateway_security_policy_sync.py", + "description": "Sample for GetSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateGatewaySecurityPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfile_sync", "segments": [ { - "end": 58, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17558,52 +21389,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_gateway_security_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.list_security_profile_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfileGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateServerTlsPolicy" + "shortName": "ListSecurityProfileGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "type": "google.cloud.network_security_v1.types.ListSecurityProfileGroupsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -17618,22 +21445,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfileGroupsAsyncPager", + "shortName": "list_security_profile_groups" }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", + "description": "Sample for ListSecurityProfileGroups", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfileGroups_async", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17643,51 +21470,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.list_security_profile_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfileGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateServerTlsPolicy" + "shortName": "ListSecurityProfileGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "type": "google.cloud.network_security_v1.types.ListSecurityProfileGroupsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -17702,22 +21525,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfileGroupsPager", + "shortName": "list_security_profile_groups" }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", + "description": "Sample for ListSecurityProfileGroups", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfileGroups_sync", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17727,52 +21550,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.list_security_profiles", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfiles", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateTlsInspectionPolicy" + "shortName": "ListSecurityProfiles" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateTlsInspectionPolicyRequest" - }, - { - "name": "tls_inspection_policy", - "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + "type": "google.cloud.network_security_v1.types.ListSecurityProfilesRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -17787,22 +21606,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfilesAsyncPager", + "shortName": "list_security_profiles" }, - "description": "Sample for UpdateTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_async.py", + "description": "Sample for ListSecurityProfiles", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateTlsInspectionPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfiles_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17812,51 +21631,47 @@ "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": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_tls_inspection_policy", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.list_security_profiles", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateTlsInspectionPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfiles", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateTlsInspectionPolicy" + "shortName": "ListSecurityProfiles" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateTlsInspectionPolicyRequest" - }, - { - "name": "tls_inspection_policy", - "type": "google.cloud.network_security_v1.types.TlsInspectionPolicy" + "type": "google.cloud.network_security_v1.types.ListSecurityProfilesRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -17871,22 +21686,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_tls_inspection_policy" + "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfilesPager", + "shortName": "list_security_profiles" }, - "description": "Sample for UpdateTlsInspectionPolicy", - "file": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_sync.py", + "description": "Sample for ListSecurityProfiles", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateTlsInspectionPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfiles_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17896,48 +21711,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": "networksecurity_v1_generated_network_security_update_tls_inspection_policy_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_url_list", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.update_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateUrlList", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateUrlList" + "shortName": "UpdateSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateUrlListRequest" + "type": "google.cloud.network_security_v1.types.UpdateSecurityProfileGroupRequest" }, { - "name": "url_list", - "type": "google.cloud.network_security_v1.types.UrlList" + "name": "security_profile_group", + "type": "google.cloud.network_security_v1.types.SecurityProfileGroup" }, { "name": "update_mask", @@ -17957,21 +21772,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_url_list" + "shortName": "update_security_profile_group" }, - "description": "Sample for UpdateUrlList", - "file": "networksecurity_v1_generated_network_security_update_url_list_async.py", + "description": "Sample for UpdateSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateUrlList_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfileGroup_async", "segments": [ { - "end": 59, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 54, "start": 27, "type": "SHORT" }, @@ -17981,47 +21796,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_url_list_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_url_list", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.update_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateUrlList", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "UpdateUrlList" + "shortName": "UpdateSecurityProfileGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateUrlListRequest" + "type": "google.cloud.network_security_v1.types.UpdateSecurityProfileGroupRequest" }, { - "name": "url_list", - "type": "google.cloud.network_security_v1.types.UrlList" + "name": "security_profile_group", + "type": "google.cloud.network_security_v1.types.SecurityProfileGroup" }, { "name": "update_mask", @@ -18041,21 +21856,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_url_list" + "shortName": "update_security_profile_group" }, - "description": "Sample for UpdateUrlList", - "file": "networksecurity_v1_generated_network_security_update_url_list_sync.py", + "description": "Sample for UpdateSecurityProfileGroup", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateUrlList_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfileGroup_sync", "segments": [ { - "end": 59, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 54, "start": 27, "type": "SHORT" }, @@ -18065,52 +21880,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_url_list_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", + "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.add_address_group_items", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.update_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "AddAddressGroupItems" + "shortName": "UpdateSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.UpdateSecurityProfileRequest" }, { - "name": "address_group", - "type": "str" + "name": "security_profile", + "type": "google.cloud.network_security_v1.types.SecurityProfile" }, { - "name": "items", - "type": "MutableSequence[str]" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -18126,21 +21941,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "add_address_group_items" + "shortName": "update_security_profile" }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py", + "description": "Sample for UpdateSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfile_async", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -18150,51 +21965,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", + "shortName": "OrganizationSecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.add_address_group_items", + "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.update_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", + "shortName": "OrganizationSecurityProfileGroupService" }, - "shortName": "AddAddressGroupItems" + "shortName": "UpdateSecurityProfile" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.UpdateSecurityProfileRequest" }, { - "name": "address_group", - "type": "str" + "name": "security_profile", + "type": "google.cloud.network_security_v1.types.SecurityProfile" }, { - "name": "items", - "type": "MutableSequence[str]" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -18210,21 +22025,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "add_address_group_items" + "shortName": "update_security_profile" }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py", + "description": "Sample for UpdateSecurityProfile", + "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync", + "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfile_sync", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -18234,51 +22049,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py" + "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.clone_address_group_items", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.create_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.CreateSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "CloneAddressGroupItems" + "shortName": "CreateSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.CreateSACAttachmentRequest" }, { - "name": "address_group", + "name": "parent", "type": "str" }, { - "name": "source_address_group", + "name": "sac_attachment", + "type": "google.cloud.network_security_v1.types.SACAttachment" + }, + { + "name": "sac_attachment_id", "type": "str" }, { @@ -18295,21 +22114,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "clone_address_group_items" + "shortName": "create_sac_attachment" }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py", + "description": "Sample for CreateSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_create_sac_attachment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_CreateSACAttachment_async", "segments": [ { - "end": 56, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 61, "start": 27, "type": "SHORT" }, @@ -18319,50 +22138,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_create_sac_attachment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.create_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.CreateSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "CloneAddressGroupItems" + "shortName": "CreateSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.CreateSACAttachmentRequest" }, { - "name": "address_group", + "name": "parent", "type": "str" }, { - "name": "source_address_group", + "name": "sac_attachment", + "type": "google.cloud.network_security_v1.types.SACAttachment" + }, + { + "name": "sac_attachment_id", "type": "str" }, { @@ -18379,21 +22202,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "clone_address_group_items" + "shortName": "create_sac_attachment" }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py", + "description": "Sample for CreateSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_create_sac_attachment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_CreateSACAttachment_sync", "segments": [ { - "end": 56, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 61, "start": 27, "type": "SHORT" }, @@ -18403,55 +22226,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_create_sac_attachment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.create_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.create_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.CreateSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "CreateAddressGroup" + "shortName": "CreateSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateSACRealmRequest" }, { "name": "parent", "type": "str" }, { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" + "name": "sac_realm", + "type": "google.cloud.network_security_v1.types.SACRealm" }, { - "name": "address_group_id", + "name": "sac_realm_id", "type": "str" }, { @@ -18468,21 +22291,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_address_group" + "shortName": "create_sac_realm" }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py", + "description": "Sample for CreateSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_create_sac_realm_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_CreateSACRealm_async", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -18492,54 +22315,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_create_sac_realm_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.create_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.create_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.CreateSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "CreateAddressGroup" + "shortName": "CreateSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.CreateSACRealmRequest" }, { "name": "parent", "type": "str" }, { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" + "name": "sac_realm", + "type": "google.cloud.network_security_v1.types.SACRealm" }, { - "name": "address_group_id", + "name": "sac_realm_id", "type": "str" }, { @@ -18556,21 +22379,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_address_group" + "shortName": "create_sac_realm" }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py", + "description": "Sample for CreateSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_create_sac_realm_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_CreateSACRealm_sync", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -18580,44 +22403,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_create_sac_realm_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.delete_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.delete_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.DeleteSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "DeleteAddressGroup" + "shortName": "DeleteSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteSACAttachmentRequest" }, { "name": "name", @@ -18637,13 +22460,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_address_group" + "shortName": "delete_sac_attachment" }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py", + "description": "Sample for DeleteSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_async", "segments": [ { "end": 55, @@ -18676,28 +22499,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.delete_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.delete_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.DeleteSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "DeleteAddressGroup" + "shortName": "DeleteSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteSACAttachmentRequest" }, { "name": "name", @@ -18717,13 +22540,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_address_group" + "shortName": "delete_sac_attachment" }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py", + "description": "Sample for DeleteSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_DeleteSACAttachment_sync", "segments": [ { "end": 55, @@ -18756,29 +22579,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_delete_sac_attachment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.get_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.delete_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.DeleteSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "GetAddressGroup" + "shortName": "DeleteSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteSACRealmRequest" }, { "name": "name", @@ -18797,22 +22620,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_sac_realm" }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py", + "description": "Sample for DeleteSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_delete_sac_realm_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_DeleteSACRealm_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -18827,38 +22650,38 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_delete_sac_realm_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.get_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.delete_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.DeleteSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "GetAddressGroup" + "shortName": "DeleteSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.DeleteSACRealmRequest" }, { "name": "name", @@ -18877,22 +22700,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_sac_realm" }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py", + "description": "Sample for DeleteSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_delete_sac_realm_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_DeleteSACRealm_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -18907,42 +22730,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_delete_sac_realm_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_group_references", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.get_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.GetSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "ListAddressGroupReferences" + "shortName": "GetSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + "type": "google.cloud.network_security_v1.types.GetSACAttachmentRequest" }, { - "name": "address_group", + "name": "name", "type": "str" }, { @@ -18958,22 +22781,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager", - "shortName": "list_address_group_references" + "resultType": "google.cloud.network_security_v1.types.SACAttachment", + "shortName": "get_sac_attachment" }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py", + "description": "Sample for GetSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_get_sac_attachment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_GetSACAttachment_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -18993,36 +22816,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_get_sac_attachment_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_group_references", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.get_sac_attachment", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.GetSACAttachment", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "ListAddressGroupReferences" + "shortName": "GetSACAttachment" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + "type": "google.cloud.network_security_v1.types.GetSACAttachmentRequest" }, { - "name": "address_group", + "name": "name", "type": "str" }, { @@ -19038,22 +22861,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager", - "shortName": "list_address_group_references" + "resultType": "google.cloud.network_security_v1.types.SACAttachment", + "shortName": "get_sac_attachment" }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py", + "description": "Sample for GetSACAttachment", + "file": "networksecurity_v1_generated_sse_realm_service_get_sac_attachment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_GetSACAttachment_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -19073,37 +22896,37 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_get_sac_attachment_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_groups", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.get_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.GetSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "ListAddressGroups" + "shortName": "GetSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + "type": "google.cloud.network_security_v1.types.GetSACRealmRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -19119,22 +22942,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager", - "shortName": "list_address_groups" + "resultType": "google.cloud.network_security_v1.types.SACRealm", + "shortName": "get_sac_realm" }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py", + "description": "Sample for GetSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_get_sac_realm_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_GetSACRealm_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -19154,36 +22977,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_get_sac_realm_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_groups", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.get_sac_realm", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.GetSACRealm", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "ListAddressGroups" + "shortName": "GetSACRealm" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + "type": "google.cloud.network_security_v1.types.GetSACRealmRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -19199,22 +23022,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager", - "shortName": "list_address_groups" + "resultType": "google.cloud.network_security_v1.types.SACRealm", + "shortName": "get_sac_realm" }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py", + "description": "Sample for GetSACRealm", + "file": "networksecurity_v1_generated_sse_realm_service_get_sac_realm_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_GetSACRealm_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -19234,43 +23057,39 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_get_sac_realm_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.remove_address_group_items", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.list_sac_attachments", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.ListSACAttachments", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "RemoveAddressGroupItems" + "shortName": "ListSACAttachments" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.ListSACAttachmentsRequest" }, { - "name": "address_group", + "name": "parent", "type": "str" }, - { - "name": "items", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -19284,22 +23103,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "remove_address_group_items" + "resultType": "google.cloud.network_security_v1.services.sse_realm_service.pagers.ListSACAttachmentsAsyncPager", + "shortName": "list_sac_attachments" }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py", + "description": "Sample for ListSACAttachments", + "file": "networksecurity_v1_generated_sse_realm_service_list_sac_attachments_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_ListSACAttachments_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -19309,52 +23128,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_list_sac_attachments_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.list_sac_attachments", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.ListSACAttachments", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "RemoveAddressGroupItems" + "shortName": "ListSACAttachments" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + "type": "google.cloud.network_security_v1.types.ListSACAttachmentsRequest" }, { - "name": "address_group", + "name": "parent", "type": "str" }, - { - "name": "items", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -19368,22 +23183,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "remove_address_group_items" + "resultType": "google.cloud.network_security_v1.services.sse_realm_service.pagers.ListSACAttachmentsPager", + "shortName": "list_sac_attachments" }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py", + "description": "Sample for ListSACAttachments", + "file": "networksecurity_v1_generated_sse_realm_service_list_sac_attachments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_ListSACAttachments_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -19393,52 +23208,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_list_sac_attachments_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient", + "shortName": "SSERealmServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.update_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceAsyncClient.list_sac_realms", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.ListSACRealms", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "UpdateAddressGroup" + "shortName": "ListSACRealms" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" + "type": "google.cloud.network_security_v1.types.ListSACRealmsRequest" }, { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -19453,22 +23264,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_address_group" + "resultType": "google.cloud.network_security_v1.services.sse_realm_service.pagers.ListSACRealmsAsyncPager", + "shortName": "list_sac_realms" }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py", + "description": "Sample for ListSACRealms", + "file": "networksecurity_v1_generated_sse_realm_service_list_sac_realms_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async", + "regionTag": "networksecurity_v1_generated_SSERealmService_ListSACRealms_async", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -19478,51 +23289,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py" + "title": "networksecurity_v1_generated_sse_realm_service_list_sac_realms_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient", + "shortName": "SSERealmServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.update_address_group", + "fullName": "google.cloud.network_security_v1.SSERealmServiceClient.list_sac_realms", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", + "fullName": "google.cloud.networksecurity.v1.SSERealmService.ListSACRealms", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" + "fullName": "google.cloud.networksecurity.v1.SSERealmService", + "shortName": "SSERealmService" }, - "shortName": "UpdateAddressGroup" + "shortName": "ListSACRealms" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" + "type": "google.cloud.network_security_v1.types.ListSACRealmsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -19537,22 +23344,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_address_group" + "resultType": "google.cloud.network_security_v1.services.sse_realm_service.pagers.ListSACRealmsPager", + "shortName": "list_sac_realms" }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py", + "description": "Sample for ListSACRealms", + "file": "networksecurity_v1_generated_sse_realm_service_list_sac_realms_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync", + "regionTag": "networksecurity_v1_generated_SSERealmService_ListSACRealms_sync", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -19562,37 +23369,37 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py" + "title": "networksecurity_v1_generated_sse_realm_service_list_sac_realms_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.create_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.create_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.CreateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "CreateSecurityProfileGroup" }, @@ -19630,10 +23437,10 @@ "shortName": "create_security_profile_group" }, "description": "Sample for CreateSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfileGroup_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_async", "segments": [ { "end": 56, @@ -19666,21 +23473,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.create_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.create_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.CreateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "CreateSecurityProfileGroup" }, @@ -19718,10 +23525,10 @@ "shortName": "create_security_profile_group" }, "description": "Sample for CreateSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfileGroup_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfileGroup_sync", "segments": [ { "end": 56, @@ -19754,22 +23561,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_group_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.create_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.create_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.CreateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "CreateSecurityProfile" }, @@ -19807,10 +23614,10 @@ "shortName": "create_security_profile" }, "description": "Sample for CreateSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfile_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_async", "segments": [ { "end": 56, @@ -19843,21 +23650,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.create_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.create_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.CreateSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.CreateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "CreateSecurityProfile" }, @@ -19895,10 +23702,10 @@ "shortName": "create_security_profile" }, "description": "Sample for CreateSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_CreateSecurityProfile_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_CreateSecurityProfile_sync", "segments": [ { "end": 56, @@ -19931,22 +23738,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_create_security_profile_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_create_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.delete_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.delete_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.DeleteSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "DeleteSecurityProfileGroup" }, @@ -19976,10 +23783,10 @@ "shortName": "delete_security_profile_group" }, "description": "Sample for DeleteSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfileGroup_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_async", "segments": [ { "end": 55, @@ -20012,21 +23819,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.delete_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.delete_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.DeleteSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "DeleteSecurityProfileGroup" }, @@ -20056,10 +23863,10 @@ "shortName": "delete_security_profile_group" }, "description": "Sample for DeleteSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfileGroup_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfileGroup_sync", "segments": [ { "end": 55, @@ -20092,22 +23899,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_group_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.delete_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.delete_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.DeleteSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "DeleteSecurityProfile" }, @@ -20137,10 +23944,10 @@ "shortName": "delete_security_profile" }, "description": "Sample for DeleteSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfile_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_async", "segments": [ { "end": 55, @@ -20173,21 +23980,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.delete_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.delete_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.DeleteSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.DeleteSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "DeleteSecurityProfile" }, @@ -20217,10 +24024,10 @@ "shortName": "delete_security_profile" }, "description": "Sample for DeleteSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_DeleteSecurityProfile_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_DeleteSecurityProfile_sync", "segments": [ { "end": 55, @@ -20253,22 +24060,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_delete_security_profile_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_delete_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.get_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.get_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.GetSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "GetSecurityProfileGroup" }, @@ -20298,10 +24105,10 @@ "shortName": "get_security_profile_group" }, "description": "Sample for GetSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfileGroup_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_async", "segments": [ { "end": 51, @@ -20334,21 +24141,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.get_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.get_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.GetSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "GetSecurityProfileGroup" }, @@ -20378,10 +24185,10 @@ "shortName": "get_security_profile_group" }, "description": "Sample for GetSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfileGroup_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfileGroup_sync", "segments": [ { "end": 51, @@ -20414,22 +24221,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_group_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.get_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.get_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.GetSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "GetSecurityProfile" }, @@ -20459,10 +24266,10 @@ "shortName": "get_security_profile" }, "description": "Sample for GetSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfile_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_async", "segments": [ { "end": 51, @@ -20495,21 +24302,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.get_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.get_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.GetSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.GetSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "GetSecurityProfile" }, @@ -20539,10 +24346,10 @@ "shortName": "get_security_profile" }, "description": "Sample for GetSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_GetSecurityProfile_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_GetSecurityProfile_sync", "segments": [ { "end": 51, @@ -20575,22 +24382,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_get_security_profile_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_get_security_profile_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.list_security_profile_groups", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.list_security_profile_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfileGroups", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.ListSecurityProfileGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "ListSecurityProfileGroups" }, @@ -20616,14 +24423,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfileGroupsAsyncPager", + "resultType": "google.cloud.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfileGroupsAsyncPager", "shortName": "list_security_profile_groups" }, "description": "Sample for ListSecurityProfileGroups", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfileGroups_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_async", "segments": [ { "end": 52, @@ -20656,21 +24463,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.list_security_profile_groups", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.list_security_profile_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfileGroups", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.ListSecurityProfileGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "ListSecurityProfileGroups" }, @@ -20696,14 +24503,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfileGroupsPager", + "resultType": "google.cloud.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfileGroupsPager", "shortName": "list_security_profile_groups" }, "description": "Sample for ListSecurityProfileGroups", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfileGroups_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfileGroups_sync", "segments": [ { "end": 52, @@ -20736,22 +24543,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profile_groups_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_list_security_profile_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.list_security_profiles", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.list_security_profiles", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfiles", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.ListSecurityProfiles", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "ListSecurityProfiles" }, @@ -20777,14 +24584,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfilesAsyncPager", + "resultType": "google.cloud.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfilesAsyncPager", "shortName": "list_security_profiles" }, "description": "Sample for ListSecurityProfiles", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_list_security_profiles_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfiles_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_async", "segments": [ { "end": 52, @@ -20817,21 +24624,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_list_security_profiles_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.list_security_profiles", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.list_security_profiles", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.ListSecurityProfiles", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.ListSecurityProfiles", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "ListSecurityProfiles" }, @@ -20857,14 +24664,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.organization_security_profile_group_service.pagers.ListSecurityProfilesPager", + "resultType": "google.cloud.network_security_v1.services.security_profile_group_service.pagers.ListSecurityProfilesPager", "shortName": "list_security_profiles" }, "description": "Sample for ListSecurityProfiles", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_list_security_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_ListSecurityProfiles_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_ListSecurityProfiles_sync", "segments": [ { "end": 52, @@ -20897,22 +24704,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_list_security_profiles_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_list_security_profiles_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.update_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.update_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.UpdateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "UpdateSecurityProfileGroup" }, @@ -20946,10 +24753,10 @@ "shortName": "update_security_profile_group" }, "description": "Sample for UpdateSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfileGroup_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_async", "segments": [ { "end": 54, @@ -20982,21 +24789,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.update_security_profile_group", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.update_security_profile_group", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfileGroup", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.UpdateSecurityProfileGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "UpdateSecurityProfileGroup" }, @@ -21030,10 +24837,10 @@ "shortName": "update_security_profile_group" }, "description": "Sample for UpdateSecurityProfileGroup", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfileGroup_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfileGroup_sync", "segments": [ { "end": 54, @@ -21066,22 +24873,22 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_group_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient", - "shortName": "OrganizationSecurityProfileGroupServiceAsyncClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient", + "shortName": "SecurityProfileGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceAsyncClient.update_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceAsyncClient.update_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.UpdateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "UpdateSecurityProfile" }, @@ -21115,10 +24922,10 @@ "shortName": "update_security_profile" }, "description": "Sample for UpdateSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_async.py", + "file": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfile_async", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_async", "segments": [ { "end": 54, @@ -21151,21 +24958,21 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_async.py" + "title": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient", - "shortName": "OrganizationSecurityProfileGroupServiceClient" + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient", + "shortName": "SecurityProfileGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.OrganizationSecurityProfileGroupServiceClient.update_security_profile", + "fullName": "google.cloud.network_security_v1.SecurityProfileGroupServiceClient.update_security_profile", "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService.UpdateSecurityProfile", + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService.UpdateSecurityProfile", "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationSecurityProfileGroupService", - "shortName": "OrganizationSecurityProfileGroupService" + "fullName": "google.cloud.networksecurity.v1.SecurityProfileGroupService", + "shortName": "SecurityProfileGroupService" }, "shortName": "UpdateSecurityProfile" }, @@ -21199,10 +25006,10 @@ "shortName": "update_security_profile" }, "description": "Sample for UpdateSecurityProfile", - "file": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_sync.py", + "file": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationSecurityProfileGroupService_UpdateSecurityProfile_sync", + "regionTag": "networksecurity_v1_generated_SecurityProfileGroupService_UpdateSecurityProfile_sync", "segments": [ { "end": 54, @@ -21235,7 +25042,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_organization_security_profile_group_service_update_security_profile_sync.py" + "title": "networksecurity_v1_generated_security_profile_group_service_update_security_profile_sync.py" } ] } diff --git a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_firewall_activation.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_firewall_activation.py index 8e6a5a4dd6a1..4b407bada9f9 100644 --- a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_firewall_activation.py +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_firewall_activation.py @@ -1937,11 +1937,11 @@ async def test_list_firewall_endpoints_async_pages(): @pytest.mark.parametrize( "request_type", [ - firewall_activation.GetFirewallEndpointRequest(), + firewall_activation.ListFirewallEndpointsRequest(), {}, ], ) -def test_get_firewall_endpoint(request_type, transport: str = "grpc"): +def test_list_project_firewall_endpoints(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1953,40 +1953,28 @@ def test_get_firewall_endpoint(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpoint( - name="name_value", - description="description_value", - state=firewall_activation.FirewallEndpoint.State.CREATING, - reconciling=True, - associated_networks=["associated_networks_value"], - satisfies_pzs=True, - satisfies_pzi=True, - billing_project_id="billing_project_id_value", + call.return_value = firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.get_firewall_endpoint(request) + response = client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.GetFirewallEndpointRequest() + request = firewall_activation.ListFirewallEndpointsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, firewall_activation.FirewallEndpoint) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == firewall_activation.FirewallEndpoint.State.CREATING - assert response.reconciling is True - assert response.associated_networks == ["associated_networks_value"] - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.billing_project_id == "billing_project_id_value" + assert isinstance(response, pagers.ListProjectFirewallEndpointsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_firewall_endpoint_non_empty_request_with_auto_populated_field(): +def test_list_project_firewall_endpoints_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 = FirewallActivationClient( @@ -1997,27 +1985,33 @@ def test_get_firewall_endpoint_non_empty_request_with_auto_populated_field(): # 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 = firewall_activation.GetFirewallEndpointRequest( - name="name_value", + request = firewall_activation.ListFirewallEndpointsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_firewall_endpoint(request=request) + client.list_project_firewall_endpoints(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointRequest( - name="name_value", + request_msg = firewall_activation.ListFirewallEndpointsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_get_firewall_endpoint_use_cached_wrapped_rpc(): +def test_list_project_firewall_endpoints_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: @@ -2032,7 +2026,7 @@ def test_get_firewall_endpoint_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_firewall_endpoint + client._transport.list_project_firewall_endpoints in client._transport._wrapped_methods ) @@ -2041,16 +2035,16 @@ def test_get_firewall_endpoint_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_firewall_endpoint] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.list_project_firewall_endpoints + ] = mock_rpc request = {} - client.get_firewall_endpoint(request) + client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_firewall_endpoint(request) + client.list_project_firewall_endpoints(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2058,7 +2052,7 @@ def test_get_firewall_endpoint_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_firewall_endpoint_async_use_cached_wrapped_rpc( +async def test_list_project_firewall_endpoints_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2075,7 +2069,7 @@ async def test_get_firewall_endpoint_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_firewall_endpoint + client._client._transport.list_project_firewall_endpoints in client._client._transport._wrapped_methods ) @@ -2083,16 +2077,16 @@ async def test_get_firewall_endpoint_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_firewall_endpoint + client._client._transport.list_project_firewall_endpoints ] = mock_rpc request = {} - await client.get_firewall_endpoint(request) + await client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_firewall_endpoint(request) + await client.list_project_firewall_endpoints(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2103,11 +2097,11 @@ async def test_get_firewall_endpoint_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.GetFirewallEndpointRequest(), + firewall_activation.ListFirewallEndpointsRequest(), {}, ], ) -async def test_get_firewall_endpoint_async( +async def test_list_project_firewall_endpoints_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -2121,58 +2115,46 @@ async def test_get_firewall_endpoint_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpoint( - name="name_value", - description="description_value", - state=firewall_activation.FirewallEndpoint.State.CREATING, - reconciling=True, - associated_networks=["associated_networks_value"], - satisfies_pzs=True, - satisfies_pzi=True, - billing_project_id="billing_project_id_value", + firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.get_firewall_endpoint(request) + response = await client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.GetFirewallEndpointRequest() + request = firewall_activation.ListFirewallEndpointsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, firewall_activation.FirewallEndpoint) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == firewall_activation.FirewallEndpoint.State.CREATING - assert response.reconciling is True - assert response.associated_networks == ["associated_networks_value"] - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.billing_project_id == "billing_project_id_value" + assert isinstance(response, pagers.ListProjectFirewallEndpointsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_firewall_endpoint_field_headers(): +def test_list_project_firewall_endpoints_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.GetFirewallEndpointRequest() + request = firewall_activation.ListFirewallEndpointsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: - call.return_value = firewall_activation.FirewallEndpoint() - client.get_firewall_endpoint(request) + call.return_value = firewall_activation.ListFirewallEndpointsResponse() + client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2183,30 +2165,30 @@ def test_get_firewall_endpoint_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_firewall_endpoint_field_headers_async(): +async def test_list_project_firewall_endpoints_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.GetFirewallEndpointRequest() + request = firewall_activation.ListFirewallEndpointsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpoint() + firewall_activation.ListFirewallEndpointsResponse() ) - await client.get_firewall_endpoint(request) + await client.list_project_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2217,37 +2199,37 @@ async def test_get_firewall_endpoint_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_firewall_endpoint_flattened(): +def test_list_project_firewall_endpoints_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpoint() + call.return_value = firewall_activation.ListFirewallEndpointsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_firewall_endpoint( - name="name_value", + client.list_project_firewall_endpoints( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_firewall_endpoint_flattened_error(): +def test_list_project_firewall_endpoints_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2255,45 +2237,45 @@ def test_get_firewall_endpoint_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_firewall_endpoint( - firewall_activation.GetFirewallEndpointRequest(), - name="name_value", + client.list_project_firewall_endpoints( + firewall_activation.ListFirewallEndpointsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_firewall_endpoint_flattened_async(): +async def test_list_project_firewall_endpoints_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpoint() + call.return_value = firewall_activation.ListFirewallEndpointsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpoint() + firewall_activation.ListFirewallEndpointsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_firewall_endpoint( - name="name_value", + response = await client.list_project_firewall_endpoints( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_firewall_endpoint_flattened_error_async(): +async def test_list_project_firewall_endpoints_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2301,98 +2283,315 @@ async def test_get_firewall_endpoint_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_firewall_endpoint( - firewall_activation.GetFirewallEndpointRequest(), - name="name_value", + await client.list_project_firewall_endpoints( + firewall_activation.ListFirewallEndpointsRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - firewall_activation.CreateFirewallEndpointRequest(), - {}, - ], -) -def test_create_firewall_endpoint(request_type, transport: str = "grpc"): +def test_list_project_firewall_endpoints_pager(transport_name: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional 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_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_firewall_endpoint(request) + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = firewall_activation.CreateFirewallEndpointRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_project_firewall_endpoints( + request={}, retry=retry, timeout=timeout + ) - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, firewall_activation.FirewallEndpoint) for i in results) -def test_create_firewall_endpoint_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. +def test_list_project_firewall_endpoints_pages(transport_name: str = "grpc"): client = FirewallActivationClient( 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 = firewall_activation.CreateFirewallEndpointRequest( - parent="parent_value", - firewall_endpoint_id="firewall_endpoint_id_value", - request_id="request_id_value", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.list_project_firewall_endpoints), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_firewall_endpoint(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointRequest( - parent="parent_value", - firewall_endpoint_id="firewall_endpoint_id_value", - request_id="request_id_value", - ) - assert args[0] == request_msg - - -def test_create_firewall_endpoint_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), + RuntimeError, + ) + pages = list(client.list_project_firewall_endpoints(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_project_firewall_endpoints_async_pager(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_project_firewall_endpoints), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_project_firewall_endpoints( + 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, firewall_activation.FirewallEndpoint) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_project_firewall_endpoints_async_pages(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_project_firewall_endpoints), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_project_firewall_endpoints(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", + [ + firewall_activation.GetFirewallEndpointRequest(), + {}, + ], +) +def test_get_firewall_endpoint(request_type, transport: str = "grpc"): + client = FirewallActivationClient( + 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_firewall_endpoint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) + response = client.get_firewall_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" + + +def test_get_firewall_endpoint_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 = FirewallActivationClient( + 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 = firewall_activation.GetFirewallEndpointRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_firewall_endpoint(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_firewall_endpoint_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 = FirewallActivationClient( + 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_firewall_endpoint + client._transport.get_firewall_endpoint in client._transport._wrapped_methods ) @@ -2401,21 +2600,16 @@ def test_create_firewall_endpoint_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_firewall_endpoint - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_firewall_endpoint] = ( + mock_rpc + ) request = {} - client.create_firewall_endpoint(request) + client.get_firewall_endpoint(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_firewall_endpoint(request) + client.get_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2423,7 +2617,7 @@ def test_create_firewall_endpoint_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_firewall_endpoint_async_use_cached_wrapped_rpc( +async def test_get_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2440,7 +2634,7 @@ async def test_create_firewall_endpoint_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_firewall_endpoint + client._client._transport.get_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -2448,21 +2642,16 @@ async def test_create_firewall_endpoint_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_firewall_endpoint + client._client._transport.get_firewall_endpoint ] = mock_rpc request = {} - await client.create_firewall_endpoint(request) + await client.get_firewall_endpoint(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_firewall_endpoint(request) + await client.get_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2473,11 +2662,11 @@ async def test_create_firewall_endpoint_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.CreateFirewallEndpointRequest(), + firewall_activation.GetFirewallEndpointRequest(), {}, ], ) -async def test_create_firewall_endpoint_async( +async def test_get_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -2491,41 +2680,58 @@ async def test_create_firewall_endpoint_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.get_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) ) - response = await client.create_firewall_endpoint(request) + response = await client.get_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.CreateFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" -def test_create_firewall_endpoint_field_headers(): +def test_get_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.CreateFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.get_firewall_endpoint), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_firewall_endpoint(request) + call.return_value = firewall_activation.FirewallEndpoint() + client.get_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2536,30 +2742,30 @@ def test_create_firewall_endpoint_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_firewall_endpoint_field_headers_async(): +async def test_get_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.CreateFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.get_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + firewall_activation.FirewallEndpoint() ) - await client.create_firewall_endpoint(request) + await client.get_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2570,45 +2776,37 @@ async def test_create_firewall_endpoint_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_firewall_endpoint_flattened(): +def test_get_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.get_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = firewall_activation.FirewallEndpoint() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_firewall_endpoint( - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", + client.get_firewall_endpoint( + 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].firewall_endpoint - mock_val = firewall_activation.FirewallEndpoint(name="name_value") - assert arg == mock_val - arg = args[0].firewall_endpoint_id - mock_val = "firewall_endpoint_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_firewall_endpoint_flattened_error(): +def test_get_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2616,55 +2814,45 @@ def test_create_firewall_endpoint_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_firewall_endpoint( - firewall_activation.CreateFirewallEndpointRequest(), - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", + client.get_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_firewall_endpoint_flattened_async(): +async def test_get_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" + type(client.transport.get_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = firewall_activation.FirewallEndpoint() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + firewall_activation.FirewallEndpoint() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_firewall_endpoint( - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", + response = await client.get_firewall_endpoint( + 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].firewall_endpoint - mock_val = firewall_activation.FirewallEndpoint(name="name_value") - assert arg == mock_val - arg = args[0].firewall_endpoint_id - mock_val = "firewall_endpoint_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_firewall_endpoint_flattened_error_async(): +async def test_get_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2672,22 +2860,20 @@ async def test_create_firewall_endpoint_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_firewall_endpoint( - firewall_activation.CreateFirewallEndpointRequest(), - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", + await client.get_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - firewall_activation.DeleteFirewallEndpointRequest(), + firewall_activation.GetFirewallEndpointRequest(), {}, ], ) -def test_delete_firewall_endpoint(request_type, transport: str = "grpc"): +def test_get_project_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2699,23 +2885,40 @@ def test_delete_firewall_endpoint(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_firewall_endpoint(request) + call.return_value = firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) + response = client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.DeleteFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" -def test_delete_firewall_endpoint_non_empty_request_with_auto_populated_field(): +def test_get_project_firewall_endpoint_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 = FirewallActivationClient( @@ -2726,29 +2929,27 @@ def test_delete_firewall_endpoint_non_empty_request_with_auto_populated_field(): # 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 = firewall_activation.DeleteFirewallEndpointRequest( + request = firewall_activation.GetFirewallEndpointRequest( name="name_value", - request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_firewall_endpoint(request=request) + client.get_project_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointRequest( + request_msg = firewall_activation.GetFirewallEndpointRequest( name="name_value", - request_id="request_id_value", ) assert args[0] == request_msg -def test_delete_firewall_endpoint_use_cached_wrapped_rpc(): +def test_get_project_firewall_endpoint_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: @@ -2763,7 +2964,7 @@ def test_delete_firewall_endpoint_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_firewall_endpoint + client._transport.get_project_firewall_endpoint in client._transport._wrapped_methods ) @@ -2773,20 +2974,15 @@ def test_delete_firewall_endpoint_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_firewall_endpoint + client._transport.get_project_firewall_endpoint ] = mock_rpc request = {} - client.delete_firewall_endpoint(request) + client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_firewall_endpoint(request) + client.get_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2794,7 +2990,7 @@ def test_delete_firewall_endpoint_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_firewall_endpoint_async_use_cached_wrapped_rpc( +async def test_get_project_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2811,7 +3007,7 @@ async def test_delete_firewall_endpoint_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_firewall_endpoint + client._client._transport.get_project_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -2819,21 +3015,16 @@ async def test_delete_firewall_endpoint_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_firewall_endpoint + client._client._transport.get_project_firewall_endpoint ] = mock_rpc request = {} - await client.delete_firewall_endpoint(request) + await client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_firewall_endpoint(request) + await client.get_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2844,11 +3035,11 @@ async def test_delete_firewall_endpoint_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.DeleteFirewallEndpointRequest(), + firewall_activation.GetFirewallEndpointRequest(), {}, ], ) -async def test_delete_firewall_endpoint_async( +async def test_get_project_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -2862,41 +3053,58 @@ async def test_delete_firewall_endpoint_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) ) - response = await client.delete_firewall_endpoint(request) + response = await client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.DeleteFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" -def test_delete_firewall_endpoint_field_headers(): +def test_get_project_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.DeleteFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_firewall_endpoint(request) + call.return_value = firewall_activation.FirewallEndpoint() + client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2912,25 +3120,25 @@ def test_delete_firewall_endpoint_field_headers(): @pytest.mark.asyncio -async def test_delete_firewall_endpoint_field_headers_async(): +async def test_get_project_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.DeleteFirewallEndpointRequest() + request = firewall_activation.GetFirewallEndpointRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + firewall_activation.FirewallEndpoint() ) - await client.delete_firewall_endpoint(request) + await client.get_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2945,20 +3153,20 @@ async def test_delete_firewall_endpoint_field_headers_async(): ) in kw["metadata"] -def test_delete_firewall_endpoint_flattened(): +def test_get_project_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = firewall_activation.FirewallEndpoint() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_firewall_endpoint( + client.get_project_firewall_endpoint( name="name_value", ) @@ -2971,7 +3179,7 @@ def test_delete_firewall_endpoint_flattened(): assert arg == mock_val -def test_delete_firewall_endpoint_flattened_error(): +def test_get_project_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2979,31 +3187,31 @@ def test_delete_firewall_endpoint_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_firewall_endpoint( - firewall_activation.DeleteFirewallEndpointRequest(), + client.get_project_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_firewall_endpoint_flattened_async(): +async def test_get_project_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" + type(client.transport.get_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = firewall_activation.FirewallEndpoint() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + firewall_activation.FirewallEndpoint() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_firewall_endpoint( + response = await client.get_project_firewall_endpoint( name="name_value", ) @@ -3017,7 +3225,7 @@ async def test_delete_firewall_endpoint_flattened_async(): @pytest.mark.asyncio -async def test_delete_firewall_endpoint_flattened_error_async(): +async def test_get_project_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3025,8 +3233,8 @@ async def test_delete_firewall_endpoint_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_firewall_endpoint( - firewall_activation.DeleteFirewallEndpointRequest(), + await client.get_project_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), name="name_value", ) @@ -3034,11 +3242,11 @@ async def test_delete_firewall_endpoint_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - firewall_activation.UpdateFirewallEndpointRequest(), + firewall_activation.CreateFirewallEndpointRequest(), {}, ], ) -def test_update_firewall_endpoint(request_type, transport: str = "grpc"): +def test_create_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3050,23 +3258,23 @@ def test_update_firewall_endpoint(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_firewall_endpoint(request) + response = client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.UpdateFirewallEndpointRequest() + request = firewall_activation.CreateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_firewall_endpoint_non_empty_request_with_auto_populated_field(): +def test_create_firewall_endpoint_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 = FirewallActivationClient( @@ -3077,27 +3285,31 @@ def test_update_firewall_endpoint_non_empty_request_with_auto_populated_field(): # 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 = firewall_activation.UpdateFirewallEndpointRequest( - request_id="request_id_value", + request = firewall_activation.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_firewall_endpoint(request=request) + client.create_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointRequest( + request_msg = firewall_activation.CreateFirewallEndpointRequest( + parent="parent_value", + firewall_endpoint_id="firewall_endpoint_id_value", request_id="request_id_value", ) assert args[0] == request_msg -def test_update_firewall_endpoint_use_cached_wrapped_rpc(): +def test_create_firewall_endpoint_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: @@ -3112,7 +3324,7 @@ def test_update_firewall_endpoint_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_firewall_endpoint + client._transport.create_firewall_endpoint in client._transport._wrapped_methods ) @@ -3122,10 +3334,10 @@ def test_update_firewall_endpoint_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_firewall_endpoint + client._transport.create_firewall_endpoint ] = mock_rpc request = {} - client.update_firewall_endpoint(request) + client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3135,7 +3347,7 @@ def test_update_firewall_endpoint_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_firewall_endpoint(request) + client.create_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3143,7 +3355,7 @@ def test_update_firewall_endpoint_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( +async def test_create_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3160,7 +3372,7 @@ async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_firewall_endpoint + client._client._transport.create_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -3168,11 +3380,11 @@ async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_firewall_endpoint + client._client._transport.create_firewall_endpoint ] = mock_rpc request = {} - await client.update_firewall_endpoint(request) + await client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3182,7 +3394,7 @@ async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_firewall_endpoint(request) + await client.create_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3193,11 +3405,11 @@ async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.UpdateFirewallEndpointRequest(), + firewall_activation.CreateFirewallEndpointRequest(), {}, ], ) -async def test_update_firewall_endpoint_async( +async def test_create_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -3211,41 +3423,41 @@ async def test_update_firewall_endpoint_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__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.update_firewall_endpoint(request) + response = await client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.UpdateFirewallEndpointRequest() + request = firewall_activation.CreateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_firewall_endpoint_field_headers(): +def test_create_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.UpdateFirewallEndpointRequest() + request = firewall_activation.CreateFirewallEndpointRequest() - request.firewall_endpoint.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_firewall_endpoint(request) + client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3256,30 +3468,30 @@ def test_update_firewall_endpoint_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "firewall_endpoint.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_firewall_endpoint_field_headers_async(): +async def test_create_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.UpdateFirewallEndpointRequest() + request = firewall_activation.CreateFirewallEndpointRequest() - request.firewall_endpoint.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_firewall_endpoint(request) + await client.create_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3290,41 +3502,45 @@ async def test_update_firewall_endpoint_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "firewall_endpoint.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_firewall_endpoint_flattened(): +def test_create_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__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.update_firewall_endpoint( + client.create_firewall_endpoint( + parent="parent_value", firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + firewall_endpoint_id="firewall_endpoint_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].firewall_endpoint mock_val = firewall_activation.FirewallEndpoint(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].firewall_endpoint_id + mock_val = "firewall_endpoint_id_value" assert arg == mock_val -def test_update_firewall_endpoint_flattened_error(): +def test_create_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3332,22 +3548,23 @@ def test_update_firewall_endpoint_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_firewall_endpoint( - firewall_activation.UpdateFirewallEndpointRequest(), + client.create_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), + parent="parent_value", firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + firewall_endpoint_id="firewall_endpoint_id_value", ) @pytest.mark.asyncio -async def test_update_firewall_endpoint_flattened_async(): +async def test_create_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" + type(client.transport.create_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -3357,25 +3574,29 @@ async def test_update_firewall_endpoint_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_firewall_endpoint( + response = await client.create_firewall_endpoint( + parent="parent_value", firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + firewall_endpoint_id="firewall_endpoint_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].firewall_endpoint mock_val = firewall_activation.FirewallEndpoint(name="name_value") assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].firewall_endpoint_id + mock_val = "firewall_endpoint_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_firewall_endpoint_flattened_error_async(): +async def test_create_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3383,21 +3604,22 @@ async def test_update_firewall_endpoint_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_firewall_endpoint( - firewall_activation.UpdateFirewallEndpointRequest(), + await client.create_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), + parent="parent_value", firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + firewall_endpoint_id="firewall_endpoint_id_value", ) @pytest.mark.parametrize( "request_type", [ - firewall_activation.ListFirewallEndpointAssociationsRequest(), + firewall_activation.CreateFirewallEndpointRequest(), {}, ], ) -def test_list_firewall_endpoint_associations(request_type, transport: str = "grpc"): +def test_create_project_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3409,30 +3631,23 @@ def test_list_firewall_endpoint_associations(request_type, transport: str = "grp # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - response = client.list_firewall_endpoint_associations(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.ListFirewallEndpointAssociationsRequest() + request = firewall_activation.CreateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFirewallEndpointAssociationsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_firewall_endpoint_associations_non_empty_request_with_auto_populated_field(): +def test_create_project_firewall_endpoint_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 = FirewallActivationClient( @@ -3443,33 +3658,31 @@ def test_list_firewall_endpoint_associations_non_empty_request_with_auto_populat # 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 = firewall_activation.ListFirewallEndpointAssociationsRequest( + request = firewall_activation.CreateFirewallEndpointRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + firewall_endpoint_id="firewall_endpoint_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_firewall_endpoint_associations(request=request) + client.create_project_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest( + request_msg = firewall_activation.CreateFirewallEndpointRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + firewall_endpoint_id="firewall_endpoint_id_value", + request_id="request_id_value", ) assert args[0] == request_msg -def test_list_firewall_endpoint_associations_use_cached_wrapped_rpc(): +def test_create_project_firewall_endpoint_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: @@ -3484,7 +3697,7 @@ def test_list_firewall_endpoint_associations_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_firewall_endpoint_associations + client._transport.create_project_firewall_endpoint in client._transport._wrapped_methods ) @@ -3494,15 +3707,20 @@ def test_list_firewall_endpoint_associations_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_firewall_endpoint_associations + client._transport.create_project_firewall_endpoint ] = mock_rpc request = {} - client.list_firewall_endpoint_associations(request) + client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_firewall_endpoint_associations(request) + # 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_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3510,7 +3728,7 @@ def test_list_firewall_endpoint_associations_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_firewall_endpoint_associations_async_use_cached_wrapped_rpc( +async def test_create_project_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3527,7 +3745,7 @@ async def test_list_firewall_endpoint_associations_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_firewall_endpoint_associations + client._client._transport.create_project_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -3535,16 +3753,21 @@ async def test_list_firewall_endpoint_associations_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_firewall_endpoint_associations + client._client._transport.create_project_firewall_endpoint ] = mock_rpc request = {} - await client.list_firewall_endpoint_associations(request) + await client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_firewall_endpoint_associations(request) + # 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_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3555,11 +3778,11 @@ async def test_list_firewall_endpoint_associations_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.ListFirewallEndpointAssociationsRequest(), + firewall_activation.CreateFirewallEndpointRequest(), {}, ], ) -async def test_list_firewall_endpoint_associations_async( +async def test_create_project_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -3573,48 +3796,41 @@ async def test_list_firewall_endpoint_associations_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.ListFirewallEndpointAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_firewall_endpoint_associations(request) + response = await client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.ListFirewallEndpointAssociationsRequest() + request = firewall_activation.CreateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFirewallEndpointAssociationsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_firewall_endpoint_associations_field_headers(): +def test_create_project_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.ListFirewallEndpointAssociationsRequest() + request = firewall_activation.CreateFirewallEndpointRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: - call.return_value = ( - firewall_activation.ListFirewallEndpointAssociationsResponse() - ) - client.list_firewall_endpoint_associations(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3630,25 +3846,25 @@ def test_list_firewall_endpoint_associations_field_headers(): @pytest.mark.asyncio -async def test_list_firewall_endpoint_associations_field_headers_async(): +async def test_create_project_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.ListFirewallEndpointAssociationsRequest() + request = firewall_activation.CreateFirewallEndpointRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.ListFirewallEndpointAssociationsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_firewall_endpoint_associations(request) + await client.create_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3663,23 +3879,23 @@ async def test_list_firewall_endpoint_associations_field_headers_async(): ) in kw["metadata"] -def test_list_firewall_endpoint_associations_flattened(): +def test_create_project_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - firewall_activation.ListFirewallEndpointAssociationsResponse() - ) + 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.list_firewall_endpoint_associations( + client.create_project_firewall_endpoint( parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", ) # Establish that the underlying call was made with the expected @@ -3689,9 +3905,15 @@ def test_list_firewall_endpoint_associations_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(name="name_value") + assert arg == mock_val + arg = args[0].firewall_endpoint_id + mock_val = "firewall_endpoint_id_value" + assert arg == mock_val -def test_list_firewall_endpoint_associations_flattened_error(): +def test_create_project_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3699,34 +3921,36 @@ def test_list_firewall_endpoint_associations_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_firewall_endpoint_associations( - firewall_activation.ListFirewallEndpointAssociationsRequest(), + client.create_project_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", ) @pytest.mark.asyncio -async def test_list_firewall_endpoint_associations_flattened_async(): +async def test_create_project_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" + type(client.transport.create_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - firewall_activation.ListFirewallEndpointAssociationsResponse() - ) + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.ListFirewallEndpointAssociationsResponse() + 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.list_firewall_endpoint_associations( + response = await client.create_project_firewall_endpoint( parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", ) # Establish that the underlying call was made with the expected @@ -3736,10 +3960,16 @@ async def test_list_firewall_endpoint_associations_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(name="name_value") + assert arg == mock_val + arg = args[0].firewall_endpoint_id + mock_val = "firewall_endpoint_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_firewall_endpoint_associations_flattened_error_async(): +async def test_create_project_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3747,228 +3977,22 @@ async def test_list_firewall_endpoint_associations_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_firewall_endpoint_associations( - firewall_activation.ListFirewallEndpointAssociationsRequest(), + await client.create_project_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", ) -def test_list_firewall_endpoint_associations_pager(transport_name: str = "grpc"): - client = FirewallActivationClient( - 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_firewall_endpoint_associations), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_firewall_endpoint_associations( - 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, firewall_activation.FirewallEndpointAssociation) - for i in results - ) - - -def test_list_firewall_endpoint_associations_pages(transport_name: str = "grpc"): - client = FirewallActivationClient( - 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_firewall_endpoint_associations), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_firewall_endpoint_associations(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_firewall_endpoint_associations_async_pager(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_firewall_endpoint_associations( - 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, firewall_activation.FirewallEndpointAssociation) - for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_firewall_endpoint_associations_async_pages(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.list_firewall_endpoint_associations(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", - [ - firewall_activation.GetFirewallEndpointAssociationRequest(), - {}, - ], -) -def test_get_firewall_endpoint_association(request_type, transport: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.DeleteFirewallEndpointRequest(), + {}, + ], +) +def test_delete_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3980,40 +4004,23 @@ def test_get_firewall_endpoint_association(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpointAssociation( - name="name_value", - state=firewall_activation.FirewallEndpointAssociation.State.CREATING, - network="network_value", - firewall_endpoint="firewall_endpoint_value", - tls_inspection_policy="tls_inspection_policy_value", - reconciling=True, - disabled=True, - ) - response = client.get_firewall_endpoint_association(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.GetFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, firewall_activation.FirewallEndpointAssociation) - assert response.name == "name_value" - assert ( - response.state == firewall_activation.FirewallEndpointAssociation.State.CREATING - ) - assert response.network == "network_value" - assert response.firewall_endpoint == "firewall_endpoint_value" - assert response.tls_inspection_policy == "tls_inspection_policy_value" - assert response.reconciling is True - assert response.disabled is True + assert isinstance(response, future.Future) -def test_get_firewall_endpoint_association_non_empty_request_with_auto_populated_field(): +def test_delete_firewall_endpoint_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 = FirewallActivationClient( @@ -4024,27 +4031,29 @@ def test_get_firewall_endpoint_association_non_empty_request_with_auto_populated # 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 = firewall_activation.GetFirewallEndpointAssociationRequest( + request = firewall_activation.DeleteFirewallEndpointRequest( name="name_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_firewall_endpoint_association(request=request) + client.delete_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointAssociationRequest( + request_msg = firewall_activation.DeleteFirewallEndpointRequest( name="name_value", + request_id="request_id_value", ) assert args[0] == request_msg -def test_get_firewall_endpoint_association_use_cached_wrapped_rpc(): +def test_delete_firewall_endpoint_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: @@ -4059,7 +4068,7 @@ def test_get_firewall_endpoint_association_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_firewall_endpoint_association + client._transport.delete_firewall_endpoint in client._transport._wrapped_methods ) @@ -4069,15 +4078,20 @@ def test_get_firewall_endpoint_association_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_firewall_endpoint_association + client._transport.delete_firewall_endpoint ] = mock_rpc request = {} - client.get_firewall_endpoint_association(request) + client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_firewall_endpoint_association(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4085,7 +4099,7 @@ def test_get_firewall_endpoint_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_firewall_endpoint_association_async_use_cached_wrapped_rpc( +async def test_delete_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4102,7 +4116,7 @@ async def test_get_firewall_endpoint_association_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_firewall_endpoint_association + client._client._transport.delete_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -4110,16 +4124,21 @@ async def test_get_firewall_endpoint_association_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_firewall_endpoint_association + client._client._transport.delete_firewall_endpoint ] = mock_rpc request = {} - await client.get_firewall_endpoint_association(request) + await client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_firewall_endpoint_association(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4130,11 +4149,11 @@ async def test_get_firewall_endpoint_association_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - firewall_activation.GetFirewallEndpointAssociationRequest(), + firewall_activation.DeleteFirewallEndpointRequest(), {}, ], ) -async def test_get_firewall_endpoint_association_async( +async def test_delete_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -4148,58 +4167,41 @@ async def test_get_firewall_endpoint_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpointAssociation( - name="name_value", - state=firewall_activation.FirewallEndpointAssociation.State.CREATING, - network="network_value", - firewall_endpoint="firewall_endpoint_value", - tls_inspection_policy="tls_inspection_policy_value", - reconciling=True, - disabled=True, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_firewall_endpoint_association(request) + response = await client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.GetFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, firewall_activation.FirewallEndpointAssociation) - assert response.name == "name_value" - assert ( - response.state == firewall_activation.FirewallEndpointAssociation.State.CREATING - ) - assert response.network == "network_value" - assert response.firewall_endpoint == "firewall_endpoint_value" - assert response.tls_inspection_policy == "tls_inspection_policy_value" - assert response.reconciling is True - assert response.disabled is True + assert isinstance(response, future.Future) -def test_get_firewall_endpoint_association_field_headers(): +def test_delete_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.GetFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: - call.return_value = firewall_activation.FirewallEndpointAssociation() - client.get_firewall_endpoint_association(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4215,25 +4217,25 @@ def test_get_firewall_endpoint_association_field_headers(): @pytest.mark.asyncio -async def test_get_firewall_endpoint_association_field_headers_async(): +async def test_delete_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.GetFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpointAssociation() + operations_pb2.Operation(name="operations/op") ) - await client.get_firewall_endpoint_association(request) + await client.delete_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4248,20 +4250,20 @@ async def test_get_firewall_endpoint_association_field_headers_async(): ) in kw["metadata"] -def test_get_firewall_endpoint_association_flattened(): +def test_delete_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpointAssociation() + 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.get_firewall_endpoint_association( + client.delete_firewall_endpoint( name="name_value", ) @@ -4274,7 +4276,7 @@ def test_get_firewall_endpoint_association_flattened(): assert arg == mock_val -def test_get_firewall_endpoint_association_flattened_error(): +def test_delete_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4282,31 +4284,31 @@ def test_get_firewall_endpoint_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_firewall_endpoint_association( - firewall_activation.GetFirewallEndpointAssociationRequest(), + client.delete_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_firewall_endpoint_association_flattened_async(): +async def test_delete_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" + type(client.transport.delete_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = firewall_activation.FirewallEndpointAssociation() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpointAssociation() + 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.get_firewall_endpoint_association( + response = await client.delete_firewall_endpoint( name="name_value", ) @@ -4320,7 +4322,7 @@ async def test_get_firewall_endpoint_association_flattened_async(): @pytest.mark.asyncio -async def test_get_firewall_endpoint_association_flattened_error_async(): +async def test_delete_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4328,8 +4330,8 @@ async def test_get_firewall_endpoint_association_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_firewall_endpoint_association( - firewall_activation.GetFirewallEndpointAssociationRequest(), + await client.delete_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), name="name_value", ) @@ -4337,11 +4339,11 @@ async def test_get_firewall_endpoint_association_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - firewall_activation.CreateFirewallEndpointAssociationRequest(), + firewall_activation.DeleteFirewallEndpointRequest(), {}, ], ) -def test_create_firewall_endpoint_association(request_type, transport: str = "grpc"): +def test_delete_project_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4353,23 +4355,23 @@ def test_create_firewall_endpoint_association(request_type, transport: str = "gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_firewall_endpoint_association(request) + response = client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.CreateFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_firewall_endpoint_association_non_empty_request_with_auto_populated_field(): +def test_delete_project_firewall_endpoint_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 = FirewallActivationClient( @@ -4380,31 +4382,29 @@ def test_create_firewall_endpoint_association_non_empty_request_with_auto_popula # 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 = firewall_activation.CreateFirewallEndpointAssociationRequest( - parent="parent_value", - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + request = firewall_activation.DeleteFirewallEndpointRequest( + name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_firewall_endpoint_association(request=request) + client.delete_project_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest( - parent="parent_value", - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + request_msg = firewall_activation.DeleteFirewallEndpointRequest( + name="name_value", request_id="request_id_value", ) assert args[0] == request_msg -def test_create_firewall_endpoint_association_use_cached_wrapped_rpc(): +def test_delete_project_firewall_endpoint_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: @@ -4419,7 +4419,7 @@ def test_create_firewall_endpoint_association_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_firewall_endpoint_association + client._transport.delete_project_firewall_endpoint in client._transport._wrapped_methods ) @@ -4429,10 +4429,10 @@ def test_create_firewall_endpoint_association_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_firewall_endpoint_association + client._transport.delete_project_firewall_endpoint ] = mock_rpc request = {} - client.create_firewall_endpoint_association(request) + client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4442,7 +4442,7 @@ def test_create_firewall_endpoint_association_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_firewall_endpoint_association(request) + client.delete_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4450,7 +4450,7 @@ def test_create_firewall_endpoint_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc( +async def test_delete_project_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4467,7 +4467,7 @@ async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.create_firewall_endpoint_association + client._client._transport.delete_project_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -4475,11 +4475,11 @@ async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_firewall_endpoint_association + client._client._transport.delete_project_firewall_endpoint ] = mock_rpc request = {} - await client.create_firewall_endpoint_association(request) + await client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4489,7 +4489,7 @@ async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_firewall_endpoint_association(request) + await client.delete_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4500,11 +4500,11 @@ async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc @pytest.mark.parametrize( "request_type", [ - firewall_activation.CreateFirewallEndpointAssociationRequest(), + firewall_activation.DeleteFirewallEndpointRequest(), {}, ], ) -async def test_create_firewall_endpoint_association_async( +async def test_delete_project_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -4518,41 +4518,41 @@ async def test_create_firewall_endpoint_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__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_firewall_endpoint_association(request) + response = await client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.CreateFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_firewall_endpoint_association_field_headers(): +def test_delete_project_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.CreateFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_firewall_endpoint_association(request) + client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4563,30 +4563,30 @@ def test_create_firewall_endpoint_association_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_firewall_endpoint_association_field_headers_async(): +async def test_delete_project_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.CreateFirewallEndpointAssociationRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_firewall_endpoint_association(request) + await client.delete_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4597,47 +4597,37 @@ async def test_create_firewall_endpoint_association_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_firewall_endpoint_association_flattened(): +def test_delete_project_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__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_firewall_endpoint_association( - parent="parent_value", - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + client.delete_project_firewall_endpoint( + 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].firewall_endpoint_association - mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") - assert arg == mock_val - arg = args[0].firewall_endpoint_association_id - mock_val = "firewall_endpoint_association_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_firewall_endpoint_association_flattened_error(): +def test_delete_project_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4645,25 +4635,21 @@ def test_create_firewall_endpoint_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_firewall_endpoint_association( - firewall_activation.CreateFirewallEndpointAssociationRequest(), - parent="parent_value", - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + client.delete_project_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_firewall_endpoint_association_flattened_async(): +async def test_delete_project_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" + type(client.transport.delete_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4673,31 +4659,21 @@ async def test_create_firewall_endpoint_association_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_firewall_endpoint_association( - parent="parent_value", - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + response = await client.delete_project_firewall_endpoint( + 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].firewall_endpoint_association - mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") - assert arg == mock_val - arg = args[0].firewall_endpoint_association_id - mock_val = "firewall_endpoint_association_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_firewall_endpoint_association_flattened_error_async(): +async def test_delete_project_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4705,24 +4681,20 @@ async def test_create_firewall_endpoint_association_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_firewall_endpoint_association( - firewall_activation.CreateFirewallEndpointAssociationRequest(), - parent="parent_value", - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + await client.delete_project_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - firewall_activation.DeleteFirewallEndpointAssociationRequest(), + firewall_activation.UpdateFirewallEndpointRequest(), {}, ], ) -def test_delete_firewall_endpoint_association(request_type, transport: str = "grpc"): +def test_update_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4734,23 +4706,23 @@ def test_delete_firewall_endpoint_association(request_type, transport: str = "gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_firewall_endpoint_association(request) + response = client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.DeleteFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_firewall_endpoint_association_non_empty_request_with_auto_populated_field(): +def test_update_firewall_endpoint_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 = FirewallActivationClient( @@ -4761,29 +4733,27 @@ def test_delete_firewall_endpoint_association_non_empty_request_with_auto_popula # 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 = firewall_activation.DeleteFirewallEndpointAssociationRequest( - name="name_value", + request = firewall_activation.UpdateFirewallEndpointRequest( request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_firewall_endpoint_association(request=request) + client.update_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest( - name="name_value", + request_msg = firewall_activation.UpdateFirewallEndpointRequest( request_id="request_id_value", ) assert args[0] == request_msg -def test_delete_firewall_endpoint_association_use_cached_wrapped_rpc(): +def test_update_firewall_endpoint_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: @@ -4798,7 +4768,7 @@ def test_delete_firewall_endpoint_association_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_firewall_endpoint_association + client._transport.update_firewall_endpoint in client._transport._wrapped_methods ) @@ -4808,10 +4778,10 @@ def test_delete_firewall_endpoint_association_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_firewall_endpoint_association + client._transport.update_firewall_endpoint ] = mock_rpc request = {} - client.delete_firewall_endpoint_association(request) + client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4821,7 +4791,7 @@ def test_delete_firewall_endpoint_association_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_firewall_endpoint_association(request) + client.update_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4829,7 +4799,7 @@ def test_delete_firewall_endpoint_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_firewall_endpoint_association_async_use_cached_wrapped_rpc( +async def test_update_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4846,7 +4816,7 @@ async def test_delete_firewall_endpoint_association_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.delete_firewall_endpoint_association + client._client._transport.update_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -4854,11 +4824,11 @@ async def test_delete_firewall_endpoint_association_async_use_cached_wrapped_rpc mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_firewall_endpoint_association + client._client._transport.update_firewall_endpoint ] = mock_rpc request = {} - await client.delete_firewall_endpoint_association(request) + await client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4868,7 +4838,7 @@ async def test_delete_firewall_endpoint_association_async_use_cached_wrapped_rpc # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_firewall_endpoint_association(request) + await client.update_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4879,11 +4849,11 @@ async def test_delete_firewall_endpoint_association_async_use_cached_wrapped_rpc @pytest.mark.parametrize( "request_type", [ - firewall_activation.DeleteFirewallEndpointAssociationRequest(), + firewall_activation.UpdateFirewallEndpointRequest(), {}, ], ) -async def test_delete_firewall_endpoint_association_async( +async def test_update_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -4897,41 +4867,41 @@ async def test_delete_firewall_endpoint_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_firewall_endpoint_association(request) + response = await client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.DeleteFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_firewall_endpoint_association_field_headers(): +def test_update_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.DeleteFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() - request.name = "name_value" + request.firewall_endpoint.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_firewall_endpoint_association(request) + client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4942,30 +4912,30 @@ def test_delete_firewall_endpoint_association_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "firewall_endpoint.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_firewall_endpoint_association_field_headers_async(): +async def test_update_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.DeleteFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() - request.name = "name_value" + request.firewall_endpoint.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_firewall_endpoint_association(request) + await client.update_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4976,37 +4946,41 @@ async def test_delete_firewall_endpoint_association_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "firewall_endpoint.name=name_value", ) in kw["metadata"] -def test_delete_firewall_endpoint_association_flattened(): +def test_update_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_firewall_endpoint_association( - name="name_value", + client.update_firewall_endpoint( + firewall_endpoint=firewall_activation.FirewallEndpoint(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].name - mock_val = "name_value" + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(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_delete_firewall_endpoint_association_flattened_error(): +def test_update_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5014,21 +4988,22 @@ def test_delete_firewall_endpoint_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_firewall_endpoint_association( - firewall_activation.DeleteFirewallEndpointAssociationRequest(), - name="name_value", + client.update_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_delete_firewall_endpoint_association_flattened_async(): +async def test_update_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" + type(client.transport.update_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -5038,21 +5013,25 @@ async def test_delete_firewall_endpoint_association_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_firewall_endpoint_association( - name="name_value", + response = await client.update_firewall_endpoint( + firewall_endpoint=firewall_activation.FirewallEndpoint(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].name - mock_val = "name_value" + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(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_delete_firewall_endpoint_association_flattened_error_async(): +async def test_update_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5060,20 +5039,21 @@ async def test_delete_firewall_endpoint_association_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_firewall_endpoint_association( - firewall_activation.DeleteFirewallEndpointAssociationRequest(), - name="name_value", + await client.update_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - firewall_activation.UpdateFirewallEndpointAssociationRequest(), + firewall_activation.UpdateFirewallEndpointRequest(), {}, ], ) -def test_update_firewall_endpoint_association(request_type, transport: str = "grpc"): +def test_update_project_firewall_endpoint(request_type, transport: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5085,23 +5065,23 @@ def test_update_firewall_endpoint_association(request_type, transport: str = "gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_firewall_endpoint_association(request) + response = client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_firewall_endpoint_association_non_empty_request_with_auto_populated_field(): +def test_update_project_firewall_endpoint_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 = FirewallActivationClient( @@ -5112,27 +5092,27 @@ def test_update_firewall_endpoint_association_non_empty_request_with_auto_popula # 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 = firewall_activation.UpdateFirewallEndpointAssociationRequest( + request = firewall_activation.UpdateFirewallEndpointRequest( request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_firewall_endpoint_association(request=request) + client.update_project_firewall_endpoint(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest( + request_msg = firewall_activation.UpdateFirewallEndpointRequest( request_id="request_id_value", ) assert args[0] == request_msg -def test_update_firewall_endpoint_association_use_cached_wrapped_rpc(): +def test_update_project_firewall_endpoint_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: @@ -5147,7 +5127,7 @@ def test_update_firewall_endpoint_association_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_firewall_endpoint_association + client._transport.update_project_firewall_endpoint in client._transport._wrapped_methods ) @@ -5157,10 +5137,10 @@ def test_update_firewall_endpoint_association_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_firewall_endpoint_association + client._transport.update_project_firewall_endpoint ] = mock_rpc request = {} - client.update_firewall_endpoint_association(request) + client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5170,7 +5150,7 @@ def test_update_firewall_endpoint_association_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_firewall_endpoint_association(request) + client.update_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5178,7 +5158,7 @@ def test_update_firewall_endpoint_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc( +async def test_update_project_firewall_endpoint_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5195,7 +5175,7 @@ async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.update_firewall_endpoint_association + client._client._transport.update_project_firewall_endpoint in client._client._transport._wrapped_methods ) @@ -5203,11 +5183,11 @@ async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_firewall_endpoint_association + client._client._transport.update_project_firewall_endpoint ] = mock_rpc request = {} - await client.update_firewall_endpoint_association(request) + await client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5217,7 +5197,7 @@ async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_firewall_endpoint_association(request) + await client.update_project_firewall_endpoint(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5228,11 +5208,11 @@ async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc @pytest.mark.parametrize( "request_type", [ - firewall_activation.UpdateFirewallEndpointAssociationRequest(), + firewall_activation.UpdateFirewallEndpointRequest(), {}, ], ) -async def test_update_firewall_endpoint_association_async( +async def test_update_project_firewall_endpoint_async( request_type, transport: str = "grpc_asyncio" ): client = FirewallActivationAsyncClient( @@ -5246,41 +5226,41 @@ async def test_update_firewall_endpoint_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__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.update_firewall_endpoint_association(request) + response = await client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_firewall_endpoint_association_field_headers(): +def test_update_project_firewall_endpoint_field_headers(): client = FirewallActivationClient( 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 = firewall_activation.UpdateFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() - request.firewall_endpoint_association.name = "name_value" + request.firewall_endpoint.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_firewall_endpoint_association(request) + client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5291,30 +5271,30 @@ def test_update_firewall_endpoint_association_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "firewall_endpoint_association.name=name_value", + "firewall_endpoint.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_firewall_endpoint_association_field_headers_async(): +async def test_update_project_firewall_endpoint_field_headers_async(): client = FirewallActivationAsyncClient( 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 = firewall_activation.UpdateFirewallEndpointAssociationRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() - request.firewall_endpoint_association.name = "name_value" + request.firewall_endpoint.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_firewall_endpoint_association(request) + await client.update_project_firewall_endpoint(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5325,27 +5305,25 @@ async def test_update_firewall_endpoint_association_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "firewall_endpoint_association.name=name_value", + "firewall_endpoint.name=name_value", ) in kw["metadata"] -def test_update_firewall_endpoint_association_flattened(): +def test_update_project_firewall_endpoint_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__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.update_firewall_endpoint_association( - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), + client.update_project_firewall_endpoint( + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5353,15 +5331,15 @@ def test_update_firewall_endpoint_association_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].firewall_endpoint_association - mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(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_firewall_endpoint_association_flattened_error(): +def test_update_project_firewall_endpoint_flattened_error(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5369,24 +5347,22 @@ def test_update_firewall_endpoint_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_firewall_endpoint_association( - firewall_activation.UpdateFirewallEndpointAssociationRequest(), - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), + client.update_project_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_firewall_endpoint_association_flattened_async(): +async def test_update_project_firewall_endpoint_flattened_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" + type(client.transport.update_project_firewall_endpoint), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -5396,10 +5372,8 @@ async def test_update_firewall_endpoint_association_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_firewall_endpoint_association( - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), + response = await client.update_project_firewall_endpoint( + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5407,8 +5381,8 @@ async def test_update_firewall_endpoint_association_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].firewall_endpoint_association - mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") + arg = args[0].firewall_endpoint + mock_val = firewall_activation.FirewallEndpoint(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -5416,7 +5390,7 @@ async def test_update_firewall_endpoint_association_flattened_async(): @pytest.mark.asyncio -async def test_update_firewall_endpoint_association_flattened_error_async(): +async def test_update_project_firewall_endpoint_flattened_error_async(): client = FirewallActivationAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5424,292 +5398,99 @@ async def test_update_firewall_endpoint_association_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_firewall_endpoint_association( - firewall_activation.UpdateFirewallEndpointAssociationRequest(), - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), + await client.update_project_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_firewall_endpoints_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.ListFirewallEndpointAssociationsRequest(), + {}, + ], +) +def test_list_firewall_endpoint_associations(request_type, transport: str = "grpc"): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Ensure method has been cached - assert ( - client._transport.list_firewall_endpoints - in client._transport._wrapped_methods - ) + # Everything is optional 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 - # 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - client._transport._wrapped_methods[ - client._transport.list_firewall_endpoints - ] = mock_rpc - - request = {} - client.list_firewall_endpoints(request) + response = client.list_firewall_endpoint_associations(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.ListFirewallEndpointAssociationsRequest() + assert args[0] == request - client.list_firewall_endpoints(request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirewallEndpointAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # 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_firewall_endpoint_associations_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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -def test_list_firewall_endpoints_rest_required_fields( - request_type=firewall_activation.ListFirewallEndpointsRequest, -): - transport_class = transports.FirewallActivationRestTransport - - 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_firewall_endpoints._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_firewall_endpoints._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = firewall_activation.ListFirewallEndpointsResponse() - # 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 = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoints(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_list_firewall_endpoints_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_firewall_endpoints._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) - - -def test_list_firewall_endpoints_rest_flattened(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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 = firewall_activation.ListFirewallEndpointAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # 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 = firewall_activation.ListFirewallEndpointsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/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 = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoints(**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/v1/{parent=organizations/*/locations/*}/firewallEndpoints" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_list_firewall_endpoints_rest_flattened_error(transport: str = "rest"): - client = FirewallActivationClient( - 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_firewall_endpoints( - firewall_activation.ListFirewallEndpointsRequest(), + client.list_firewall_endpoint_associations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest( parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) + assert args[0] == request_msg -def test_list_firewall_endpoints_rest_pager(transport: str = "rest"): - client = FirewallActivationClient( - 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 = ( - firewall_activation.ListFirewallEndpointsResponse( - firewall_endpoints=[ - firewall_activation.FirewallEndpoint(), - firewall_activation.FirewallEndpoint(), - firewall_activation.FirewallEndpoint(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointsResponse( - firewall_endpoints=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointsResponse( - firewall_endpoints=[ - firewall_activation.FirewallEndpoint(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointsResponse( - firewall_endpoints=[ - firewall_activation.FirewallEndpoint(), - firewall_activation.FirewallEndpoint(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - firewall_activation.ListFirewallEndpointsResponse.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": "organizations/sample1/locations/sample2"} - - pager = client.list_firewall_endpoints(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, firewall_activation.FirewallEndpoint) for i in results) - - pages = list(client.list_firewall_endpoints(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_firewall_endpoint_rest_use_cached_wrapped_rpc(): +def test_list_firewall_endpoint_associations_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 = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5718,7 +5499,7 @@ def test_get_firewall_endpoint_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_firewall_endpoint + client._transport.list_firewall_endpoint_associations in client._transport._wrapped_methods ) @@ -5727,397 +5508,564 @@ def test_get_firewall_endpoint_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_firewall_endpoint] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_firewall_endpoint_associations + ] = mock_rpc request = {} - client.get_firewall_endpoint(request) + client.list_firewall_endpoint_associations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_firewall_endpoint(request) + client.list_firewall_endpoint_associations(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_firewall_endpoint_rest_required_fields( - request_type=firewall_activation.GetFirewallEndpointRequest, +@pytest.mark.asyncio +async def test_list_firewall_endpoint_associations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.FirewallActivationRestTransport + # Clients should use _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 = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_firewall_endpoint_associations + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_firewall_endpoint._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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_firewall_endpoint_associations + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_firewall_endpoint_associations(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_firewall_endpoint._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.list_firewall_endpoint_associations(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.ListFirewallEndpointAssociationsRequest(), + {}, + ], +) +async def test_list_firewall_endpoint_associations_async( + request_type, transport: str = "grpc_asyncio" +): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = firewall_activation.FirewallEndpoint() - # 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 + # Everything is optional 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 - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_firewall_endpoint_associations(request) - # Convert return value to protobuf type - return_value = firewall_activation.FirewallEndpoint.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = firewall_activation.ListFirewallEndpointAssociationsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirewallEndpointAssociationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - response = client.get_firewall_endpoint(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +def test_list_firewall_endpoint_associations_field_headers(): + client = FirewallActivationClient( + 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 = firewall_activation.ListFirewallEndpointAssociationsRequest() -def test_get_firewall_endpoint_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + request.parent = "parent_value" - unset_fields = transport.get_firewall_endpoint._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + call.return_value = ( + firewall_activation.ListFirewallEndpointAssociationsResponse() + ) + client.list_firewall_endpoint_associations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_get_firewall_endpoint_rest_flattened(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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_firewall_endpoint_associations_field_headers_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = firewall_activation.FirewallEndpoint() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.ListFirewallEndpointAssociationsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointAssociationsResponse() ) - mock_args.update(sample_request) + await client.list_firewall_endpoint_associations(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 = firewall_activation.FirewallEndpoint.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"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_firewall_endpoint(**mock_args) + # 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_firewall_endpoint_associations_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + firewall_activation.ListFirewallEndpointAssociationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_firewall_endpoint_associations( + parent="parent_value", + ) # 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/v1/{name=organizations/*/locations/*/firewallEndpoints/*}" - % client.transport._host, - args[1], - ) + 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_get_firewall_endpoint_rest_flattened_error(transport: str = "rest"): +def test_list_firewall_endpoint_associations_flattened_error(): client = FirewallActivationClient( 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_firewall_endpoint( - firewall_activation.GetFirewallEndpointRequest(), - name="name_value", + client.list_firewall_endpoint_associations( + firewall_activation.ListFirewallEndpointAssociationsRequest(), + parent="parent_value", ) -def test_create_firewall_endpoint_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_list_firewall_endpoint_associations_flattened_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.create_firewall_endpoint - in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + firewall_activation.ListFirewallEndpointAssociationsResponse() ) - # 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. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointAssociationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_firewall_endpoint_associations( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.create_firewall_endpoint - ] = mock_rpc - - request = {} - client.create_firewall_endpoint(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_firewall_endpoint(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_firewall_endpoint_rest_required_fields( - request_type=firewall_activation.CreateFirewallEndpointRequest, -): - transport_class = transports.FirewallActivationRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["firewall_endpoint_id"] = "" - 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 - assert "firewallEndpointId" not in jsonified_request + # 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 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_firewall_endpoint._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "firewallEndpointId" in jsonified_request - assert ( - jsonified_request["firewallEndpointId"] == request_init["firewall_endpoint_id"] +@pytest.mark.asyncio +async def test_list_firewall_endpoint_associations_flattened_error_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - jsonified_request["parent"] = "parent_value" - jsonified_request["firewallEndpointId"] = "firewall_endpoint_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_firewall_endpoint._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "firewall_endpoint_id", - "request_id", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_firewall_endpoint_associations( + firewall_activation.ListFirewallEndpointAssociationsRequest(), + parent="parent_value", ) - ) - 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 "firewallEndpointId" in jsonified_request - assert jsonified_request["firewallEndpointId"] == "firewall_endpoint_id_value" +def test_list_firewall_endpoint_associations_pager(transport_name: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - 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_firewall_endpoint(request) - - expected_params = [ - ( - "firewallEndpointId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + ), + RuntimeError, + ) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_firewall_endpoint_associations( + request={}, retry=retry, timeout=timeout + ) -def test_create_firewall_endpoint_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - unset_fields = transport.create_firewall_endpoint._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "firewallEndpointId", - "requestId", - ) - ) - & set( - ( - "parent", - "firewallEndpointId", - "firewallEndpoint", - ) + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, firewall_activation.FirewallEndpointAssociation) + for i in results ) - ) -def test_create_firewall_endpoint_rest_flattened(): +def test_list_firewall_endpoint_associations_pages(transport_name: str = "grpc"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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": "organizations/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_firewall_endpoint(**mock_args) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_firewall_endpoint_associations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # 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/v1/{parent=organizations/*/locations/*}/firewallEndpoints" - % client.transport._host, - args[1], + +@pytest.mark.asyncio +async def test_list_firewall_endpoint_associations_async_pager(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_firewall_endpoint_associations( + 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, firewall_activation.FirewallEndpointAssociation) + for i in responses + ) -def test_create_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + +@pytest.mark.asyncio +async def test_list_firewall_endpoint_associations_async_pages(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_firewall_endpoint_associations(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", + [ + firewall_activation.GetFirewallEndpointAssociationRequest(), + {}, + ], +) +def test_get_firewall_endpoint_association(request_type, transport: str = "grpc"): client = FirewallActivationClient( 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_firewall_endpoint( - firewall_activation.CreateFirewallEndpointRequest(), - parent="parent_value", - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - firewall_endpoint_id="firewall_endpoint_id_value", + # Everything is optional 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_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = firewall_activation.FirewallEndpointAssociation( + name="name_value", + state=firewall_activation.FirewallEndpointAssociation.State.CREATING, + network="network_value", + firewall_endpoint="firewall_endpoint_value", + tls_inspection_policy="tls_inspection_policy_value", + reconciling=True, + disabled=True, ) + response = client.get_firewall_endpoint_association(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.GetFirewallEndpointAssociationRequest() + assert args[0] == request -def test_delete_firewall_endpoint_rest_use_cached_wrapped_rpc(): + # Establish that the response is the type that we expect. + assert isinstance(response, firewall_activation.FirewallEndpointAssociation) + assert response.name == "name_value" + assert ( + response.state == firewall_activation.FirewallEndpointAssociation.State.CREATING + ) + assert response.network == "network_value" + assert response.firewall_endpoint == "firewall_endpoint_value" + assert response.tls_inspection_policy == "tls_inspection_policy_value" + assert response.reconciling is True + assert response.disabled is True + + +def test_get_firewall_endpoint_association_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 = FirewallActivationClient( + 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 = firewall_activation.GetFirewallEndpointAssociationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_firewall_endpoint_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointAssociationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_firewall_endpoint_association_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 = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -6126,7 +6074,7 @@ def test_delete_firewall_endpoint_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_firewall_endpoint + client._transport.get_firewall_endpoint_association in client._transport._wrapped_methods ) @@ -6136,183 +6084,357 @@ def test_delete_firewall_endpoint_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_firewall_endpoint + client._transport.get_firewall_endpoint_association ] = mock_rpc - request = {} - client.delete_firewall_endpoint(request) + client.get_firewall_endpoint_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_firewall_endpoint(request) + client.get_firewall_endpoint_association(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_firewall_endpoint_rest_required_fields( - request_type=firewall_activation.DeleteFirewallEndpointRequest, +@pytest.mark.asyncio +async def test_get_firewall_endpoint_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.FirewallActivationRestTransport - - 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) - ) + # Clients should use _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 = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_firewall_endpoint._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.get_firewall_endpoint_association + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # 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_firewall_endpoint_association + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.get_firewall_endpoint_association(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_firewall_endpoint._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_firewall_endpoint_association(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 +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.GetFirewallEndpointAssociationRequest(), + {}, + ], +) +async def test_get_firewall_endpoint_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = FirewallActivationAsyncClient( + 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_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpointAssociation( + name="name_value", + state=firewall_activation.FirewallEndpointAssociation.State.CREATING, + network="network_value", + firewall_endpoint="firewall_endpoint_value", + tls_inspection_policy="tls_inspection_policy_value", + reconciling=True, + disabled=True, + ) + ) + response = await client.get_firewall_endpoint_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = firewall_activation.GetFirewallEndpointAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall_activation.FirewallEndpointAssociation) + assert response.name == "name_value" + assert ( + response.state == firewall_activation.FirewallEndpointAssociation.State.CREATING + ) + assert response.network == "network_value" + assert response.firewall_endpoint == "firewall_endpoint_value" + assert response.tls_inspection_policy == "tls_inspection_policy_value" + assert response.reconciling is True + assert response.disabled is True - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_get_firewall_endpoint_association_field_headers(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.GetFirewallEndpointAssociationRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = firewall_activation.FirewallEndpointAssociation() + client.get_firewall_endpoint_association(request) - response = client.delete_firewall_endpoint(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_firewall_endpoint_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_firewall_endpoint_association_field_headers_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_firewall_endpoint._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.GetFirewallEndpointAssociationRequest() + request.name = "name_value" -def test_delete_firewall_endpoint_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpointAssociation() + ) + await client.get_firewall_endpoint_association(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_firewall_endpoint_association_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = firewall_activation.FirewallEndpointAssociation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_firewall_endpoint_association( name="name_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_firewall_endpoint(**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/v1/{name=organizations/*/locations/*/firewallEndpoints/*}" - % client.transport._host, - args[1], - ) + 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_firewall_endpoint_rest_flattened_error(transport: str = "rest"): +def test_get_firewall_endpoint_association_flattened_error(): client = FirewallActivationClient( 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_firewall_endpoint( - firewall_activation.DeleteFirewallEndpointRequest(), + client.get_firewall_endpoint_association( + firewall_activation.GetFirewallEndpointAssociationRequest(), name="name_value", ) -def test_update_firewall_endpoint_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - +@pytest.mark.asyncio +async def test_get_firewall_endpoint_association_flattened_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = firewall_activation.FirewallEndpointAssociation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpointAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_firewall_endpoint_association( + 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_firewall_endpoint_association_flattened_error_async(): + client = FirewallActivationAsyncClient( + 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_firewall_endpoint_association( + firewall_activation.GetFirewallEndpointAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.CreateFirewallEndpointAssociationRequest(), + {}, + ], +) +def test_create_firewall_endpoint_association(request_type, transport: str = "grpc"): + client = FirewallActivationClient( + 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_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_firewall_endpoint_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.CreateFirewallEndpointAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_firewall_endpoint_association_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 = FirewallActivationClient( + 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 = firewall_activation.CreateFirewallEndpointAssociationRequest( + parent="parent_value", + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_firewall_endpoint_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest( + parent="parent_value", + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + request_id="request_id_value", + ) + assert args[0] == request_msg + + +def test_create_firewall_endpoint_association_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 = FirewallActivationClient( + 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_firewall_endpoint + client._transport.create_firewall_endpoint_association in client._transport._wrapped_methods ) @@ -6322,664 +6444,716 @@ def test_update_firewall_endpoint_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_firewall_endpoint + client._transport.create_firewall_endpoint_association ] = mock_rpc - request = {} - client.update_firewall_endpoint(request) + client.create_firewall_endpoint_association(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 + # 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.update_firewall_endpoint(request) + client.create_firewall_endpoint_association(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_firewall_endpoint_rest_required_fields( - request_type=firewall_activation.UpdateFirewallEndpointRequest, +@pytest.mark.asyncio +async def test_create_firewall_endpoint_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.FirewallActivationRestTransport - - 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_firewall_endpoint._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Clients should use _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 = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify required fields with default values are now present + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_firewall_endpoint._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", + # Ensure method has been cached + assert ( + client._client._transport.create_firewall_endpoint_association + in client._client._transport._wrapped_methods ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # 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_firewall_endpoint_association + ] = mock_rpc - # 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": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + request = {} + await client.create_firewall_endpoint_association(request) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # 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() - response = client.update_firewall_endpoint(request) + await client.create_firewall_endpoint_association(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_firewall_endpoint_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.CreateFirewallEndpointAssociationRequest(), + {}, + ], +) +async def test_create_firewall_endpoint_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = transport.update_firewall_endpoint._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "updateMask", - "firewallEndpoint", - ) + # Everything is optional 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_firewall_endpoint_association), "__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_firewall_endpoint_association(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = firewall_activation.CreateFirewallEndpointAssociationRequest() + assert args[0] == request -def test_update_firewall_endpoint_rest_flattened(): + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_firewall_endpoint_association_field_headers(): client = FirewallActivationClient( 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") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.CreateFirewallEndpointAssociationRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "firewall_endpoint": { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" - } - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_firewall_endpoint_association(request) + + # Establish that the 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_firewall_endpoint_association_field_headers_async(): + client = FirewallActivationAsyncClient( + 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 = firewall_activation.CreateFirewallEndpointAssociationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_firewall_endpoint_association(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"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_firewall_endpoint(**mock_args) + # 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_firewall_endpoint_association_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__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_firewall_endpoint_association( + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + ) # 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/v1/{firewall_endpoint.name=organizations/*/locations/*/firewallEndpoints/*}" - % client.transport._host, - args[1], - ) + 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].firewall_endpoint_association + mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") + assert arg == mock_val + arg = args[0].firewall_endpoint_association_id + mock_val = "firewall_endpoint_association_id_value" + assert arg == mock_val -def test_update_firewall_endpoint_rest_flattened_error(transport: str = "rest"): +def test_create_firewall_endpoint_association_flattened_error(): client = FirewallActivationClient( 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_firewall_endpoint( - firewall_activation.UpdateFirewallEndpointRequest(), - firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_firewall_endpoint_association( + firewall_activation.CreateFirewallEndpointAssociationRequest(), + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", ) -def test_list_firewall_endpoint_associations_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_create_firewall_endpoint_association_flattened_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Ensure method has been cached - assert ( - client._transport.list_firewall_endpoint_associations - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_firewall_endpoint_association( + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", ) - client._transport._wrapped_methods[ - client._transport.list_firewall_endpoint_associations - ] = mock_rpc - - request = {} - client.list_firewall_endpoint_associations(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # 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].firewall_endpoint_association + mock_val = firewall_activation.FirewallEndpointAssociation(name="name_value") + assert arg == mock_val + arg = args[0].firewall_endpoint_association_id + mock_val = "firewall_endpoint_association_id_value" + assert arg == mock_val - client.list_firewall_endpoint_associations(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_firewall_endpoint_association_flattened_error_async(): + client = FirewallActivationAsyncClient( + 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_firewall_endpoint_association( + firewall_activation.CreateFirewallEndpointAssociationRequest(), + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + ) -def test_list_firewall_endpoint_associations_rest_required_fields( - request_type=firewall_activation.ListFirewallEndpointAssociationsRequest, -): - transport_class = transports.FirewallActivationRestTransport - 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) +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.DeleteFirewallEndpointAssociationRequest(), + {}, + ], +) +def test_delete_firewall_endpoint_association(request_type, transport: str = "grpc"): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_firewall_endpoint_associations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Everything is optional 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 - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_firewall_endpoint_association(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.DeleteFirewallEndpointAssociationRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_firewall_endpoint_associations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_delete_firewall_endpoint_association_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 = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = firewall_activation.ListFirewallEndpointAssociationsResponse() - # 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 = ( - firewall_activation.ListFirewallEndpointAssociationsResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) + # 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 = firewall_activation.DeleteFirewallEndpointAssociationRequest( + name="name_value", + request_id="request_id_value", + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_firewall_endpoint_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest( + name="name_value", + request_id="request_id_value", + ) + assert args[0] == request_msg - response = client.list_firewall_endpoint_associations(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +def test_delete_firewall_endpoint_association_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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_list_firewall_endpoint_associations_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Ensure method has been cached + assert ( + client._transport.delete_firewall_endpoint_association + in client._transport._wrapped_methods + ) - unset_fields = ( - transport.list_firewall_endpoint_associations._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # 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. ) - & set(("parent",)) - ) + client._transport._wrapped_methods[ + client._transport.delete_firewall_endpoint_association + ] = mock_rpc + request = {} + client.delete_firewall_endpoint_association(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_list_firewall_endpoint_associations_rest_flattened(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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() - # 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 = firewall_activation.ListFirewallEndpointAssociationsResponse() + client.delete_firewall_endpoint_association(request) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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 = firewall_activation.ListFirewallEndpointAssociationsResponse.pb( - return_value +@pytest.mark.asyncio +async def test_delete_firewall_endpoint_association_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 = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_firewall_endpoint_associations(**mock_args) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # 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/v1/{parent=projects/*/locations/*}/firewallEndpointAssociations" - % client.transport._host, - args[1], + # Ensure method has been cached + assert ( + client._client._transport.delete_firewall_endpoint_association + 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_firewall_endpoint_association + ] = mock_rpc -def test_list_firewall_endpoint_associations_rest_flattened_error( - transport: str = "rest", -): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + request = {} + await client.delete_firewall_endpoint_association(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_firewall_endpoint_associations( - firewall_activation.ListFirewallEndpointAssociationsRequest(), - parent="parent_value", - ) + # 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() -def test_list_firewall_endpoint_associations_rest_pager(transport: str = "rest"): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + await client.delete_firewall_endpoint_association(request) - # 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 = ( - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="abc", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[], - next_page_token="def", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - ], - next_page_token="ghi", - ), - firewall_activation.ListFirewallEndpointAssociationsResponse( - firewall_endpoint_associations=[ - firewall_activation.FirewallEndpointAssociation(), - firewall_activation.FirewallEndpointAssociation(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Wrap the values into proper Response objs - response = tuple( - firewall_activation.ListFirewallEndpointAssociationsResponse.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"} +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.DeleteFirewallEndpointAssociationRequest(), + {}, + ], +) +async def test_delete_firewall_endpoint_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - pager = client.list_firewall_endpoint_associations(request=sample_request) + # Everything is optional 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 - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, firewall_activation.FirewallEndpointAssociation) - for i in results + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + response = await client.delete_firewall_endpoint_association(request) - pages = list( - client.list_firewall_endpoint_associations(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = firewall_activation.DeleteFirewallEndpointAssociationRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_firewall_endpoint_association_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 = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_delete_firewall_endpoint_association_field_headers(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Ensure method has been cached - assert ( - client._transport.get_firewall_endpoint_association - in client._transport._wrapped_methods - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.DeleteFirewallEndpointAssociationRequest() - # 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_firewall_endpoint_association - ] = mock_rpc + request.name = "name_value" - request = {} - client.get_firewall_endpoint_association(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_firewall_endpoint_association(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_firewall_endpoint_association(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + 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"] -def test_get_firewall_endpoint_association_rest_required_fields( - request_type=firewall_activation.GetFirewallEndpointAssociationRequest, -): - transport_class = transports.FirewallActivationRestTransport - 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) +@pytest.mark.asyncio +async def test_delete_firewall_endpoint_association_field_headers_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.DeleteFirewallEndpointAssociationRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_firewall_endpoint_association._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + request.name = "name_value" - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_firewall_endpoint_association(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_firewall_endpoint_association._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_delete_firewall_endpoint_association_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = firewall_activation.FirewallEndpointAssociation() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_firewall_endpoint_association( + name="name_value", + ) - response_value = Response() - response_value.status_code = 200 + # 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 - # Convert return value to protobuf type - return_value = firewall_activation.FirewallEndpointAssociation.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"} +def test_delete_firewall_endpoint_association_flattened_error(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - response = client.get_firewall_endpoint_association(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_firewall_endpoint_association( + firewall_activation.DeleteFirewallEndpointAssociationRequest(), + name="name_value", + ) -def test_get_firewall_endpoint_association_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_delete_firewall_endpoint_association_flattened_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = ( - transport.get_firewall_endpoint_association._get_unset_required_fields({}) - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_firewall_endpoint_association( + name="name_value", + ) -def test_get_firewall_endpoint_association_rest_flattened(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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 - # 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 = firewall_activation.FirewallEndpointAssociation() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/sample3" - } +@pytest.mark.asyncio +async def test_delete_firewall_endpoint_association_flattened_error_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) - # get truthy value for each flattened field - mock_args = dict( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_firewall_endpoint_association( + firewall_activation.DeleteFirewallEndpointAssociationRequest(), 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 = firewall_activation.FirewallEndpointAssociation.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_firewall_endpoint_association(**mock_args) +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.UpdateFirewallEndpointAssociationRequest(), + {}, + ], +) +def test_update_firewall_endpoint_association(request_type, transport: str = "grpc"): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # 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/v1/{name=projects/*/locations/*/firewallEndpointAssociations/*}" - % client.transport._host, - args[1], - ) + # Everything is optional 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_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_firewall_endpoint_association(request) -def test_get_firewall_endpoint_association_rest_flattened_error( - transport: str = "rest", -): + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_firewall_endpoint_association_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 = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_firewall_endpoint_association( - firewall_activation.GetFirewallEndpointAssociationRequest(), - name="name_value", + # 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 = firewall_activation.UpdateFirewallEndpointAssociationRequest( + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_firewall_endpoint_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest( + request_id="request_id_value", ) + assert args[0] == request_msg -def test_create_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): +def test_update_firewall_endpoint_association_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 = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -6988,7 +7162,7 @@ def test_create_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_firewall_endpoint_association + client._transport.update_firewall_endpoint_association in client._transport._wrapped_methods ) @@ -6998,197 +7172,283 @@ def test_create_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_firewall_endpoint_association + client._transport.update_firewall_endpoint_association ] = mock_rpc - request = {} - client.create_firewall_endpoint_association(request) + client.update_firewall_endpoint_association(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 + # 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_firewall_endpoint_association(request) + client.update_firewall_endpoint_association(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_firewall_endpoint_association_rest_required_fields( - request_type=firewall_activation.CreateFirewallEndpointAssociationRequest, +@pytest.mark.asyncio +async def test_update_firewall_endpoint_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.FirewallActivationRestTransport + # Clients should use _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 = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.update_firewall_endpoint_association + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_firewall_endpoint_association._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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_firewall_endpoint_association + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_firewall_endpoint_association(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_firewall_endpoint_association._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "firewall_endpoint_association_id", - "request_id", - ) - ) - jsonified_request.update(unset_fields) + # 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() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.update_firewall_endpoint_association(request) - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # 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) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.UpdateFirewallEndpointAssociationRequest(), + {}, + ], +) +async def test_update_firewall_endpoint_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional 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 - response = client.create_firewall_endpoint_association(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__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.update_firewall_endpoint_association(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_firewall_endpoint_association_rest_unset_required_fields(): - transport = transports.FirewallActivationRestTransport( - credentials=ga_credentials.AnonymousCredentials + +def test_update_firewall_endpoint_association_field_headers(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = ( - transport.create_firewall_endpoint_association._get_unset_required_fields({}) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + + request.firewall_endpoint_association.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_firewall_endpoint_association(request) + + # Establish that the 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", + "firewall_endpoint_association.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_firewall_endpoint_association_field_headers_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) - assert set(unset_fields) == ( - set( - ( - "firewallEndpointAssociationId", - "requestId", - ) - ) - & set( - ( - "parent", - "firewallEndpointAssociation", - ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = firewall_activation.UpdateFirewallEndpointAssociationRequest() + + request.firewall_endpoint_association.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - ) + await client.update_firewall_endpoint_association(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", + "firewall_endpoint_association.name=name_value", + ) in kw["metadata"] -def test_create_firewall_endpoint_association_rest_flattened(): +def test_update_firewall_endpoint_association_flattened(): client = FirewallActivationClient( 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") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__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.update_firewall_endpoint_association( + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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].firewall_endpoint_association + mock_val = firewall_activation.FirewallEndpointAssociation(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 - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + +def test_update_firewall_endpoint_association_flattened_error(): + client = FirewallActivationClient( + 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_firewall_endpoint_association( + firewall_activation.UpdateFirewallEndpointAssociationRequest(), firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( name="name_value" ), - firewall_endpoint_association_id="firewall_endpoint_association_id_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 - json_return_value = json_format.MessageToJson(return_value) - response_value._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_firewall_endpoint_association(**mock_args) +@pytest.mark.asyncio +async def test_update_firewall_endpoint_association_flattened_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__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.update_firewall_endpoint_association( + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/firewallEndpointAssociations" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].firewall_endpoint_association + mock_val = firewall_activation.FirewallEndpointAssociation(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_create_firewall_endpoint_association_rest_flattened_error( - transport: str = "rest", -): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_update_firewall_endpoint_association_flattened_error_async(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_firewall_endpoint_association( - firewall_activation.CreateFirewallEndpointAssociationRequest(), - parent="parent_value", + await client.update_firewall_endpoint_association( + firewall_activation.UpdateFirewallEndpointAssociationRequest(), firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( name="name_value" ), - firewall_endpoint_association_id="firewall_endpoint_association_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): +def test_list_firewall_endpoints_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: @@ -7203,7 +7463,7 @@ def test_delete_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_firewall_endpoint_association + client._transport.list_firewall_endpoints in client._transport._wrapped_methods ) @@ -7213,33 +7473,29 @@ def test_delete_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_firewall_endpoint_association + client._transport.list_firewall_endpoints ] = mock_rpc request = {} - client.delete_firewall_endpoint_association(request) + client.list_firewall_endpoints(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_firewall_endpoint_association(request) + client.list_firewall_endpoints(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_firewall_endpoint_association_rest_required_fields( - request_type=firewall_activation.DeleteFirewallEndpointAssociationRequest, +def test_list_firewall_endpoints_rest_required_fields( + request_type=firewall_activation.ListFirewallEndpointsRequest, ): transport_class = transports.FirewallActivationRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7250,23 +7506,30 @@ def test_delete_firewall_endpoint_association_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + ).list_firewall_endpoints._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + ).list_firewall_endpoints._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7275,7 +7538,7 @@ def test_delete_firewall_endpoint_association_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = firewall_activation.ListFirewallEndpointsResponse() # 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 @@ -7287,38 +7550,51 @@ def test_delete_firewall_endpoint_association_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = firewall_activation.ListFirewallEndpointsResponse.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.delete_firewall_endpoint_association(request) + response = client.list_firewall_endpoints(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_firewall_endpoint_association_rest_unset_required_fields(): +def test_list_firewall_endpoints_rest_unset_required_fields(): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.delete_firewall_endpoint_association._get_unset_required_fields({}) + unset_fields = transport.list_firewall_endpoints._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) ) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) -def test_delete_firewall_endpoint_association_rest_flattened(): +def test_list_firewall_endpoints_rest_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7327,43 +7603,43 @@ def test_delete_firewall_endpoint_association_rest_flattened(): # 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") + return_value = firewall_activation.ListFirewallEndpointsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/sample3" - } + sample_request = {"parent": "organizations/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = firewall_activation.ListFirewallEndpointsResponse.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.delete_firewall_endpoint_association(**mock_args) + client.list_firewall_endpoints(**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/v1/{name=projects/*/locations/*/firewallEndpointAssociations/*}" + "%s/v1/{parent=organizations/*/locations/*}/firewallEndpoints" % client.transport._host, args[1], ) -def test_delete_firewall_endpoint_association_rest_flattened_error( - transport: str = "rest", -): +def test_list_firewall_endpoints_rest_flattened_error(transport: str = "rest"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7372,13 +7648,77 @@ def test_delete_firewall_endpoint_association_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_firewall_endpoint_association( - firewall_activation.DeleteFirewallEndpointAssociationRequest(), - name="name_value", + client.list_firewall_endpoints( + firewall_activation.ListFirewallEndpointsRequest(), + parent="parent_value", ) -def test_update_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): +def test_list_firewall_endpoints_rest_pager(transport: str = "rest"): + client = FirewallActivationClient( + 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 = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + firewall_activation.ListFirewallEndpointsResponse.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": "organizations/sample1/locations/sample2"} + + pager = client.list_firewall_endpoints(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, firewall_activation.FirewallEndpoint) for i in results) + + pages = list(client.list_firewall_endpoints(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_project_firewall_endpoints_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: @@ -7393,7 +7733,7 @@ def test_update_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_firewall_endpoint_association + client._transport.list_project_firewall_endpoints in client._transport._wrapped_methods ) @@ -7403,32 +7743,29 @@ def test_update_firewall_endpoint_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_firewall_endpoint_association + client._transport.list_project_firewall_endpoints ] = mock_rpc request = {} - client.update_firewall_endpoint_association(request) + client.list_project_firewall_endpoints(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.update_firewall_endpoint_association(request) + client.list_project_firewall_endpoints(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_firewall_endpoint_association_rest_required_fields( - request_type=firewall_activation.UpdateFirewallEndpointAssociationRequest, +def test_list_project_firewall_endpoints_rest_required_fields( + request_type=firewall_activation.ListFirewallEndpointsRequest, ): transport_class = transports.FirewallActivationRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7439,24 +7776,30 @@ def test_update_firewall_endpoint_association_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + ).list_project_firewall_endpoints._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() - ).update_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + ).list_project_firewall_endpoints._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "request_id", - "update_mask", + "filter", + "order_by", + "page_size", + "page_token", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7465,7 +7808,7 @@ def test_update_firewall_endpoint_association_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = firewall_activation.ListFirewallEndpointsResponse() # 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 @@ -7477,52 +7820,53 @@ def test_update_firewall_endpoint_association_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "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 = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoint_association(request) + response = client.list_project_firewall_endpoints(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_firewall_endpoint_association_rest_unset_required_fields(): +def test_list_project_firewall_endpoints_rest_unset_required_fields(): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.update_firewall_endpoint_association._get_unset_required_fields({}) + unset_fields = transport.list_project_firewall_endpoints._get_unset_required_fields( + {} ) assert set(unset_fields) == ( set( ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "updateMask", - "firewallEndpointAssociation", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) -def test_update_firewall_endpoint_association_rest_flattened(): +def test_list_project_firewall_endpoints_rest_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7531,48 +7875,43 @@ def test_update_firewall_endpoint_association_rest_flattened(): # 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") + return_value = firewall_activation.ListFirewallEndpointsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "firewall_endpoint_association": { - "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/sample3" - } - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + 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 = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoint_association(**mock_args) + client.list_project_firewall_endpoints(**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/v1/{firewall_endpoint_association.name=projects/*/locations/*/firewallEndpointAssociations/*}" + "%s/v1/{parent=projects/*/locations/*}/firewallEndpoints" % client.transport._host, args[1], ) -def test_update_firewall_endpoint_association_rest_flattened_error( - transport: str = "rest", -): +def test_list_project_firewall_endpoints_rest_flattened_error(transport: str = "rest"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7581,655 +7920,4469 @@ def test_update_firewall_endpoint_association_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_firewall_endpoint_association( - firewall_activation.UpdateFirewallEndpointAssociationRequest(), - firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( - 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.FirewallActivationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + client.list_project_firewall_endpoints( + firewall_activation.ListFirewallEndpointsRequest(), + parent="parent_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.FirewallActivationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FirewallActivationClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.FirewallActivationGrpcTransport( +def test_list_project_firewall_endpoints_rest_pager(transport: str = "rest"): + client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = FirewallActivationClient( - 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 = FirewallActivationClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # 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 = ( + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointsResponse( + firewall_endpoints=[ + firewall_activation.FirewallEndpoint(), + firewall_activation.FirewallEndpoint(), + ], + ), ) + # Two responses for two calls + response = response + response - # It is an error to provide scopes and a transport instance. - transport = transports.FirewallActivationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): + # Wrap the values into proper Response objs + response = tuple( + firewall_activation.ListFirewallEndpointsResponse.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_project_firewall_endpoints(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, firewall_activation.FirewallEndpoint) for i in results) + + pages = list( + client.list_project_firewall_endpoints(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_firewall_endpoint_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 = FirewallActivationClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FirewallActivationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FirewallActivationClient(transport=transport) - assert client.transport is transport + # Ensure method has been cached + assert ( + client._transport.get_firewall_endpoint + 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_firewall_endpoint] = ( + mock_rpc + ) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FirewallActivationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + request = {} + client.get_firewall_endpoint(request) - transport = transports.FirewallActivationGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_firewall_endpoint(request) -@pytest.mark.parametrize( - "transport_class", - [ - transports.FirewallActivationGrpcTransport, - transports.FirewallActivationGrpcAsyncIOTransport, - transports.FirewallActivationRestTransport, - ], -) -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() + # 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_transport_kind_grpc(): - transport = FirewallActivationClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() +def test_get_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.GetFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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) ) - assert transport.kind == "grpc" + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_firewall_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_initialize_client_w_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_firewall_endpoint._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" -# 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_firewall_endpoints_empty_call_grpc(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoints), "__call__" - ) as call: - call.return_value = firewall_activation.ListFirewallEndpointsResponse() - client.list_firewall_endpoints(request=None) + # Designate an appropriate value for the returned response. + return_value = firewall_activation.FirewallEndpoint() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.ListFirewallEndpointsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = firewall_activation.FirewallEndpoint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -# 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_firewall_endpoint_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" - ) as call: - call.return_value = firewall_activation.FirewallEndpoint() - client.get_firewall_endpoint(request=None) + response = client.get_firewall_endpoint(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_firewall_endpoint_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_firewall_endpoint(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointRequest() - assert args[0] == request_msg + unset_fields = transport.get_firewall_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -# 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_firewall_endpoint_empty_call_grpc(): +def test_get_firewall_endpoint_rest_flattened(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_firewall_endpoint(request=None) + # 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 = firewall_activation.FirewallEndpoint() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -# 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_firewall_endpoint_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = firewall_activation.FirewallEndpoint.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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_firewall_endpoint(request=None) + client.get_firewall_endpoint(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointRequest() - assert args[0] == request_msg + # 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/v1/{name=organizations/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], + ) -# 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_firewall_endpoint_associations_empty_call_grpc(): +def test_get_firewall_endpoint_rest_flattened_error(transport: str = "rest"): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" - ) as call: - call.return_value = ( - firewall_activation.ListFirewallEndpointAssociationsResponse() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), + name="name_value", ) - client.list_firewall_endpoint_associations(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest() - assert args[0] == request_msg +def test_get_project_firewall_endpoint_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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_firewall_endpoint_association_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" - ) as call: - call.return_value = firewall_activation.FirewallEndpointAssociation() - client.get_firewall_endpoint_association(request=None) + # Ensure method has been cached + assert ( + client._transport.get_project_firewall_endpoint + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointAssociationRequest() - assert args[0] == request_msg + # 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_project_firewall_endpoint + ] = mock_rpc + request = {} + client.get_project_firewall_endpoint(request) -# 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_firewall_endpoint_association_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_firewall_endpoint_association(request=None) + client.get_project_firewall_endpoint(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest() - assert args[0] == request_msg + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# 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_firewall_endpoint_association_empty_call_grpc(): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_project_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.GetFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_firewall_endpoint_association(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest() - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_project_firewall_endpoint._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_project_firewall_endpoint._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" -# 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_firewall_endpoint_association_empty_call_grpc(): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_firewall_endpoint_association(request=None) + # Designate an appropriate value for the returned response. + return_value = firewall_activation.FirewallEndpoint() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = firewall_activation.FirewallEndpoint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_transport_kind_grpc_asyncio(): - transport = FirewallActivationAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + response_value._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_project_firewall_endpoint(request) -def test_initialize_client_w_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_firewall_endpoints_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_project_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoints), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.ListFirewallEndpointsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_firewall_endpoints(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.ListFirewallEndpointsRequest() - assert args[0] == request_msg + unset_fields = transport.get_project_firewall_endpoint._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) -# 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_firewall_endpoint_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_project_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_endpoint), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpoint( - name="name_value", - description="description_value", - state=firewall_activation.FirewallEndpoint.State.CREATING, - reconciling=True, - associated_networks=["associated_networks_value"], - satisfies_pzs=True, - satisfies_pzi=True, - billing_project_id="billing_project_id_value", - ) - ) - await client.get_firewall_endpoint(request=None) + # 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 = firewall_activation.FirewallEndpoint() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/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 = firewall_activation.FirewallEndpoint.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"} -# 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_firewall_endpoint_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.get_project_firewall_endpoint(**mock_args) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_endpoint), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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/v1/{name=projects/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], ) - await client.create_firewall_endpoint(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointRequest() - assert args[0] == request_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_firewall_endpoint_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_project_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_endpoint), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_project_firewall_endpoint( + firewall_activation.GetFirewallEndpointRequest(), + name="name_value", ) - await client.delete_firewall_endpoint(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointRequest() - assert args[0] == request_msg +def test_create_firewall_endpoint_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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_firewall_endpoint_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_endpoint), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert ( + client._transport.create_firewall_endpoint + in client._transport._wrapped_methods ) - await client.update_firewall_endpoint(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointRequest() - assert args[0] == request_msg + # 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_firewall_endpoint + ] = mock_rpc + request = {} + client.create_firewall_endpoint(request) -# 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_firewall_endpoint_associations_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_firewall_endpoint_associations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.ListFirewallEndpointAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_firewall_endpoint_associations(request=None) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest() - assert args[0] == request_msg + client.create_firewall_endpoint(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# 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_firewall_endpoint_association_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_create_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.CreateFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["firewall_endpoint_id"] = "" + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_firewall_endpoint_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - firewall_activation.FirewallEndpointAssociation( - name="name_value", - state=firewall_activation.FirewallEndpointAssociation.State.CREATING, - network="network_value", - firewall_endpoint="firewall_endpoint_value", - tls_inspection_policy="tls_inspection_policy_value", - reconciling=True, - disabled=True, - ) - ) - await client.get_firewall_endpoint_association(request=None) + # verify fields with default values are dropped + assert "firewallEndpointId" not in jsonified_request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.GetFirewallEndpointAssociationRequest() - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_firewall_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "firewallEndpointId" in jsonified_request + assert ( + jsonified_request["firewallEndpointId"] == request_init["firewall_endpoint_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["firewallEndpointId"] = "firewall_endpoint_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "firewall_endpoint_id", + "request_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" + assert "firewallEndpointId" in jsonified_request + assert jsonified_request["firewallEndpointId"] == "firewall_endpoint_id_value" + + client = FirewallActivationClient( + 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_firewall_endpoint(request) + + expected_params = [ + ( + "firewallEndpointId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_firewall_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "firewallEndpointId", + "requestId", + ) + ) + & set( + ( + "parent", + "firewallEndpointId", + "firewallEndpoint", + ) + ) + ) + + +def test_create_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + 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": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_firewall_endpoint(**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/v1/{parent=organizations/*/locations/*}/firewallEndpoints" + % client.transport._host, + args[1], + ) + + +def test_create_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), + parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + +def test_create_project_firewall_endpoint_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 = FirewallActivationClient( + 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_project_firewall_endpoint + 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_project_firewall_endpoint + ] = mock_rpc + + request = {} + client.create_project_firewall_endpoint(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_project_firewall_endpoint(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_project_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.CreateFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["firewall_endpoint_id"] = "" + 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 + assert "firewallEndpointId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_project_firewall_endpoint._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "firewallEndpointId" in jsonified_request + assert ( + jsonified_request["firewallEndpointId"] == request_init["firewall_endpoint_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["firewallEndpointId"] = "firewall_endpoint_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_project_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "firewall_endpoint_id", + "request_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" + assert "firewallEndpointId" in jsonified_request + assert jsonified_request["firewallEndpointId"] == "firewall_endpoint_id_value" + + client = FirewallActivationClient( + 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_project_firewall_endpoint(request) + + expected_params = [ + ( + "firewallEndpointId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_project_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_project_firewall_endpoint._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "firewallEndpointId", + "requestId", + ) + ) + & set( + ( + "parent", + "firewallEndpointId", + "firewallEndpoint", + ) + ) + ) + + +def test_create_project_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_project_firewall_endpoint(**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/v1/{parent=projects/*/locations/*}/firewallEndpoints" + % client.transport._host, + args[1], + ) + + +def test_create_project_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_project_firewall_endpoint( + firewall_activation.CreateFirewallEndpointRequest(), + parent="parent_value", + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + firewall_endpoint_id="firewall_endpoint_id_value", + ) + + +def test_delete_firewall_endpoint_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 = FirewallActivationClient( + 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_firewall_endpoint + 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_firewall_endpoint + ] = mock_rpc + + request = {} + client.delete_firewall_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_firewall_endpoint(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_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.DeleteFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint._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_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_firewall_endpoint(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_firewall_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_firewall_endpoint(**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/v1/{name=organizations/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), + name="name_value", + ) + + +def test_delete_project_firewall_endpoint_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 = FirewallActivationClient( + 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_project_firewall_endpoint + 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_project_firewall_endpoint + ] = mock_rpc + + request = {} + client.delete_project_firewall_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_project_firewall_endpoint(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_project_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.DeleteFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_project_firewall_endpoint._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_project_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_project_firewall_endpoint(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_project_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_project_firewall_endpoint._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_project_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_project_firewall_endpoint(**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/v1/{name=projects/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_project_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_project_firewall_endpoint( + firewall_activation.DeleteFirewallEndpointRequest(), + name="name_value", + ) + + +def test_update_firewall_endpoint_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 = FirewallActivationClient( + 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_firewall_endpoint + 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_firewall_endpoint + ] = mock_rpc + + request = {} + client.update_firewall_endpoint(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.update_firewall_endpoint(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_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.UpdateFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint._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_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = FirewallActivationClient( + 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": "patch", + "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.update_firewall_endpoint(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_firewall_endpoint._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "firewallEndpoint", + ) + ) + ) + + +def test_update_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + 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 = { + "firewall_endpoint": { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + firewall_endpoint=firewall_activation.FirewallEndpoint(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_firewall_endpoint(**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/v1/{firewall_endpoint.name=organizations/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], + ) + + +def test_update_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_project_firewall_endpoint_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 = FirewallActivationClient( + 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_project_firewall_endpoint + 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_project_firewall_endpoint + ] = mock_rpc + + request = {} + client.update_project_firewall_endpoint(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.update_project_firewall_endpoint(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_project_firewall_endpoint_rest_required_fields( + request_type=firewall_activation.UpdateFirewallEndpointRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_project_firewall_endpoint._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_project_firewall_endpoint._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = FirewallActivationClient( + 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": "patch", + "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.update_project_firewall_endpoint(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_project_firewall_endpoint_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_project_firewall_endpoint._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "firewallEndpoint", + ) + ) + ) + + +def test_update_project_firewall_endpoint_rest_flattened(): + client = FirewallActivationClient( + 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 = { + "firewall_endpoint": { + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + firewall_endpoint=firewall_activation.FirewallEndpoint(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_project_firewall_endpoint(**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/v1/{firewall_endpoint.name=projects/*/locations/*/firewallEndpoints/*}" + % client.transport._host, + args[1], + ) + + +def test_update_project_firewall_endpoint_rest_flattened_error(transport: str = "rest"): + client = FirewallActivationClient( + 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_project_firewall_endpoint( + firewall_activation.UpdateFirewallEndpointRequest(), + firewall_endpoint=firewall_activation.FirewallEndpoint(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_firewall_endpoint_associations_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 = FirewallActivationClient( + 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_firewall_endpoint_associations + 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_firewall_endpoint_associations + ] = mock_rpc + + request = {} + client.list_firewall_endpoint_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firewall_endpoint_associations(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_firewall_endpoint_associations_rest_required_fields( + request_type=firewall_activation.ListFirewallEndpointAssociationsRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint_associations._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_firewall_endpoint_associations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = firewall_activation.ListFirewallEndpointAssociationsResponse() + # 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 = ( + firewall_activation.ListFirewallEndpointAssociationsResponse.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_firewall_endpoint_associations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_firewall_endpoint_associations_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_firewall_endpoint_associations._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_firewall_endpoint_associations_rest_flattened(): + client = FirewallActivationClient( + 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 = firewall_activation.ListFirewallEndpointAssociationsResponse() + + # 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 = firewall_activation.ListFirewallEndpointAssociationsResponse.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_firewall_endpoint_associations(**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/v1/{parent=projects/*/locations/*}/firewallEndpointAssociations" + % client.transport._host, + args[1], + ) + + +def test_list_firewall_endpoint_associations_rest_flattened_error( + transport: str = "rest", +): + client = FirewallActivationClient( + 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_firewall_endpoint_associations( + firewall_activation.ListFirewallEndpointAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_firewall_endpoint_associations_rest_pager(transport: str = "rest"): + client = FirewallActivationClient( + 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 = ( + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="abc", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[], + next_page_token="def", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + ], + next_page_token="ghi", + ), + firewall_activation.ListFirewallEndpointAssociationsResponse( + firewall_endpoint_associations=[ + firewall_activation.FirewallEndpointAssociation(), + firewall_activation.FirewallEndpointAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + firewall_activation.ListFirewallEndpointAssociationsResponse.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_firewall_endpoint_associations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, firewall_activation.FirewallEndpointAssociation) + for i in results + ) + + pages = list( + client.list_firewall_endpoint_associations(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_firewall_endpoint_association_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 = FirewallActivationClient( + 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_firewall_endpoint_association + 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_firewall_endpoint_association + ] = mock_rpc + + request = {} + client.get_firewall_endpoint_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_firewall_endpoint_association(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_firewall_endpoint_association_rest_required_fields( + request_type=firewall_activation.GetFirewallEndpointAssociationRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint_association._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_firewall_endpoint_association._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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = firewall_activation.FirewallEndpointAssociation() + # 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 = firewall_activation.FirewallEndpointAssociation.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_firewall_endpoint_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_firewall_endpoint_association_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_firewall_endpoint_association._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_firewall_endpoint_association_rest_flattened(): + client = FirewallActivationClient( + 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 = firewall_activation.FirewallEndpointAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/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 = firewall_activation.FirewallEndpointAssociation.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_firewall_endpoint_association(**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/v1/{name=projects/*/locations/*/firewallEndpointAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_firewall_endpoint_association_rest_flattened_error( + transport: str = "rest", +): + client = FirewallActivationClient( + 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_firewall_endpoint_association( + firewall_activation.GetFirewallEndpointAssociationRequest(), + name="name_value", + ) + + +def test_create_firewall_endpoint_association_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 = FirewallActivationClient( + 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_firewall_endpoint_association + 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_firewall_endpoint_association + ] = mock_rpc + + request = {} + client.create_firewall_endpoint_association(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_firewall_endpoint_association(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_firewall_endpoint_association_rest_required_fields( + request_type=firewall_activation.CreateFirewallEndpointAssociationRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint_association._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_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "firewall_endpoint_association_id", + "request_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 = FirewallActivationClient( + 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_firewall_endpoint_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_firewall_endpoint_association_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_firewall_endpoint_association._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "firewallEndpointAssociationId", + "requestId", + ) + ) + & set( + ( + "parent", + "firewallEndpointAssociation", + ) + ) + ) + + +def test_create_firewall_endpoint_association_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_firewall_endpoint_association(**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/v1/{parent=projects/*/locations/*}/firewallEndpointAssociations" + % client.transport._host, + args[1], + ) + + +def test_create_firewall_endpoint_association_rest_flattened_error( + transport: str = "rest", +): + client = FirewallActivationClient( + 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_firewall_endpoint_association( + firewall_activation.CreateFirewallEndpointAssociationRequest(), + parent="parent_value", + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + name="name_value" + ), + firewall_endpoint_association_id="firewall_endpoint_association_id_value", + ) + + +def test_delete_firewall_endpoint_association_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 = FirewallActivationClient( + 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_firewall_endpoint_association + 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_firewall_endpoint_association + ] = mock_rpc + + request = {} + client.delete_firewall_endpoint_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_firewall_endpoint_association(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_firewall_endpoint_association_rest_required_fields( + request_type=firewall_activation.DeleteFirewallEndpointAssociationRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint_association._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_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_firewall_endpoint_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_firewall_endpoint_association_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_firewall_endpoint_association._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_firewall_endpoint_association_rest_flattened(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_firewall_endpoint_association(**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/v1/{name=projects/*/locations/*/firewallEndpointAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_firewall_endpoint_association_rest_flattened_error( + transport: str = "rest", +): + client = FirewallActivationClient( + 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_firewall_endpoint_association( + firewall_activation.DeleteFirewallEndpointAssociationRequest(), + name="name_value", + ) + + +def test_update_firewall_endpoint_association_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 = FirewallActivationClient( + 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_firewall_endpoint_association + 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_firewall_endpoint_association + ] = mock_rpc + + request = {} + client.update_firewall_endpoint_association(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.update_firewall_endpoint_association(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_firewall_endpoint_association_rest_required_fields( + request_type=firewall_activation.UpdateFirewallEndpointAssociationRequest, +): + transport_class = transports.FirewallActivationRestTransport + + 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_firewall_endpoint_association._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_firewall_endpoint_association._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = FirewallActivationClient( + 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": "patch", + "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.update_firewall_endpoint_association(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_firewall_endpoint_association_rest_unset_required_fields(): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_firewall_endpoint_association._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "firewallEndpointAssociation", + ) + ) + ) + + +def test_update_firewall_endpoint_association_rest_flattened(): + client = FirewallActivationClient( + 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 = { + "firewall_endpoint_association": { + "name": "projects/sample1/locations/sample2/firewallEndpointAssociations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_firewall_endpoint_association(**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/v1/{firewall_endpoint_association.name=projects/*/locations/*/firewallEndpointAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_firewall_endpoint_association_rest_flattened_error( + transport: str = "rest", +): + client = FirewallActivationClient( + 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_firewall_endpoint_association( + firewall_activation.UpdateFirewallEndpointAssociationRequest(), + firewall_endpoint_association=firewall_activation.FirewallEndpointAssociation( + 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.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallActivationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FirewallActivationClient( + 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 = FirewallActivationClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallActivationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FirewallActivationClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FirewallActivationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FirewallActivationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FirewallActivationGrpcTransport, + transports.FirewallActivationGrpcAsyncIOTransport, + transports.FirewallActivationRestTransport, + ], +) +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 = FirewallActivationClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_firewall_endpoints_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoints), "__call__" + ) as call: + call.return_value = firewall_activation.ListFirewallEndpointsResponse() + client.list_firewall_endpoints(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointsRequest() + assert args[0] == request_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_project_firewall_endpoints_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_project_firewall_endpoints), "__call__" + ) as call: + call.return_value = firewall_activation.ListFirewallEndpointsResponse() + client.list_project_firewall_endpoints(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointsRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint), "__call__" + ) as call: + call.return_value = firewall_activation.FirewallEndpoint() + client.get_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_project_firewall_endpoint), "__call__" + ) as call: + call.return_value = firewall_activation.FirewallEndpoint() + client.get_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_project_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_project_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_project_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_project_firewall_endpoint), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_associations_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + call.return_value = ( + firewall_activation.ListFirewallEndpointAssociationsResponse() + ) + client.list_firewall_endpoint_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = firewall_activation.FirewallEndpointAssociation() + client.get_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_firewall_endpoint_association_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = FirewallActivationAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_firewall_endpoints_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_firewall_endpoints(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointsRequest() + assert args[0] == request_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_project_firewall_endpoints_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_project_firewall_endpoints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_project_firewall_endpoints(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointsRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) + ) + await client.get_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_project_firewall_endpoint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_value", + ) + ) + await client.get_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint), "__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_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_project_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_project_firewall_endpoint), "__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_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_project_firewall_endpoint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint), "__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.update_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointRequest() + assert args[0] == request_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_project_firewall_endpoint_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_project_firewall_endpoint), "__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.update_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_associations_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_firewall_endpoint_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.ListFirewallEndpointAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_firewall_endpoint_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointAssociationsRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + firewall_activation.FirewallEndpointAssociation( + name="name_value", + state=firewall_activation.FirewallEndpointAssociation.State.CREATING, + network="network_value", + firewall_endpoint="firewall_endpoint_value", + tls_inspection_policy="tls_inspection_policy_value", + reconciling=True, + disabled=True, + ) + ) + await client.get_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointAssociationRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_firewall_endpoint_association_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_firewall_endpoint_association), "__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_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_firewall_endpoint_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest() + assert args[0] == request_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_firewall_endpoint_association_empty_call_grpc_asyncio(): + client = FirewallActivationAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_firewall_endpoint_association), "__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.update_firewall_endpoint_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = FirewallActivationClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_firewall_endpoints_rest_bad_request( + request_type=firewall_activation.ListFirewallEndpointsRequest, +): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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_firewall_endpoints(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.ListFirewallEndpointsRequest, + dict, + ], +) +def test_list_firewall_endpoints_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoints(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirewallEndpointsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_firewall_endpoints_rest_interceptors(null_interceptor): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FirewallActivationRestInterceptor(), + ) + client = FirewallActivationClient(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.FirewallActivationRestInterceptor, "post_list_firewall_endpoints" + ) as post, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "post_list_firewall_endpoints_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FirewallActivationRestInterceptor, "pre_list_firewall_endpoints" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = firewall_activation.ListFirewallEndpointsRequest.pb( + firewall_activation.ListFirewallEndpointsRequest() + ) + 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 = firewall_activation.ListFirewallEndpointsResponse.to_json( + firewall_activation.ListFirewallEndpointsResponse() + ) + req.return_value.content = return_value + + request = firewall_activation.ListFirewallEndpointsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = firewall_activation.ListFirewallEndpointsResponse() + post_with_metadata.return_value = ( + firewall_activation.ListFirewallEndpointsResponse(), + metadata, + ) + + client.list_firewall_endpoints( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_project_firewall_endpoints_rest_bad_request( + request_type=firewall_activation.ListFirewallEndpointsRequest, +): + client = FirewallActivationClient( + 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_project_firewall_endpoints(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.ListFirewallEndpointsRequest, + dict, + ], +) +def test_list_project_firewall_endpoints_rest_call_success(request_type): + client = FirewallActivationClient( + 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 = firewall_activation.ListFirewallEndpointsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = firewall_activation.ListFirewallEndpointsResponse.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_project_firewall_endpoints(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectFirewallEndpointsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_project_firewall_endpoints_rest_interceptors(null_interceptor): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FirewallActivationRestInterceptor(), + ) + client = FirewallActivationClient(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.FirewallActivationRestInterceptor, + "post_list_project_firewall_endpoints", + ) as post, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "post_list_project_firewall_endpoints_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "pre_list_project_firewall_endpoints", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = firewall_activation.ListFirewallEndpointsRequest.pb( + firewall_activation.ListFirewallEndpointsRequest() + ) + 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 = firewall_activation.ListFirewallEndpointsResponse.to_json( + firewall_activation.ListFirewallEndpointsResponse() + ) + req.return_value.content = return_value + + request = firewall_activation.ListFirewallEndpointsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = firewall_activation.ListFirewallEndpointsResponse() + post_with_metadata.return_value = ( + firewall_activation.ListFirewallEndpointsResponse(), + metadata, + ) + + client.list_project_firewall_endpoints( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.GetFirewallEndpointRequest, +): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/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_firewall_endpoint(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.GetFirewallEndpointRequest, + dict, + ], +) +def test_get_firewall_endpoint_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/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 = firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_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 = firewall_activation.FirewallEndpoint.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_firewall_endpoint(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_firewall_endpoint_rest_interceptors(null_interceptor): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FirewallActivationRestInterceptor(), + ) + client = FirewallActivationClient(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.FirewallActivationRestInterceptor, "post_get_firewall_endpoint" + ) as post, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "post_get_firewall_endpoint_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FirewallActivationRestInterceptor, "pre_get_firewall_endpoint" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = firewall_activation.GetFirewallEndpointRequest.pb( + firewall_activation.GetFirewallEndpointRequest() + ) + 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 = firewall_activation.FirewallEndpoint.to_json( + firewall_activation.FirewallEndpoint() + ) + req.return_value.content = return_value + + request = firewall_activation.GetFirewallEndpointRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = firewall_activation.FirewallEndpoint() + post_with_metadata.return_value = ( + firewall_activation.FirewallEndpoint(), + metadata, + ) + + client.get_firewall_endpoint( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_project_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.GetFirewallEndpointRequest, +): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/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_project_firewall_endpoint(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.GetFirewallEndpointRequest, + dict, + ], +) +def test_get_project_firewall_endpoint_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/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 = firewall_activation.FirewallEndpoint( + name="name_value", + description="description_value", + state=firewall_activation.FirewallEndpoint.State.CREATING, + reconciling=True, + associated_networks=["associated_networks_value"], + satisfies_pzs=True, + satisfies_pzi=True, + billing_project_id="billing_project_id_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 = firewall_activation.FirewallEndpoint.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_project_firewall_endpoint(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall_activation.FirewallEndpoint) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == firewall_activation.FirewallEndpoint.State.CREATING + assert response.reconciling is True + assert response.associated_networks == ["associated_networks_value"] + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.billing_project_id == "billing_project_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_firewall_endpoint_rest_interceptors(null_interceptor): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FirewallActivationRestInterceptor(), + ) + client = FirewallActivationClient(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.FirewallActivationRestInterceptor, + "post_get_project_firewall_endpoint", + ) as post, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "post_get_project_firewall_endpoint_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "pre_get_project_firewall_endpoint", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = firewall_activation.GetFirewallEndpointRequest.pb( + firewall_activation.GetFirewallEndpointRequest() + ) + 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 = firewall_activation.FirewallEndpoint.to_json( + firewall_activation.FirewallEndpoint() + ) + req.return_value.content = return_value + + request = firewall_activation.GetFirewallEndpointRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = firewall_activation.FirewallEndpoint() + post_with_metadata.return_value = ( + firewall_activation.FirewallEndpoint(), + metadata, + ) + + client.get_project_firewall_endpoint( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.CreateFirewallEndpointRequest, +): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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_firewall_endpoint(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.CreateFirewallEndpointRequest, + dict, + ], +) +def test_create_firewall_endpoint_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init["firewall_endpoint"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "reconciling": True, + "associated_networks": [ + "associated_networks_value1", + "associated_networks_value2", + ], + "associations": [{"name": "name_value", "network": "network_value"}], + "satisfies_pzs": True, + "satisfies_pzi": True, + "billing_project_id": "billing_project_id_value", + "endpoint_settings": {"jumbo_frames_enabled": 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 = firewall_activation.CreateFirewallEndpointRequest.meta.fields[ + "firewall_endpoint" + ] + + 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) + ] -# 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_firewall_endpoint_association_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + subfields_not_in_runtime = [] - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_firewall_endpoint_association), "__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_firewall_endpoint_association(request=None) + # 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["firewall_endpoint"].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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.CreateFirewallEndpointAssociationRequest() - assert args[0] == request_msg + 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["firewall_endpoint"][field])): + del request_init["firewall_endpoint"][field][i][subfield] + else: + del request_init["firewall_endpoint"][field][subfield] + request = request_type(**request_init) -# 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_firewall_endpoint_association_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # 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") - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_firewall_endpoint_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_firewall_endpoint_association(request=None) + # 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_firewall_endpoint(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.DeleteFirewallEndpointAssociationRequest() - assert args[0] == request_msg + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) -# 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_firewall_endpoint_association_empty_call_grpc_asyncio(): - client = FirewallActivationAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_firewall_endpoint_rest_interceptors(null_interceptor): + transport = transports.FirewallActivationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FirewallActivationRestInterceptor(), ) + client = FirewallActivationClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_firewall_endpoint_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + 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.FirewallActivationRestInterceptor, + "post_create_firewall_endpoint", + ) as post, + mock.patch.object( + transports.FirewallActivationRestInterceptor, + "post_create_firewall_endpoint_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FirewallActivationRestInterceptor, "pre_create_firewall_endpoint" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = firewall_activation.CreateFirewallEndpointRequest.pb( + firewall_activation.CreateFirewallEndpointRequest() ) - await client.update_firewall_endpoint_association(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = firewall_activation.UpdateFirewallEndpointAssociationRequest() - assert args[0] == request_msg + 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 = firewall_activation.CreateFirewallEndpointRequest() + 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_firewall_endpoint( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = FirewallActivationClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_firewall_endpoints_rest_bad_request( - request_type=firewall_activation.ListFirewallEndpointsRequest, +def test_create_project_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.CreateFirewallEndpointRequest, ): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} + 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. @@ -8245,55 +12398,132 @@ def test_list_firewall_endpoints_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_firewall_endpoints(request) + client.create_project_firewall_endpoint(request) + + +@pytest.mark.parametrize( + "request_type", + [ + firewall_activation.CreateFirewallEndpointRequest, + dict, + ], +) +def test_create_project_firewall_endpoint_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["firewall_endpoint"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "reconciling": True, + "associated_networks": [ + "associated_networks_value1", + "associated_networks_value2", + ], + "associations": [{"name": "name_value", "network": "network_value"}], + "satisfies_pzs": True, + "satisfies_pzi": True, + "billing_project_id": "billing_project_id_value", + "endpoint_settings": {"jumbo_frames_enabled": 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 = firewall_activation.CreateFirewallEndpointRequest.meta.fields[ + "firewall_endpoint" + ] + + 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["firewall_endpoint"].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 -@pytest.mark.parametrize( - "request_type", - [ - firewall_activation.ListFirewallEndpointsRequest, - dict, - ], -) -def test_list_firewall_endpoints_rest_call_success(request_type): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + 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, + } + ) - # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} + # 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["firewall_endpoint"][field])): + del request_init["firewall_endpoint"][field][i][subfield] + else: + del request_init["firewall_endpoint"][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 = firewall_activation.ListFirewallEndpointsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + 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 - - # Convert return value to protobuf type - return_value = firewall_activation.ListFirewallEndpointsResponse.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_firewall_endpoints(request) + response = client.create_project_firewall_endpoint(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFirewallEndpointsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_firewall_endpoints_rest_interceptors(null_interceptor): +def test_create_project_firewall_endpoint_rest_interceptors(null_interceptor): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8305,22 +12535,25 @@ def test_list_firewall_endpoints_rest_interceptors(null_interceptor): 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.FirewallActivationRestInterceptor, "post_list_firewall_endpoints" + transports.FirewallActivationRestInterceptor, + "post_create_project_firewall_endpoint", ) as post, mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_list_firewall_endpoints_with_metadata", + "post_create_project_firewall_endpoint_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.FirewallActivationRestInterceptor, "pre_list_firewall_endpoints" + transports.FirewallActivationRestInterceptor, + "pre_create_project_firewall_endpoint", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = firewall_activation.ListFirewallEndpointsRequest.pb( - firewall_activation.ListFirewallEndpointsRequest() + pb_message = firewall_activation.CreateFirewallEndpointRequest.pb( + firewall_activation.CreateFirewallEndpointRequest() ) transcode.return_value = { "method": "post", @@ -8332,24 +12565,19 @@ def test_list_firewall_endpoints_rest_interceptors(null_interceptor): 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 = firewall_activation.ListFirewallEndpointsResponse.to_json( - firewall_activation.ListFirewallEndpointsResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = firewall_activation.ListFirewallEndpointsRequest() + request = firewall_activation.CreateFirewallEndpointRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = firewall_activation.ListFirewallEndpointsResponse() - post_with_metadata.return_value = ( - firewall_activation.ListFirewallEndpointsResponse(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_firewall_endpoints( + client.create_project_firewall_endpoint( request, metadata=[ ("key", "val"), @@ -8362,8 +12590,8 @@ def test_list_firewall_endpoints_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_firewall_endpoint_rest_bad_request( - request_type=firewall_activation.GetFirewallEndpointRequest, +def test_delete_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.DeleteFirewallEndpointRequest, ): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -8387,17 +12615,17 @@ def test_get_firewall_endpoint_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_firewall_endpoint(request) + client.delete_firewall_endpoint(request) @pytest.mark.parametrize( "request_type", [ - firewall_activation.GetFirewallEndpointRequest, + firewall_activation.DeleteFirewallEndpointRequest, dict, ], ) -def test_get_firewall_endpoint_rest_call_success(request_type): +def test_delete_firewall_endpoint_rest_call_success(request_type): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8411,43 +12639,23 @@ def test_get_firewall_endpoint_rest_call_success(request_type): # 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 = firewall_activation.FirewallEndpoint( - name="name_value", - description="description_value", - state=firewall_activation.FirewallEndpoint.State.CREATING, - reconciling=True, - associated_networks=["associated_networks_value"], - satisfies_pzs=True, - satisfies_pzi=True, - billing_project_id="billing_project_id_value", - ) + 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 - - # Convert return value to protobuf type - return_value = firewall_activation.FirewallEndpoint.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_firewall_endpoint(request) + response = client.delete_firewall_endpoint(request) # Establish that the response is the type that we expect. - assert isinstance(response, firewall_activation.FirewallEndpoint) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == firewall_activation.FirewallEndpoint.State.CREATING - assert response.reconciling is True - assert response.associated_networks == ["associated_networks_value"] - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.billing_project_id == "billing_project_id_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_firewall_endpoint_rest_interceptors(null_interceptor): +def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8459,22 +12667,24 @@ def test_get_firewall_endpoint_rest_interceptors(null_interceptor): 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.FirewallActivationRestInterceptor, "post_get_firewall_endpoint" + transports.FirewallActivationRestInterceptor, + "post_delete_firewall_endpoint", ) as post, mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_get_firewall_endpoint_with_metadata", + "post_delete_firewall_endpoint_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.FirewallActivationRestInterceptor, "pre_get_firewall_endpoint" + transports.FirewallActivationRestInterceptor, "pre_delete_firewall_endpoint" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = firewall_activation.GetFirewallEndpointRequest.pb( - firewall_activation.GetFirewallEndpointRequest() + pb_message = firewall_activation.DeleteFirewallEndpointRequest.pb( + firewall_activation.DeleteFirewallEndpointRequest() ) transcode.return_value = { "method": "post", @@ -8486,24 +12696,19 @@ def test_get_firewall_endpoint_rest_interceptors(null_interceptor): 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 = firewall_activation.FirewallEndpoint.to_json( - firewall_activation.FirewallEndpoint() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = firewall_activation.GetFirewallEndpointRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = firewall_activation.FirewallEndpoint() - post_with_metadata.return_value = ( - firewall_activation.FirewallEndpoint(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_firewall_endpoint( + client.delete_firewall_endpoint( request, metadata=[ ("key", "val"), @@ -8516,14 +12721,16 @@ def test_get_firewall_endpoint_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_firewall_endpoint_rest_bad_request( - request_type=firewall_activation.CreateFirewallEndpointRequest, +def test_delete_project_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.DeleteFirewallEndpointRequest, ): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8539,110 +12746,25 @@ def test_create_firewall_endpoint_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_firewall_endpoint(request) + client.delete_project_firewall_endpoint(request) @pytest.mark.parametrize( "request_type", - [ - firewall_activation.CreateFirewallEndpointRequest, - dict, - ], -) -def test_create_firewall_endpoint_rest_call_success(request_type): - client = FirewallActivationClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} - request_init["firewall_endpoint"] = { - "name": "name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "state": 1, - "reconciling": True, - "associated_networks": [ - "associated_networks_value1", - "associated_networks_value2", - ], - "associations": [{"name": "name_value", "network": "network_value"}], - "satisfies_pzs": True, - "satisfies_pzi": True, - "billing_project_id": "billing_project_id_value", - "endpoint_settings": {"jumbo_frames_enabled": 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 = firewall_activation.CreateFirewallEndpointRequest.meta.fields[ - "firewall_endpoint" - ] - - 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["firewall_endpoint"].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["firewall_endpoint"][field])): - del request_init["firewall_endpoint"][field][i][subfield] - else: - del request_init["firewall_endpoint"][field][subfield] + [ + firewall_activation.DeleteFirewallEndpointRequest, + dict, + ], +) +def test_delete_project_firewall_endpoint_rest_call_success(request_type): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8657,14 +12779,14 @@ def get_message_fields(field): response_value.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_firewall_endpoint(request) + response = client.delete_project_firewall_endpoint(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_firewall_endpoint_rest_interceptors(null_interceptor): +def test_delete_project_firewall_endpoint_rest_interceptors(null_interceptor): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8679,21 +12801,22 @@ def test_create_firewall_endpoint_rest_interceptors(null_interceptor): mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_create_firewall_endpoint", + "post_delete_project_firewall_endpoint", ) as post, mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_create_firewall_endpoint_with_metadata", + "post_delete_project_firewall_endpoint_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.FirewallActivationRestInterceptor, "pre_create_firewall_endpoint" + transports.FirewallActivationRestInterceptor, + "pre_delete_project_firewall_endpoint", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = firewall_activation.CreateFirewallEndpointRequest.pb( - firewall_activation.CreateFirewallEndpointRequest() + pb_message = firewall_activation.DeleteFirewallEndpointRequest.pb( + firewall_activation.DeleteFirewallEndpointRequest() ) transcode.return_value = { "method": "post", @@ -8708,7 +12831,7 @@ def test_create_firewall_endpoint_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = firewall_activation.CreateFirewallEndpointRequest() + request = firewall_activation.DeleteFirewallEndpointRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8717,7 +12840,7 @@ def test_create_firewall_endpoint_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_firewall_endpoint( + client.delete_project_firewall_endpoint( request, metadata=[ ("key", "val"), @@ -8730,15 +12853,17 @@ def test_create_firewall_endpoint_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_firewall_endpoint_rest_bad_request( - request_type=firewall_activation.DeleteFirewallEndpointRequest, +def test_update_firewall_endpoint_rest_bad_request( + request_type=firewall_activation.UpdateFirewallEndpointRequest, ): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + "firewall_endpoint": { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + } } request = request_type(**request_init) @@ -8755,25 +12880,114 @@ def test_delete_firewall_endpoint_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_firewall_endpoint(request) + client.update_firewall_endpoint(request) @pytest.mark.parametrize( "request_type", [ - firewall_activation.DeleteFirewallEndpointRequest, + firewall_activation.UpdateFirewallEndpointRequest, dict, ], ) -def test_delete_firewall_endpoint_rest_call_success(request_type): +def test_update_firewall_endpoint_rest_call_success(request_type): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + "firewall_endpoint": { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + } + } + request_init["firewall_endpoint"] = { + "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "reconciling": True, + "associated_networks": [ + "associated_networks_value1", + "associated_networks_value2", + ], + "associations": [{"name": "name_value", "network": "network_value"}], + "satisfies_pzs": True, + "satisfies_pzi": True, + "billing_project_id": "billing_project_id_value", + "endpoint_settings": {"jumbo_frames_enabled": 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 = firewall_activation.UpdateFirewallEndpointRequest.meta.fields[ + "firewall_endpoint" + ] + + 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["firewall_endpoint"].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["firewall_endpoint"][field])): + del request_init["firewall_endpoint"][field][i][subfield] + else: + del request_init["firewall_endpoint"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8788,14 +13002,14 @@ def test_delete_firewall_endpoint_rest_call_success(request_type): response_value.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_firewall_endpoint(request) + response = client.update_firewall_endpoint(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): +def test_update_firewall_endpoint_rest_interceptors(null_interceptor): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8810,21 +13024,21 @@ def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_delete_firewall_endpoint", + "post_update_firewall_endpoint", ) as post, mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_delete_firewall_endpoint_with_metadata", + "post_update_firewall_endpoint_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.FirewallActivationRestInterceptor, "pre_delete_firewall_endpoint" + transports.FirewallActivationRestInterceptor, "pre_update_firewall_endpoint" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = firewall_activation.DeleteFirewallEndpointRequest.pb( - firewall_activation.DeleteFirewallEndpointRequest() + pb_message = firewall_activation.UpdateFirewallEndpointRequest.pb( + firewall_activation.UpdateFirewallEndpointRequest() ) transcode.return_value = { "method": "post", @@ -8839,7 +13053,7 @@ def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = firewall_activation.DeleteFirewallEndpointRequest() + request = firewall_activation.UpdateFirewallEndpointRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8848,7 +13062,7 @@ def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_firewall_endpoint( + client.update_firewall_endpoint( request, metadata=[ ("key", "val"), @@ -8861,7 +13075,7 @@ def test_delete_firewall_endpoint_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_firewall_endpoint_rest_bad_request( +def test_update_project_firewall_endpoint_rest_bad_request( request_type=firewall_activation.UpdateFirewallEndpointRequest, ): client = FirewallActivationClient( @@ -8870,7 +13084,7 @@ def test_update_firewall_endpoint_rest_bad_request( # send a request that will satisfy transcoding request_init = { "firewall_endpoint": { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" } } request = request_type(**request_init) @@ -8888,7 +13102,7 @@ def test_update_firewall_endpoint_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_firewall_endpoint(request) + client.update_project_firewall_endpoint(request) @pytest.mark.parametrize( @@ -8898,7 +13112,7 @@ def test_update_firewall_endpoint_rest_bad_request( dict, ], ) -def test_update_firewall_endpoint_rest_call_success(request_type): +def test_update_project_firewall_endpoint_rest_call_success(request_type): client = FirewallActivationClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8906,11 +13120,11 @@ def test_update_firewall_endpoint_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = { "firewall_endpoint": { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3" + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3" } } request_init["firewall_endpoint"] = { - "name": "organizations/sample1/locations/sample2/firewallEndpoints/sample3", + "name": "projects/sample1/locations/sample2/firewallEndpoints/sample3", "description": "description_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, @@ -9010,14 +13224,14 @@ def get_message_fields(field): response_value.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_firewall_endpoint(request) + response = client.update_project_firewall_endpoint(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_update_firewall_endpoint_rest_interceptors(null_interceptor): +def test_update_project_firewall_endpoint_rest_interceptors(null_interceptor): transport = transports.FirewallActivationRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9032,14 +13246,15 @@ def test_update_firewall_endpoint_rest_interceptors(null_interceptor): mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_update_firewall_endpoint", + "post_update_project_firewall_endpoint", ) as post, mock.patch.object( transports.FirewallActivationRestInterceptor, - "post_update_firewall_endpoint_with_metadata", + "post_update_project_firewall_endpoint_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.FirewallActivationRestInterceptor, "pre_update_firewall_endpoint" + transports.FirewallActivationRestInterceptor, + "pre_update_project_firewall_endpoint", ) as pre, ): pre.assert_not_called() @@ -9070,7 +13285,7 @@ def test_update_firewall_endpoint_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_firewall_endpoint( + client.update_project_firewall_endpoint( request, metadata=[ ("key", "val"), @@ -10559,6 +14774,27 @@ def test_list_firewall_endpoints_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_list_project_firewall_endpoints_empty_call_rest(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_project_firewall_endpoints), "__call__" + ) as call: + client.list_project_firewall_endpoints(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.ListFirewallEndpointsRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_rest(): @@ -10580,6 +14816,27 @@ def test_get_firewall_endpoint_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_get_project_firewall_endpoint_empty_call_rest(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_project_firewall_endpoint), "__call__" + ) as call: + client.get_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.GetFirewallEndpointRequest() + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_create_firewall_endpoint_empty_call_rest(): @@ -10601,6 +14858,27 @@ def test_create_firewall_endpoint_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_create_project_firewall_endpoint_empty_call_rest(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_project_firewall_endpoint), "__call__" + ) as call: + client.create_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.CreateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_rest(): @@ -10622,6 +14900,27 @@ def test_delete_firewall_endpoint_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_delete_project_firewall_endpoint_empty_call_rest(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_project_firewall_endpoint), "__call__" + ) as call: + client.delete_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.DeleteFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_empty_call_rest(): @@ -10643,6 +14942,27 @@ def test_update_firewall_endpoint_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_update_project_firewall_endpoint_empty_call_rest(): + client = FirewallActivationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_project_firewall_endpoint), "__call__" + ) as call: + client.update_project_firewall_endpoint(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = firewall_activation.UpdateFirewallEndpointRequest() + assert args[0] == request_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_firewall_endpoint_associations_empty_call_rest(): @@ -10799,10 +15119,15 @@ def test_firewall_activation_base_transport(): # raise NotImplementedError. methods = ( "list_firewall_endpoints", + "list_project_firewall_endpoints", "get_firewall_endpoint", + "get_project_firewall_endpoint", "create_firewall_endpoint", + "create_project_firewall_endpoint", "delete_firewall_endpoint", + "delete_project_firewall_endpoint", "update_firewall_endpoint", + "update_project_firewall_endpoint", "list_firewall_endpoint_associations", "get_firewall_endpoint_association", "create_firewall_endpoint_association", @@ -11092,18 +15417,33 @@ def test_firewall_activation_client_transport_session_collision(transport_name): session1 = client1.transport.list_firewall_endpoints._session session2 = client2.transport.list_firewall_endpoints._session assert session1 != session2 + session1 = client1.transport.list_project_firewall_endpoints._session + session2 = client2.transport.list_project_firewall_endpoints._session + assert session1 != session2 session1 = client1.transport.get_firewall_endpoint._session session2 = client2.transport.get_firewall_endpoint._session assert session1 != session2 + session1 = client1.transport.get_project_firewall_endpoint._session + session2 = client2.transport.get_project_firewall_endpoint._session + assert session1 != session2 session1 = client1.transport.create_firewall_endpoint._session session2 = client2.transport.create_firewall_endpoint._session assert session1 != session2 + session1 = client1.transport.create_project_firewall_endpoint._session + session2 = client2.transport.create_project_firewall_endpoint._session + assert session1 != session2 session1 = client1.transport.delete_firewall_endpoint._session session2 = client2.transport.delete_firewall_endpoint._session assert session1 != session2 + session1 = client1.transport.delete_project_firewall_endpoint._session + session2 = client2.transport.delete_project_firewall_endpoint._session + assert session1 != session2 session1 = client1.transport.update_firewall_endpoint._session session2 = client2.transport.update_firewall_endpoint._session assert session1 != session2 + session1 = client1.transport.update_project_firewall_endpoint._session + session2 = client2.transport.update_project_firewall_endpoint._session + assert session1 != session2 session1 = client1.transport.list_firewall_endpoint_associations._session session2 = client2.transport.list_firewall_endpoint_associations._session assert session1 != session2 diff --git a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_network_security.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_network_security.py index 54b7308c3d7a..fbe094ed035a 100644 --- a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_network_security.py +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_network_security.py @@ -38352,6 +38352,7 @@ def test_create_authz_policy_rest_call_success(request_type): "base_protocol_methods_option": 1, "methods": [{"name": "name_value", "params": {}}], }, + "snis": {}, } ], "not_operations": {}, @@ -38359,6 +38360,7 @@ def test_create_authz_policy_rest_call_success(request_type): "when": "when_value", } ], + "network_rules": {}, "action": 1, "custom_provider": { "cloud_iap": {}, @@ -38618,6 +38620,7 @@ def test_update_authz_policy_rest_call_success(request_type): "base_protocol_methods_option": 1, "methods": [{"name": "name_value", "params": {}}], }, + "snis": {}, } ], "not_operations": {}, @@ -38625,6 +38628,7 @@ def test_update_authz_policy_rest_call_success(request_type): "when": "when_value", } ], + "network_rules": {}, "action": 1, "custom_provider": { "cloud_iap": {}, diff --git a/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_security_profile_group_service.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_security_profile_group_service.py new file mode 100644 index 000000000000..b93e9a63fcfc --- /dev/null +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_security_profile_group_service.py @@ -0,0 +1,13459 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.network_security_v1.services.security_profile_group_service import ( + SecurityProfileGroupServiceAsyncClient, + SecurityProfileGroupServiceClient, + pagers, + transports, +) +from google.cloud.network_security_v1.types import ( + common, + security_profile_group, + security_profile_group_intercept, + security_profile_group_mirroring, + security_profile_group_service, + security_profile_group_threatprevention, + security_profile_group_urlfiltering, +) +from google.cloud.network_security_v1.types import ( + security_profile_group as gcn_security_profile_group, +) + +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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert SecurityProfileGroupServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + SecurityProfileGroupServiceClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityProfileGroupServiceClient._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: + SecurityProfileGroupServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityProfileGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityProfileGroupServiceClient._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 SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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): + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._get_client_cert_source(None, False) is None + ) + assert ( + SecurityProfileGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SecurityProfileGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SecurityProfileGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceClient), +) +@mock.patch.object( + SecurityProfileGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityProfileGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SecurityProfileGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = SecurityProfileGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SecurityProfileGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SecurityProfileGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SecurityProfileGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + SecurityProfileGroupServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityProfileGroupServiceClient._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 ( + SecurityProfileGroupServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SecurityProfileGroupServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + SecurityProfileGroupServiceClient._get_universe_domain(None, None) + == SecurityProfileGroupServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SecurityProfileGroupServiceClient._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 = SecurityProfileGroupServiceClient(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 = SecurityProfileGroupServiceClient(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", + [ + (SecurityProfileGroupServiceClient, "grpc"), + (SecurityProfileGroupServiceAsyncClient, "grpc_asyncio"), + (SecurityProfileGroupServiceClient, "rest"), + ], +) +def test_security_profile_group_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SecurityProfileGroupServiceGrpcTransport, "grpc"), + (transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityProfileGroupServiceRestTransport, "rest"), + ], +) +def test_security_profile_group_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SecurityProfileGroupServiceClient, "grpc"), + (SecurityProfileGroupServiceAsyncClient, "grpc_asyncio"), + (SecurityProfileGroupServiceClient, "rest"), + ], +) +def test_security_profile_group_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +def test_security_profile_group_service_client_get_transport_class(): + transport = SecurityProfileGroupServiceClient.get_transport_class() + available_transports = [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceRestTransport, + ] + assert transport in available_transports + + transport = SecurityProfileGroupServiceClient.get_transport_class("grpc") + assert transport == transports.SecurityProfileGroupServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + SecurityProfileGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceClient), +) +@mock.patch.object( + SecurityProfileGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceAsyncClient), +) +def test_security_profile_group_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + SecurityProfileGroupServiceClient, "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( + SecurityProfileGroupServiceClient, "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", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + "true", + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + "false", + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceRestTransport, + "rest", + "true", + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SecurityProfileGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceClient), +) +@mock.patch.object( + SecurityProfileGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_profile_group_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [SecurityProfileGroupServiceClient, SecurityProfileGroupServiceAsyncClient], +) +@mock.patch.object( + SecurityProfileGroupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecurityProfileGroupServiceClient), +) +@mock.patch.object( + SecurityProfileGroupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecurityProfileGroupServiceAsyncClient), +) +def test_security_profile_group_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", + [SecurityProfileGroupServiceClient, SecurityProfileGroupServiceAsyncClient], +) +@mock.patch.object( + SecurityProfileGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceClient), +) +@mock.patch.object( + SecurityProfileGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityProfileGroupServiceAsyncClient), +) +def test_security_profile_group_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityProfileGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SecurityProfileGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = SecurityProfileGroupServiceClient._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", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceRestTransport, + "rest", + ), + ], +) +def test_security_profile_group_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceRestTransport, + "rest", + None, + ), + ], +) +def test_security_profile_group_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_security_profile_group_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.network_security_v1.services.security_profile_group_service.transports.SecurityProfileGroupServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SecurityProfileGroupServiceClient( + 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", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_security_profile_group_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfileGroupsRequest(), + {}, + ], +) +def test_list_security_profile_groups(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_security_profile_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.ListSecurityProfileGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfileGroupsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_security_profile_groups_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfileGroupsRequest( + 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_security_profile_groups), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_security_profile_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfileGroupsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_security_profile_groups_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 = SecurityProfileGroupServiceClient( + 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_security_profile_groups + 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_security_profile_groups + ] = mock_rpc + request = {} + client.list_security_profile_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_profile_groups(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_security_profile_groups_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_groups + 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_security_profile_groups + ] = mock_rpc + + request = {} + await client.list_security_profile_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_security_profile_groups(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfileGroupsRequest(), + {}, + ], +) +async def test_list_security_profile_groups_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfileGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_security_profile_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.ListSecurityProfileGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfileGroupsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_security_profile_groups_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfileGroupsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + call.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + client.list_security_profile_groups(request) + + # Establish that the 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_security_profile_groups_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.ListSecurityProfileGroupsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + await client.list_security_profile_groups(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_security_profile_groups_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_profile_groups( + 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_security_profile_groups_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups( + security_profile_group_service.ListSecurityProfileGroupsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_security_profile_groups_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_profile_groups( + 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_security_profile_groups_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_groups( + security_profile_group_service.ListSecurityProfileGroupsRequest(), + parent="parent_value", + ) + + +def test_list_security_profile_groups_pager(transport_name: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_security_profile_groups( + 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, security_profile_group.SecurityProfileGroup) for i in results + ) + + +def test_list_security_profile_groups_pages(transport_name: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_profile_groups(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_security_profile_groups_async_pager(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_profile_groups( + 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, security_profile_group.SecurityProfileGroup) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_security_profile_groups_async_pages(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_security_profile_groups(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", + [ + security_profile_group_service.GetSecurityProfileGroupRequest(), + {}, + ], +) +def test_get_security_profile_group(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfileGroup( + name="name_value", + description="description_value", + etag="etag_value", + data_path_id=1234, + threat_prevention_profile="threat_prevention_profile_value", + custom_mirroring_profile="custom_mirroring_profile_value", + custom_intercept_profile="custom_intercept_profile_value", + url_filtering_profile="url_filtering_profile_value", + ) + response = client.get_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.GetSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfileGroup) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.data_path_id == 1234 + assert response.threat_prevention_profile == "threat_prevention_profile_value" + assert response.custom_mirroring_profile == "custom_mirroring_profile_value" + assert response.custom_intercept_profile == "custom_intercept_profile_value" + assert response.url_filtering_profile == "url_filtering_profile_value" + + +def test_get_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.GetSecurityProfileGroupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_security_profile_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileGroupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + request = {} + client.get_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_profile_group(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_security_profile_group_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + await client.get_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_security_profile_group(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.GetSecurityProfileGroupRequest(), + {}, + ], +) +async def test_get_security_profile_group_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfileGroup( + name="name_value", + description="description_value", + etag="etag_value", + data_path_id=1234, + threat_prevention_profile="threat_prevention_profile_value", + custom_mirroring_profile="custom_mirroring_profile_value", + custom_intercept_profile="custom_intercept_profile_value", + url_filtering_profile="url_filtering_profile_value", + ) + ) + response = await client.get_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.GetSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfileGroup) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.data_path_id == 1234 + assert response.threat_prevention_profile == "threat_prevention_profile_value" + assert response.custom_mirroring_profile == "custom_mirroring_profile_value" + assert response.custom_intercept_profile == "custom_intercept_profile_value" + assert response.url_filtering_profile == "url_filtering_profile_value" + + +def test_get_security_profile_group_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.GetSecurityProfileGroupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + call.return_value = security_profile_group.SecurityProfileGroup() + client.get_security_profile_group(request) + + # Establish that the 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_security_profile_group_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.GetSecurityProfileGroupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfileGroup() + ) + await client.get_security_profile_group(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_security_profile_group_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfileGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_profile_group( + 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_security_profile_group_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.GetSecurityProfileGroupRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_security_profile_group_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfileGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfileGroup() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_profile_group( + 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_security_profile_group_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group( + security_profile_group_service.GetSecurityProfileGroupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileGroupRequest(), + {}, + ], +) +def test_create_security_profile_group(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.CreateSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_security_profile_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileGroupRequest( + parent="parent_value", + security_profile_group_id="security_profile_group_id_value", + ) + assert args[0] == request_msg + + +def test_create_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + request = {} + client.create_security_profile_group(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_security_profile_group(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_security_profile_group_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + await client.create_security_profile_group(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_security_profile_group(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileGroupRequest(), + {}, + ], +) +async def test_create_security_profile_group_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group), "__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_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.CreateSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_security_profile_group_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.CreateSecurityProfileGroupRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_security_profile_group(request) + + # Establish that the 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_security_profile_group_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.CreateSecurityProfileGroupRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_security_profile_group(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_security_profile_group_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__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_security_profile_group( + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_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].security_profile_group + mock_val = gcn_security_profile_group.SecurityProfileGroup(name="name_value") + assert arg == mock_val + arg = args[0].security_profile_group_id + mock_val = "security_profile_group_id_value" + assert arg == mock_val + + +def test_create_security_profile_group_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.CreateSecurityProfileGroupRequest(), + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_security_profile_group_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__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_security_profile_group( + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_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].security_profile_group + mock_val = gcn_security_profile_group.SecurityProfileGroup(name="name_value") + assert arg == mock_val + arg = args[0].security_profile_group_id + mock_val = "security_profile_group_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_security_profile_group_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group( + security_profile_group_service.CreateSecurityProfileGroupRequest(), + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileGroupRequest(), + {}, + ], +) +def test_update_security_profile_group(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.UpdateSecurityProfileGroupRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_security_profile_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request_msg + + +def test_update_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + request = {} + client.update_security_profile_group(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.update_security_profile_group(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_security_profile_group_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + await client.update_security_profile_group(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.update_security_profile_group(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileGroupRequest(), + {}, + ], +) +async def test_update_security_profile_group_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group), "__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.update_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_security_profile_group_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.UpdateSecurityProfileGroupRequest() + + request.security_profile_group.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_security_profile_group(request) + + # Establish that the 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", + "security_profile_group.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_security_profile_group_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.UpdateSecurityProfileGroupRequest() + + request.security_profile_group.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_security_profile_group(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", + "security_profile_group.name=name_value", + ) in kw["metadata"] + + +def test_update_security_profile_group_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__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.update_security_profile_group( + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + 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].security_profile_group + mock_val = gcn_security_profile_group.SecurityProfileGroup(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_security_profile_group_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.UpdateSecurityProfileGroupRequest(), + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_security_profile_group_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__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.update_security_profile_group( + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + 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].security_profile_group + mock_val = gcn_security_profile_group.SecurityProfileGroup(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_security_profile_group_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group( + security_profile_group_service.UpdateSecurityProfileGroupRequest(), + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileGroupRequest(), + {}, + ], +) +def test_delete_security_profile_group(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.DeleteSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.DeleteSecurityProfileGroupRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_security_profile_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileGroupRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + request = {} + client.delete_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_security_profile_group(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_security_profile_group_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + await client.delete_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_security_profile_group(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileGroupRequest(), + {}, + ], +) +async def test_delete_security_profile_group_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.DeleteSecurityProfileGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_security_profile_group_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.DeleteSecurityProfileGroupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_security_profile_group(request) + + # Establish that the 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_security_profile_group_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.DeleteSecurityProfileGroupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_security_profile_group(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_security_profile_group_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_security_profile_group( + 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_security_profile_group_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.DeleteSecurityProfileGroupRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_security_profile_group_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_security_profile_group( + 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_security_profile_group_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile_group( + security_profile_group_service.DeleteSecurityProfileGroupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfilesRequest(), + {}, + ], +) +def test_list_security_profiles(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group_service.ListSecurityProfilesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_security_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.ListSecurityProfilesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfilesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_security_profiles_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfilesRequest( + 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_security_profiles), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_security_profiles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfilesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_security_profiles_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 = SecurityProfileGroupServiceClient( + 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_security_profiles + 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_security_profiles] = ( + mock_rpc + ) + request = {} + client.list_security_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_profiles(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_security_profiles_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profiles + 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_security_profiles + ] = mock_rpc + + request = {} + await client.list_security_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_security_profiles(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfilesRequest(), + {}, + ], +) +async def test_list_security_profiles_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfilesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_security_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.ListSecurityProfilesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfilesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_security_profiles_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfilesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + call.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse() + ) + client.list_security_profiles(request) + + # Establish that the 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_security_profiles_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.ListSecurityProfilesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfilesResponse() + ) + await client.list_security_profiles(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_security_profiles_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_profiles( + 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_security_profiles_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profiles( + security_profile_group_service.ListSecurityProfilesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_security_profiles_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfilesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_profiles( + 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_security_profiles_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profiles( + security_profile_group_service.ListSecurityProfilesRequest(), + parent="parent_value", + ) + + +def test_list_security_profiles_pager(transport_name: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profiles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_security_profiles(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, security_profile_group.SecurityProfile) for i in results + ) + + +def test_list_security_profiles_pages(transport_name: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profiles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_profiles(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_security_profiles_async_pager(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_profiles( + 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, security_profile_group.SecurityProfile) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_security_profiles_async_pages(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_security_profiles(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", + [ + security_profile_group_service.GetSecurityProfileRequest(), + {}, + ], +) +def test_get_security_profile(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfile( + name="name_value", + description="description_value", + etag="etag_value", + type_=security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION, + ) + response = client.get_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.GetSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfile) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert ( + response.type_ + == security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION + ) + + +def test_get_security_profile_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.GetSecurityProfileRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_security_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile 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_security_profile] = ( + mock_rpc + ) + request = {} + client.get_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_profile(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_security_profile_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + await client.get_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_security_profile(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.GetSecurityProfileRequest(), + {}, + ], +) +async def test_get_security_profile_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfile( + name="name_value", + description="description_value", + etag="etag_value", + type_=security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION, + ) + ) + response = await client.get_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.GetSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfile) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert ( + response.type_ + == security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION + ) + + +def test_get_security_profile_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.GetSecurityProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + call.return_value = security_profile_group.SecurityProfile() + client.get_security_profile(request) + + # Establish that the 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_security_profile_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.GetSecurityProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfile() + ) + await client.get_security_profile(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_security_profile_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_profile( + 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_security_profile_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.GetSecurityProfileRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_security_profile_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = security_profile_group.SecurityProfile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfile() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_profile( + 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_security_profile_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile( + security_profile_group_service.GetSecurityProfileRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileRequest(), + {}, + ], +) +def test_create_security_profile(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.CreateSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_security_profile_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_security_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileRequest( + parent="parent_value", + security_profile_id="security_profile_id_value", + ) + assert args[0] == request_msg + + +def test_create_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + request = {} + client.create_security_profile(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_security_profile(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_security_profile_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + await client.create_security_profile(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_security_profile(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileRequest(), + {}, + ], +) +async def test_create_security_profile_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile), "__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_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.CreateSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_security_profile_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.CreateSecurityProfileRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_security_profile(request) + + # Establish that the 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_security_profile_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.CreateSecurityProfileRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_security_profile(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_security_profile_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__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_security_profile( + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_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].security_profile + mock_val = security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].security_profile_id + mock_val = "security_profile_id_value" + assert arg == mock_val + + +def test_create_security_profile_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.CreateSecurityProfileRequest(), + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_security_profile_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__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_security_profile( + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_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].security_profile + mock_val = security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].security_profile_id + mock_val = "security_profile_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_security_profile_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile( + security_profile_group_service.CreateSecurityProfileRequest(), + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileRequest(), + {}, + ], +) +def test_update_security_profile(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_security_profile_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.UpdateSecurityProfileRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_security_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request_msg + + +def test_update_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + request = {} + client.update_security_profile(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.update_security_profile(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_security_profile_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + await client.update_security_profile(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.update_security_profile(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileRequest(), + {}, + ], +) +async def test_update_security_profile_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile), "__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.update_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_security_profile_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.UpdateSecurityProfileRequest() + + request.security_profile.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_security_profile(request) + + # Establish that the 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", + "security_profile.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_security_profile_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.UpdateSecurityProfileRequest() + + request.security_profile.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_security_profile(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", + "security_profile.name=name_value", + ) in kw["metadata"] + + +def test_update_security_profile_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__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.update_security_profile( + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + 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].security_profile + mock_val = security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ) + 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_security_profile_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.UpdateSecurityProfileRequest(), + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_security_profile_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__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.update_security_profile( + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + 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].security_profile + mock_val = security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ) + 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_security_profile_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile( + security_profile_group_service.UpdateSecurityProfileRequest(), + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileRequest(), + {}, + ], +) +def test_delete_security_profile(request_type, transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.DeleteSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_security_profile_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 = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.DeleteSecurityProfileRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_security_profile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg + + +def test_delete_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + request = {} + client.delete_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_security_profile(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_security_profile_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 = SecurityProfileGroupServiceAsyncClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + await client.delete_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_security_profile(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 +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileRequest(), + {}, + ], +) +async def test_delete_security_profile_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = security_profile_group_service.DeleteSecurityProfileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_security_profile_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.DeleteSecurityProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_security_profile(request) + + # Establish that the 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_security_profile_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = security_profile_group_service.DeleteSecurityProfileRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_security_profile(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_security_profile_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_security_profile( + 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_security_profile_flattened_error(): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.DeleteSecurityProfileRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_security_profile_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_security_profile( + 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_security_profile_flattened_error_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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_security_profile( + security_profile_group_service.DeleteSecurityProfileRequest(), + name="name_value", + ) + + +def test_list_security_profile_groups_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 = SecurityProfileGroupServiceClient( + 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_security_profile_groups + 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_security_profile_groups + ] = mock_rpc + + request = {} + client.list_security_profile_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_profile_groups(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_security_profile_groups_rest_required_fields( + request_type=security_profile_group_service.ListSecurityProfileGroupsRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile_groups._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_security_profile_groups._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 = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_profile_group_service.ListSecurityProfileGroupsResponse() + # 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse.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_security_profile_groups(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_security_profile_groups_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_security_profile_groups._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_security_profile_groups_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + + # 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse.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_security_profile_groups(**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/v1/{parent=projects/*/locations/*}/securityProfileGroups" + % client.transport._host, + args[1], + ) + + +def test_list_security_profile_groups_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups( + security_profile_group_service.ListSecurityProfileGroupsRequest(), + parent="parent_value", + ) + + +def test_list_security_profile_groups_rest_pager(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfileGroupsResponse( + security_profile_groups=[ + security_profile_group.SecurityProfileGroup(), + security_profile_group.SecurityProfileGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + security_profile_group_service.ListSecurityProfileGroupsResponse.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_security_profile_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, security_profile_group.SecurityProfileGroup) for i in results + ) + + pages = list(client.list_security_profile_groups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + client.get_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_profile_group(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_security_profile_group_rest_required_fields( + request_type=security_profile_group_service.GetSecurityProfileGroupRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile_group._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_security_profile_group._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 = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_profile_group.SecurityProfileGroup() + # 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 = security_profile_group.SecurityProfileGroup.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_security_profile_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_security_profile_group_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_security_profile_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_security_profile_group_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group.SecurityProfileGroup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/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 = security_profile_group.SecurityProfileGroup.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_security_profile_group(**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/v1/{name=projects/*/locations/*/securityProfileGroups/*}" + % client.transport._host, + args[1], + ) + + +def test_get_security_profile_group_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.GetSecurityProfileGroupRequest(), + name="name_value", + ) + + +def test_create_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + client.create_security_profile_group(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_security_profile_group(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_security_profile_group_rest_required_fields( + request_type=security_profile_group_service.CreateSecurityProfileGroupRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["security_profile_group_id"] = "" + 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 + assert "securityProfileGroupId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_security_profile_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "securityProfileGroupId" in jsonified_request + assert ( + jsonified_request["securityProfileGroupId"] + == request_init["security_profile_group_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["securityProfileGroupId"] = "security_profile_group_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_security_profile_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("security_profile_group_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" + assert "securityProfileGroupId" in jsonified_request + assert ( + jsonified_request["securityProfileGroupId"] == "security_profile_group_id_value" + ) + + client = SecurityProfileGroupServiceClient( + 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_security_profile_group(request) + + expected_params = [ + ( + "securityProfileGroupId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_security_profile_group_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_security_profile_group._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("securityProfileGroupId",)) + & set( + ( + "parent", + "securityProfileGroupId", + "securityProfileGroup", + ) + ) + ) + + +def test_create_security_profile_group_rest_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_security_profile_group(**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/v1/{parent=projects/*/locations/*}/securityProfileGroups" + % client.transport._host, + args[1], + ) + + +def test_create_security_profile_group_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.CreateSecurityProfileGroupRequest(), + parent="parent_value", + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + security_profile_group_id="security_profile_group_id_value", + ) + + +def test_update_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + client.update_security_profile_group(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.update_security_profile_group(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_security_profile_group_rest_required_fields( + request_type=security_profile_group_service.UpdateSecurityProfileGroupRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile_group._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_security_profile_group._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 = SecurityProfileGroupServiceClient( + 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": "patch", + "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.update_security_profile_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_security_profile_group_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_security_profile_group._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "updateMask", + "securityProfileGroup", + ) + ) + ) + + +def test_update_security_profile_group_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = { + "security_profile_group": { + "name": "projects/sample1/locations/sample2/securityProfileGroups/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_security_profile_group(**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/v1/{security_profile_group.name=projects/*/locations/*/securityProfileGroups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_security_profile_group_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.UpdateSecurityProfileGroupRequest(), + security_profile_group=gcn_security_profile_group.SecurityProfileGroup( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_security_profile_group_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 = SecurityProfileGroupServiceClient( + 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_security_profile_group + 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_security_profile_group + ] = mock_rpc + + request = {} + client.delete_security_profile_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_security_profile_group(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_security_profile_group_rest_required_fields( + request_type=security_profile_group_service.DeleteSecurityProfileGroupRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile_group._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_security_profile_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_security_profile_group(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_security_profile_group_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_security_profile_group._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_security_profile_group_rest_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_security_profile_group(**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/v1/{name=projects/*/locations/*/securityProfileGroups/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_security_profile_group_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group( + security_profile_group_service.DeleteSecurityProfileGroupRequest(), + name="name_value", + ) + + +def test_list_security_profiles_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 = SecurityProfileGroupServiceClient( + 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_security_profiles + 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_security_profiles] = ( + mock_rpc + ) + + request = {} + client.list_security_profiles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_security_profiles(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_security_profiles_rest_required_fields( + request_type=security_profile_group_service.ListSecurityProfilesRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profiles._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_security_profiles._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 = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_profile_group_service.ListSecurityProfilesResponse() + # 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 = ( + security_profile_group_service.ListSecurityProfilesResponse.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_security_profiles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_security_profiles_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_security_profiles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_security_profiles_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfilesResponse() + + # 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 = security_profile_group_service.ListSecurityProfilesResponse.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_security_profiles(**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/v1/{parent=projects/*/locations/*}/securityProfiles" + % client.transport._host, + args[1], + ) + + +def test_list_security_profiles_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profiles( + security_profile_group_service.ListSecurityProfilesRequest(), + parent="parent_value", + ) + + +def test_list_security_profiles_rest_pager(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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 = ( + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + next_page_token="abc", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[], + next_page_token="def", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + ], + next_page_token="ghi", + ), + security_profile_group_service.ListSecurityProfilesResponse( + security_profiles=[ + security_profile_group.SecurityProfile(), + security_profile_group.SecurityProfile(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + security_profile_group_service.ListSecurityProfilesResponse.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_security_profiles(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, security_profile_group.SecurityProfile) for i in results + ) + + pages = list(client.list_security_profiles(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile 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_security_profile] = ( + mock_rpc + ) + + request = {} + client.get_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_security_profile(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_security_profile_rest_required_fields( + request_type=security_profile_group_service.GetSecurityProfileRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile._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_security_profile._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 = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = security_profile_group.SecurityProfile() + # 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 = security_profile_group.SecurityProfile.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_security_profile(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_security_profile_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_security_profile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_security_profile_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group.SecurityProfile() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/securityProfiles/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 = security_profile_group.SecurityProfile.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_security_profile(**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/v1/{name=projects/*/locations/*/securityProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_get_security_profile_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.GetSecurityProfileRequest(), + name="name_value", + ) + + +def test_create_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + client.create_security_profile(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_security_profile(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_security_profile_rest_required_fields( + request_type=security_profile_group_service.CreateSecurityProfileRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["security_profile_id"] = "" + 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 + assert "securityProfileId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_security_profile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "securityProfileId" in jsonified_request + assert jsonified_request["securityProfileId"] == request_init["security_profile_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["securityProfileId"] = "security_profile_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_security_profile._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("security_profile_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" + assert "securityProfileId" in jsonified_request + assert jsonified_request["securityProfileId"] == "security_profile_id_value" + + client = SecurityProfileGroupServiceClient( + 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_security_profile(request) + + expected_params = [ + ( + "securityProfileId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_security_profile_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_security_profile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("securityProfileId",)) + & set( + ( + "parent", + "securityProfileId", + "securityProfile", + ) + ) + ) + + +def test_create_security_profile_rest_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_security_profile(**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/v1/{parent=projects/*/locations/*}/securityProfiles" + % client.transport._host, + args[1], + ) + + +def test_create_security_profile_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.CreateSecurityProfileRequest(), + parent="parent_value", + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + security_profile_id="security_profile_id_value", + ) + + +def test_update_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + client.update_security_profile(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.update_security_profile(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_security_profile_rest_required_fields( + request_type=security_profile_group_service.UpdateSecurityProfileRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile._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_security_profile._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 = SecurityProfileGroupServiceClient( + 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": "patch", + "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.update_security_profile(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_security_profile_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_security_profile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "updateMask", + "securityProfile", + ) + ) + ) + + +def test_update_security_profile_rest_flattened(): + client = SecurityProfileGroupServiceClient( + 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 = { + "security_profile": { + "name": "projects/sample1/locations/sample2/securityProfiles/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._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_security_profile(**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/v1/{security_profile.name=projects/*/locations/*/securityProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_update_security_profile_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.UpdateSecurityProfileRequest(), + security_profile=security_profile_group.SecurityProfile( + threat_prevention_profile=security_profile_group_threatprevention.ThreatPreventionProfile( + severity_overrides=[ + security_profile_group_threatprevention.SeverityOverride( + severity=security_profile_group_threatprevention.Severity.INFORMATIONAL + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_security_profile_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 = SecurityProfileGroupServiceClient( + 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_security_profile + 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_security_profile + ] = mock_rpc + + request = {} + client.delete_security_profile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_security_profile(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_security_profile_rest_required_fields( + request_type=security_profile_group_service.DeleteSecurityProfileRequest, +): + transport_class = transports.SecurityProfileGroupServiceRestTransport + + 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_security_profile._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_security_profile._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_security_profile(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_security_profile_rest_unset_required_fields(): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_security_profile._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_security_profile_rest_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/securityProfiles/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_security_profile(**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/v1/{name=projects/*/locations/*/securityProfiles/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_security_profile_rest_flattened_error(transport: str = "rest"): + client = SecurityProfileGroupServiceClient( + 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_security_profile( + security_profile_group_service.DeleteSecurityProfileRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityProfileGroupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityProfileGroupServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityProfileGroupServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityProfileGroupServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + transports.SecurityProfileGroupServiceRestTransport, + ], +) +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 = SecurityProfileGroupServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_security_profile_groups_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + call.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + client.list_security_profile_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfileGroupsRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + call.return_value = security_profile_group.SecurityProfileGroup() + client.get_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_security_profile_group_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileGroupRequest() + assert args[0] == request_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_security_profiles_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + call.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse() + ) + client.list_security_profiles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfilesRequest() + assert args[0] == request_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_security_profile_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + call.return_value = security_profile_group.SecurityProfile() + client.get_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_security_profile_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_grpc(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SecurityProfileGroupServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_security_profile_groups_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfileGroupsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_security_profile_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfileGroupsRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfileGroup( + name="name_value", + description="description_value", + etag="etag_value", + data_path_id=1234, + threat_prevention_profile="threat_prevention_profile_value", + custom_mirroring_profile="custom_mirroring_profile_value", + custom_intercept_profile="custom_intercept_profile_value", + url_filtering_profile="url_filtering_profile_value", + ) + ) + await client.get_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_security_profile_group_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__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_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__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.update_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileGroupRequest() + assert args[0] == request_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_security_profiles_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group_service.ListSecurityProfilesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_security_profiles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfilesRequest() + assert args[0] == request_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_security_profile_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + security_profile_group.SecurityProfile( + name="name_value", + description="description_value", + etag="etag_value", + type_=security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION, + ) + ) + await client.get_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_security_profile_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__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_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__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.update_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_grpc_asyncio(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SecurityProfileGroupServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_security_profile_groups_rest_bad_request( + request_type=security_profile_group_service.ListSecurityProfileGroupsRequest, +): + client = SecurityProfileGroupServiceClient( + 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_security_profile_groups(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfileGroupsRequest, + dict, + ], +) +def test_list_security_profile_groups_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfileGroupsResponse( + 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse.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_security_profile_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfileGroupsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_security_profile_groups_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_list_security_profile_groups", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_list_security_profile_groups_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_list_security_profile_groups", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.ListSecurityProfileGroupsRequest.pb( + security_profile_group_service.ListSecurityProfileGroupsRequest() + ) + 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 = ( + security_profile_group_service.ListSecurityProfileGroupsResponse.to_json( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + ) + req.return_value.content = return_value + + request = security_profile_group_service.ListSecurityProfileGroupsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse() + ) + post_with_metadata.return_value = ( + security_profile_group_service.ListSecurityProfileGroupsResponse(), + metadata, + ) + + client.list_security_profile_groups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_security_profile_group_rest_bad_request( + request_type=security_profile_group_service.GetSecurityProfileGroupRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/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_security_profile_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.GetSecurityProfileGroupRequest, + dict, + ], +) +def test_get_security_profile_group_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/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 = security_profile_group.SecurityProfileGroup( + name="name_value", + description="description_value", + etag="etag_value", + data_path_id=1234, + threat_prevention_profile="threat_prevention_profile_value", + custom_mirroring_profile="custom_mirroring_profile_value", + custom_intercept_profile="custom_intercept_profile_value", + url_filtering_profile="url_filtering_profile_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 = security_profile_group.SecurityProfileGroup.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_security_profile_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfileGroup) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.data_path_id == 1234 + assert response.threat_prevention_profile == "threat_prevention_profile_value" + assert response.custom_mirroring_profile == "custom_mirroring_profile_value" + assert response.custom_intercept_profile == "custom_intercept_profile_value" + assert response.url_filtering_profile == "url_filtering_profile_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_security_profile_group_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_get_security_profile_group", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_get_security_profile_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_get_security_profile_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.GetSecurityProfileGroupRequest.pb( + security_profile_group_service.GetSecurityProfileGroupRequest() + ) + 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 = security_profile_group.SecurityProfileGroup.to_json( + security_profile_group.SecurityProfileGroup() + ) + req.return_value.content = return_value + + request = security_profile_group_service.GetSecurityProfileGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = security_profile_group.SecurityProfileGroup() + post_with_metadata.return_value = ( + security_profile_group.SecurityProfileGroup(), + metadata, + ) + + client.get_security_profile_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_security_profile_group_rest_bad_request( + request_type=security_profile_group_service.CreateSecurityProfileGroupRequest, +): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileGroupRequest, + dict, + ], +) +def test_create_security_profile_group_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["security_profile_group"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "data_path_id": 1234, + "labels": {}, + "threat_prevention_profile": "threat_prevention_profile_value", + "custom_mirroring_profile": "custom_mirroring_profile_value", + "custom_intercept_profile": "custom_intercept_profile_value", + "url_filtering_profile": "url_filtering_profile_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 = ( + security_profile_group_service.CreateSecurityProfileGroupRequest.meta.fields[ + "security_profile_group" + ] + ) + + 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[ + "security_profile_group" + ].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["security_profile_group"][field])): + del request_init["security_profile_group"][field][i][subfield] + else: + del request_init["security_profile_group"][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_security_profile_group(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_security_profile_group_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_create_security_profile_group", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_create_security_profile_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_create_security_profile_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + security_profile_group_service.CreateSecurityProfileGroupRequest.pb( + security_profile_group_service.CreateSecurityProfileGroupRequest() + ) + ) + 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 = security_profile_group_service.CreateSecurityProfileGroupRequest() + 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_security_profile_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_security_profile_group_rest_bad_request( + request_type=security_profile_group_service.UpdateSecurityProfileGroupRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "security_profile_group": { + "name": "projects/sample1/locations/sample2/securityProfileGroups/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_security_profile_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileGroupRequest, + dict, + ], +) +def test_update_security_profile_group_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "security_profile_group": { + "name": "projects/sample1/locations/sample2/securityProfileGroups/sample3" + } + } + request_init["security_profile_group"] = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "data_path_id": 1234, + "labels": {}, + "threat_prevention_profile": "threat_prevention_profile_value", + "custom_mirroring_profile": "custom_mirroring_profile_value", + "custom_intercept_profile": "custom_intercept_profile_value", + "url_filtering_profile": "url_filtering_profile_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 = ( + security_profile_group_service.UpdateSecurityProfileGroupRequest.meta.fields[ + "security_profile_group" + ] + ) + + 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[ + "security_profile_group" + ].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["security_profile_group"][field])): + del request_init["security_profile_group"][field][i][subfield] + else: + del request_init["security_profile_group"][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.update_security_profile_group(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_update_security_profile_group_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_update_security_profile_group", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_update_security_profile_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_update_security_profile_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + security_profile_group_service.UpdateSecurityProfileGroupRequest.pb( + security_profile_group_service.UpdateSecurityProfileGroupRequest() + ) + ) + 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 = security_profile_group_service.UpdateSecurityProfileGroupRequest() + 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.update_security_profile_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_security_profile_group_rest_bad_request( + request_type=security_profile_group_service.DeleteSecurityProfileGroupRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/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_security_profile_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileGroupRequest, + dict, + ], +) +def test_delete_security_profile_group_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfileGroups/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_security_profile_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_security_profile_group_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_delete_security_profile_group", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_delete_security_profile_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_delete_security_profile_group", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + security_profile_group_service.DeleteSecurityProfileGroupRequest.pb( + security_profile_group_service.DeleteSecurityProfileGroupRequest() + ) + ) + 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 = security_profile_group_service.DeleteSecurityProfileGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_security_profile_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_security_profiles_rest_bad_request( + request_type=security_profile_group_service.ListSecurityProfilesRequest, +): + client = SecurityProfileGroupServiceClient( + 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_security_profiles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.ListSecurityProfilesRequest, + dict, + ], +) +def test_list_security_profiles_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + 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 = security_profile_group_service.ListSecurityProfilesResponse( + 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 = security_profile_group_service.ListSecurityProfilesResponse.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_security_profiles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecurityProfilesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_security_profiles_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_list_security_profiles", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_list_security_profiles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_list_security_profiles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.ListSecurityProfilesRequest.pb( + security_profile_group_service.ListSecurityProfilesRequest() + ) + 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 = ( + security_profile_group_service.ListSecurityProfilesResponse.to_json( + security_profile_group_service.ListSecurityProfilesResponse() + ) + ) + req.return_value.content = return_value + + request = security_profile_group_service.ListSecurityProfilesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse() + ) + post_with_metadata.return_value = ( + security_profile_group_service.ListSecurityProfilesResponse(), + metadata, + ) + + client.list_security_profiles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_security_profile_rest_bad_request( + request_type=security_profile_group_service.GetSecurityProfileRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfiles/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_security_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.GetSecurityProfileRequest, + dict, + ], +) +def test_get_security_profile_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfiles/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 = security_profile_group.SecurityProfile( + name="name_value", + description="description_value", + etag="etag_value", + type_=security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION, + ) + + # 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 = security_profile_group.SecurityProfile.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_security_profile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, security_profile_group.SecurityProfile) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert ( + response.type_ + == security_profile_group.SecurityProfile.ProfileType.THREAT_PREVENTION + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_security_profile_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_get_security_profile", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_get_security_profile_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_get_security_profile", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.GetSecurityProfileRequest.pb( + security_profile_group_service.GetSecurityProfileRequest() + ) + 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 = security_profile_group.SecurityProfile.to_json( + security_profile_group.SecurityProfile() + ) + req.return_value.content = return_value + + request = security_profile_group_service.GetSecurityProfileRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = security_profile_group.SecurityProfile() + post_with_metadata.return_value = ( + security_profile_group.SecurityProfile(), + metadata, + ) + + client.get_security_profile( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_security_profile_rest_bad_request( + request_type=security_profile_group_service.CreateSecurityProfileRequest, +): + client = SecurityProfileGroupServiceClient( + 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_security_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.CreateSecurityProfileRequest, + dict, + ], +) +def test_create_security_profile_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["security_profile"] = { + "threat_prevention_profile": { + "severity_overrides": [{"severity": 1, "action": 4}], + "threat_overrides": [ + {"threat_id": "threat_id_value", "type_": 1, "action": 4} + ], + "antivirus_overrides": [{"protocol": 1, "action": 4}], + }, + "custom_mirroring_profile": { + "mirroring_endpoint_group": "mirroring_endpoint_group_value" + }, + "custom_intercept_profile": { + "intercept_endpoint_group": "intercept_endpoint_group_value" + }, + "url_filtering_profile": { + "url_filters": [ + { + "filtering_action": 1, + "urls": ["urls_value1", "urls_value2"], + "priority": 898, + } + ] + }, + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "labels": {}, + "type_": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + security_profile_group_service.CreateSecurityProfileRequest.meta.fields[ + "security_profile" + ] + ) + + 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["security_profile"].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["security_profile"][field])): + del request_init["security_profile"][field][i][subfield] + else: + del request_init["security_profile"][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_security_profile(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_security_profile_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_create_security_profile", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_create_security_profile_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_create_security_profile", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.CreateSecurityProfileRequest.pb( + security_profile_group_service.CreateSecurityProfileRequest() + ) + 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 = security_profile_group_service.CreateSecurityProfileRequest() + 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_security_profile( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_security_profile_rest_bad_request( + request_type=security_profile_group_service.UpdateSecurityProfileRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "security_profile": { + "name": "projects/sample1/locations/sample2/securityProfiles/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_security_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.UpdateSecurityProfileRequest, + dict, + ], +) +def test_update_security_profile_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "security_profile": { + "name": "projects/sample1/locations/sample2/securityProfiles/sample3" + } + } + request_init["security_profile"] = { + "threat_prevention_profile": { + "severity_overrides": [{"severity": 1, "action": 4}], + "threat_overrides": [ + {"threat_id": "threat_id_value", "type_": 1, "action": 4} + ], + "antivirus_overrides": [{"protocol": 1, "action": 4}], + }, + "custom_mirroring_profile": { + "mirroring_endpoint_group": "mirroring_endpoint_group_value" + }, + "custom_intercept_profile": { + "intercept_endpoint_group": "intercept_endpoint_group_value" + }, + "url_filtering_profile": { + "url_filters": [ + { + "filtering_action": 1, + "urls": ["urls_value1", "urls_value2"], + "priority": 898, + } + ] + }, + "name": "projects/sample1/locations/sample2/securityProfiles/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "labels": {}, + "type_": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + security_profile_group_service.UpdateSecurityProfileRequest.meta.fields[ + "security_profile" + ] + ) + + 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["security_profile"].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["security_profile"][field])): + del request_init["security_profile"][field][i][subfield] + else: + del request_init["security_profile"][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.update_security_profile(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_update_security_profile_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_update_security_profile", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_update_security_profile_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_update_security_profile", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.UpdateSecurityProfileRequest.pb( + security_profile_group_service.UpdateSecurityProfileRequest() + ) + 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 = security_profile_group_service.UpdateSecurityProfileRequest() + 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.update_security_profile( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_security_profile_rest_bad_request( + request_type=security_profile_group_service.DeleteSecurityProfileRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfiles/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_security_profile(request) + + +@pytest.mark.parametrize( + "request_type", + [ + security_profile_group_service.DeleteSecurityProfileRequest, + dict, + ], +) +def test_delete_security_profile_rest_call_success(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/securityProfiles/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_security_profile(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_security_profile_rest_interceptors(null_interceptor): + transport = transports.SecurityProfileGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityProfileGroupServiceRestInterceptor(), + ) + client = SecurityProfileGroupServiceClient(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.SecurityProfileGroupServiceRestInterceptor, + "post_delete_security_profile", + ) as post, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "post_delete_security_profile_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecurityProfileGroupServiceRestInterceptor, + "pre_delete_security_profile", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = security_profile_group_service.DeleteSecurityProfileRequest.pb( + security_profile_group_service.DeleteSecurityProfileRequest() + ) + 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 = security_profile_group_service.DeleteSecurityProfileRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_security_profile( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + 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_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_security_profile_groups_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profile_groups), "__call__" + ) as call: + client.list_security_profile_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfileGroupsRequest() + assert args[0] == request_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_security_profile_group_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile_group), "__call__" + ) as call: + client.get_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileGroupRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_security_profile_group_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile_group), "__call__" + ) as call: + client.create_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile_group), "__call__" + ) as call: + client.update_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileGroupRequest() + assert args[0] == request_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_security_profile_group_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile_group), "__call__" + ) as call: + client.delete_security_profile_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileGroupRequest() + assert args[0] == request_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_security_profiles_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_security_profiles), "__call__" + ) as call: + client.list_security_profiles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.ListSecurityProfilesRequest() + assert args[0] == request_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_security_profile_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_security_profile), "__call__" + ) as call: + client.get_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.GetSecurityProfileRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_security_profile_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_security_profile), "__call__" + ) as call: + client.create_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.CreateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_security_profile), "__call__" + ) as call: + client.update_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.UpdateSecurityProfileRequest() + assert args[0] == request_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_security_profile_empty_call_rest(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_profile), "__call__" + ) as call: + client.delete_security_profile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = security_profile_group_service.DeleteSecurityProfileRequest() + assert args[0] == request_msg + + +def test_security_profile_group_service_rest_lro_client(): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityProfileGroupServiceGrpcTransport, + ) + + +def test_security_profile_group_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityProfileGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_security_profile_group_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_security_v1.services.security_profile_group_service.transports.SecurityProfileGroupServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SecurityProfileGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_security_profile_groups", + "get_security_profile_group", + "create_security_profile_group", + "update_security_profile_group", + "delete_security_profile_group", + "list_security_profiles", + "get_security_profile", + "create_security_profile", + "update_security_profile", + "delete_security_profile", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_security_profile_group_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.network_security_v1.services.security_profile_group_service.transports.SecurityProfileGroupServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityProfileGroupServiceTransport( + 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",), + quota_project_id="octopus", + ) + + +def test_security_profile_group_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.network_security_v1.services.security_profile_group_service.transports.SecurityProfileGroupServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityProfileGroupServiceTransport() + adc.assert_called_once() + + +def test_security_profile_group_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecurityProfileGroupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + ], +) +def test_security_profile_group_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + transports.SecurityProfileGroupServiceRestTransport, + ], +) +def test_security_profile_group_service_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecurityProfileGroupServiceGrpcTransport, grpc_helpers), + ( + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_security_profile_group_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + ], +) +def test_security_profile_group_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_security_profile_group_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SecurityProfileGroupServiceRestTransport( + 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_security_profile_group_service_host_no_port(transport_name): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_security_profile_group_service_host_with_port(transport_name): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networksecurity.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_security_profile_group_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityProfileGroupServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityProfileGroupServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_security_profile_groups._session + session2 = client2.transport.list_security_profile_groups._session + assert session1 != session2 + session1 = client1.transport.get_security_profile_group._session + session2 = client2.transport.get_security_profile_group._session + assert session1 != session2 + session1 = client1.transport.create_security_profile_group._session + session2 = client2.transport.create_security_profile_group._session + assert session1 != session2 + session1 = client1.transport.update_security_profile_group._session + session2 = client2.transport.update_security_profile_group._session + assert session1 != session2 + session1 = client1.transport.delete_security_profile_group._session + session2 = client2.transport.delete_security_profile_group._session + assert session1 != session2 + session1 = client1.transport.list_security_profiles._session + session2 = client2.transport.list_security_profiles._session + assert session1 != session2 + session1 = client1.transport.get_security_profile._session + session2 = client2.transport.get_security_profile._session + assert session1 != session2 + session1 = client1.transport.create_security_profile._session + session2 = client2.transport.create_security_profile._session + assert session1 != session2 + session1 = client1.transport.update_security_profile._session + session2 = client2.transport.update_security_profile._session + assert session1 != session2 + session1 = client1.transport.delete_security_profile._session + session2 = client2.transport.delete_security_profile._session + assert session1 != session2 + + +def test_security_profile_group_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityProfileGroupServiceGrpcTransport( + 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_security_profile_group_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityProfileGroupServiceGrpcAsyncIOTransport( + 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.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + ], +) +def test_security_profile_group_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityProfileGroupServiceGrpcTransport, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + ], +) +def test_security_profile_group_service_transport_channel_mtls_with_adc( + transport_class, +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_security_profile_group_service_grpc_lro_client(): + client = SecurityProfileGroupServiceClient( + 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_security_profile_group_service_grpc_lro_async_client(): + client = SecurityProfileGroupServiceAsyncClient( + 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_intercept_endpoint_group_path(): + project = "squid" + location = "clam" + intercept_endpoint_group = "whelk" + expected = "projects/{project}/locations/{location}/interceptEndpointGroups/{intercept_endpoint_group}".format( + project=project, + location=location, + intercept_endpoint_group=intercept_endpoint_group, + ) + actual = SecurityProfileGroupServiceClient.intercept_endpoint_group_path( + project, location, intercept_endpoint_group + ) + assert expected == actual + + +def test_parse_intercept_endpoint_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "intercept_endpoint_group": "nudibranch", + } + path = SecurityProfileGroupServiceClient.intercept_endpoint_group_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_intercept_endpoint_group_path(path) + assert expected == actual + + +def test_mirroring_endpoint_group_path(): + project = "cuttlefish" + location = "mussel" + mirroring_endpoint_group = "winkle" + expected = "projects/{project}/locations/{location}/mirroringEndpointGroups/{mirroring_endpoint_group}".format( + project=project, + location=location, + mirroring_endpoint_group=mirroring_endpoint_group, + ) + actual = SecurityProfileGroupServiceClient.mirroring_endpoint_group_path( + project, location, mirroring_endpoint_group + ) + assert expected == actual + + +def test_parse_mirroring_endpoint_group_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "mirroring_endpoint_group": "abalone", + } + path = SecurityProfileGroupServiceClient.mirroring_endpoint_group_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_mirroring_endpoint_group_path(path) + assert expected == actual + + +def test_security_profile_path(): + organization = "squid" + location = "clam" + security_profile = "whelk" + expected = "organizations/{organization}/locations/{location}/securityProfiles/{security_profile}".format( + organization=organization, + location=location, + security_profile=security_profile, + ) + actual = SecurityProfileGroupServiceClient.security_profile_path( + organization, location, security_profile + ) + assert expected == actual + + +def test_parse_security_profile_path(): + expected = { + "organization": "octopus", + "location": "oyster", + "security_profile": "nudibranch", + } + path = SecurityProfileGroupServiceClient.security_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_security_profile_path(path) + assert expected == actual + + +def test_security_profile_group_path(): + organization = "cuttlefish" + location = "mussel" + security_profile_group = "winkle" + expected = "organizations/{organization}/locations/{location}/securityProfileGroups/{security_profile_group}".format( + organization=organization, + location=location, + security_profile_group=security_profile_group, + ) + actual = SecurityProfileGroupServiceClient.security_profile_group_path( + organization, location, security_profile_group + ) + assert expected == actual + + +def test_parse_security_profile_group_path(): + expected = { + "organization": "nautilus", + "location": "scallop", + "security_profile_group": "abalone", + } + path = SecurityProfileGroupServiceClient.security_profile_group_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_security_profile_group_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SecurityProfileGroupServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = SecurityProfileGroupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SecurityProfileGroupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = SecurityProfileGroupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SecurityProfileGroupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = SecurityProfileGroupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = SecurityProfileGroupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = SecurityProfileGroupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SecurityProfileGroupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = SecurityProfileGroupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityProfileGroupServiceClient.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.SecurityProfileGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SecurityProfileGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SecurityProfileGroupServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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_cancel_operation_flattened(): + client = SecurityProfileGroupServiceClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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_get_operation_flattened(): + client = SecurityProfileGroupServiceClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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_operations_flattened(): + client = SecurityProfileGroupServiceClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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_list_locations_flattened(): + client = SecurityProfileGroupServiceClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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_get_location_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(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 response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecurityProfileGroupServiceClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SecurityProfileGroupServiceAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = SecurityProfileGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityProfileGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceAsyncClient( + 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 = SecurityProfileGroupServiceClient( + 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 = SecurityProfileGroupServiceClient( + 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", + [ + ( + SecurityProfileGroupServiceClient, + transports.SecurityProfileGroupServiceGrpcTransport, + ), + ( + SecurityProfileGroupServiceAsyncClient, + transports.SecurityProfileGroupServiceGrpcAsyncIOTransport, + ), + ], +) +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-network-security/tests/unit/gapic/network_security_v1/test_sse_realm_service.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_sse_realm_service.py new file mode 100644 index 000000000000..ee26b4beef03 --- /dev/null +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_sse_realm_service.py @@ -0,0 +1,11123 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.network_security_v1.services.sse_realm_service import ( + SSERealmServiceAsyncClient, + SSERealmServiceClient, + pagers, + transports, +) +from google.cloud.network_security_v1.types import common, sse_realm + +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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert SSERealmServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + assert ( + SSERealmServiceClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert SSERealmServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SSERealmServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SSERealmServiceClient._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: + SSERealmServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert SSERealmServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SSERealmServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SSERealmServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SSERealmServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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): + SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._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 SSERealmServiceClient._get_client_cert_source(None, False) is None + assert ( + SSERealmServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + SSERealmServiceClient._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 ( + SSERealmServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SSERealmServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SSERealmServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceClient), +) +@mock.patch.object( + SSERealmServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SSERealmServiceClient._DEFAULT_UNIVERSE + default_endpoint = SSERealmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SSERealmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SSERealmServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SSERealmServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SSERealmServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SSERealmServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SSERealmServiceClient._get_api_endpoint(None, None, default_universe, "always") + == SSERealmServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SSERealmServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SSERealmServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SSERealmServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SSERealmServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SSERealmServiceClient._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 ( + SSERealmServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SSERealmServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SSERealmServiceClient._get_universe_domain(None, None) + == SSERealmServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SSERealmServiceClient._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 = SSERealmServiceClient(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 = SSERealmServiceClient(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", + [ + (SSERealmServiceClient, "grpc"), + (SSERealmServiceAsyncClient, "grpc_asyncio"), + (SSERealmServiceClient, "rest"), + ], +) +def test_sse_realm_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SSERealmServiceGrpcTransport, "grpc"), + (transports.SSERealmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SSERealmServiceRestTransport, "rest"), + ], +) +def test_sse_realm_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SSERealmServiceClient, "grpc"), + (SSERealmServiceAsyncClient, "grpc_asyncio"), + (SSERealmServiceClient, "rest"), + ], +) +def test_sse_realm_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +def test_sse_realm_service_client_get_transport_class(): + transport = SSERealmServiceClient.get_transport_class() + available_transports = [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceRestTransport, + ] + assert transport in available_transports + + transport = SSERealmServiceClient.get_transport_class("grpc") + assert transport == transports.SSERealmServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SSERealmServiceClient, transports.SSERealmServiceGrpcTransport, "grpc"), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SSERealmServiceClient, transports.SSERealmServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + SSERealmServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceClient), +) +@mock.patch.object( + SSERealmServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceAsyncClient), +) +def test_sse_realm_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SSERealmServiceClient, "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(SSERealmServiceClient, "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", + [ + ( + SSERealmServiceClient, + transports.SSERealmServiceGrpcTransport, + "grpc", + "true", + ), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SSERealmServiceClient, + transports.SSERealmServiceGrpcTransport, + "grpc", + "false", + ), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SSERealmServiceClient, + transports.SSERealmServiceRestTransport, + "rest", + "true", + ), + ( + SSERealmServiceClient, + transports.SSERealmServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SSERealmServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceClient), +) +@mock.patch.object( + SSERealmServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sse_realm_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SSERealmServiceClient, SSERealmServiceAsyncClient] +) +@mock.patch.object( + SSERealmServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SSERealmServiceClient), +) +@mock.patch.object( + SSERealmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SSERealmServiceAsyncClient), +) +def test_sse_realm_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [SSERealmServiceClient, SSERealmServiceAsyncClient] +) +@mock.patch.object( + SSERealmServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceClient), +) +@mock.patch.object( + SSERealmServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SSERealmServiceAsyncClient), +) +def test_sse_realm_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SSERealmServiceClient._DEFAULT_UNIVERSE + default_endpoint = SSERealmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SSERealmServiceClient._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", + [ + (SSERealmServiceClient, transports.SSERealmServiceGrpcTransport, "grpc"), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SSERealmServiceClient, transports.SSERealmServiceRestTransport, "rest"), + ], +) +def test_sse_realm_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SSERealmServiceClient, + transports.SSERealmServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (SSERealmServiceClient, transports.SSERealmServiceRestTransport, "rest", None), + ], +) +def test_sse_realm_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_sse_realm_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.network_security_v1.services.sse_realm_service.transports.SSERealmServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SSERealmServiceClient( + 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", + [ + ( + SSERealmServiceClient, + transports.SSERealmServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SSERealmServiceAsyncClient, + transports.SSERealmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sse_realm_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACRealmsRequest(), + {}, + ], +) +def test_list_sac_realms(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACRealmsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_sac_realms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.ListSACRealmsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACRealmsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_sac_realms_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 = SSERealmServiceClient( + 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 = sse_realm.ListSACRealmsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sac_realms(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACRealmsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_sac_realms_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 = SSERealmServiceClient( + 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_sac_realms 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_sac_realms] = mock_rpc + request = {} + client.list_sac_realms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sac_realms(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_sac_realms_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 = SSERealmServiceAsyncClient( + 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_sac_realms + 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_sac_realms + ] = mock_rpc + + request = {} + await client.list_sac_realms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_sac_realms(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACRealmsRequest(), + {}, + ], +) +async def test_list_sac_realms_async(request_type, transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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_sac_realms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACRealmsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_sac_realms(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.ListSACRealmsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACRealmsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_sac_realms_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACRealmsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + call.return_value = sse_realm.ListSACRealmsResponse() + client.list_sac_realms(request) + + # Establish that the 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_sac_realms_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.ListSACRealmsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACRealmsResponse() + ) + await client.list_sac_realms(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_sac_realms_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACRealmsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sac_realms( + 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_sac_realms_flattened_error(): + client = SSERealmServiceClient( + 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_sac_realms( + sse_realm.ListSACRealmsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sac_realms_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACRealmsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACRealmsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sac_realms( + 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_sac_realms_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_realms( + sse_realm.ListSACRealmsRequest(), + parent="parent_value", + ) + + +def test_list_sac_realms_pager(transport_name: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realms), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + next_page_token="abc", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[], + next_page_token="def", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sac_realms(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, sse_realm.SACRealm) for i in results) + + +def test_list_sac_realms_pages(transport_name: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realms), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + next_page_token="abc", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[], + next_page_token="def", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sac_realms(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_sac_realms_async_pager(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_realms), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + next_page_token="abc", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[], + next_page_token="def", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sac_realms( + 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, sse_realm.SACRealm) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sac_realms_async_pages(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_realms), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + next_page_token="abc", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[], + next_page_token="def", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_sac_realms(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", + [ + sse_realm.GetSACRealmRequest(), + {}, + ], +) +def test_get_sac_realm(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACRealm( + name="name_value", + security_service=sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS, + state=sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT, + ) + response = client.get_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.GetSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACRealm) + assert response.name == "name_value" + assert ( + response.security_service + == sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS + ) + assert response.state == sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT + + +def test_get_sac_realm_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 = SSERealmServiceClient( + 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 = sse_realm.GetSACRealmRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sac_realm(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACRealmRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = mock_rpc + request = {} + client.get_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sac_realm(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_sac_realm_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 = SSERealmServiceAsyncClient( + 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_sac_realm + 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_sac_realm + ] = mock_rpc + + request = {} + await client.get_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_sac_realm(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.GetSACRealmRequest(), + {}, + ], +) +async def test_get_sac_realm_async(request_type, transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACRealm( + name="name_value", + security_service=sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS, + state=sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT, + ) + ) + response = await client.get_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.GetSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACRealm) + assert response.name == "name_value" + assert ( + response.security_service + == sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS + ) + assert response.state == sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT + + +def test_get_sac_realm_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.GetSACRealmRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + call.return_value = sse_realm.SACRealm() + client.get_sac_realm(request) + + # Establish that the 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_sac_realm_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.GetSACRealmRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(sse_realm.SACRealm()) + await client.get_sac_realm(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_sac_realm_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACRealm() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sac_realm( + 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_sac_realm_flattened_error(): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.GetSACRealmRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sac_realm_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACRealm() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(sse_realm.SACRealm()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sac_realm( + 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_sac_realm_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_realm( + sse_realm.GetSACRealmRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACRealmRequest(), + {}, + ], +) +def test_create_sac_realm(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.CreateSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_sac_realm_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 = SSERealmServiceClient( + 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 = sse_realm.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sac_realm(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACRealmRequest( + parent="parent_value", + sac_realm_id="sac_realm_id_value", + ) + assert args[0] == request_msg + + +def test_create_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = ( + mock_rpc + ) + request = {} + client.create_sac_realm(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_sac_realm(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_sac_realm_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 = SSERealmServiceAsyncClient( + 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_sac_realm + 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_sac_realm + ] = mock_rpc + + request = {} + await client.create_sac_realm(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_sac_realm(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACRealmRequest(), + {}, + ], +) +async def test_create_sac_realm_async(request_type, transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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_sac_realm), "__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_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.CreateSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_sac_realm_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.CreateSACRealmRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_sac_realm(request) + + # Establish that the 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_sac_realm_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.CreateSACRealmRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_sac_realm(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_sac_realm_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__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_sac_realm( + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_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].sac_realm + mock_val = sse_realm.SACRealm(name="name_value") + assert arg == mock_val + arg = args[0].sac_realm_id + mock_val = "sac_realm_id_value" + assert arg == mock_val + + +def test_create_sac_realm_flattened_error(): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.CreateSACRealmRequest(), + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sac_realm_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__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_sac_realm( + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_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].sac_realm + mock_val = sse_realm.SACRealm(name="name_value") + assert arg == mock_val + arg = args[0].sac_realm_id + mock_val = "sac_realm_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sac_realm_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_realm( + sse_realm.CreateSACRealmRequest(), + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACRealmRequest(), + {}, + ], +) +def test_delete_sac_realm(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.DeleteSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_sac_realm_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 = SSERealmServiceClient( + 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 = sse_realm.DeleteSACRealmRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sac_realm(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACRealmRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = ( + mock_rpc + ) + request = {} + client.delete_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_sac_realm(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_sac_realm_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 = SSERealmServiceAsyncClient( + 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_sac_realm + 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_sac_realm + ] = mock_rpc + + request = {} + await client.delete_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_sac_realm(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACRealmRequest(), + {}, + ], +) +async def test_delete_sac_realm_async(request_type, transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.DeleteSACRealmRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_sac_realm_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.DeleteSACRealmRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_sac_realm(request) + + # Establish that the 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_sac_realm_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.DeleteSACRealmRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_sac_realm(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_sac_realm_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_sac_realm( + 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_sac_realm_flattened_error(): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.DeleteSACRealmRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sac_realm_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_sac_realm( + 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_sac_realm_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_realm( + sse_realm.DeleteSACRealmRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACAttachmentsRequest(), + {}, + ], +) +def test_list_sac_attachments(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACAttachmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_sac_attachments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.ListSACAttachmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACAttachmentsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_sac_attachments_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 = SSERealmServiceClient( + 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 = sse_realm.ListSACAttachmentsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sac_attachments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACAttachmentsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_sac_attachments_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 = SSERealmServiceClient( + 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_sac_attachments 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_sac_attachments] = ( + mock_rpc + ) + request = {} + client.list_sac_attachments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sac_attachments(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_sac_attachments_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 = SSERealmServiceAsyncClient( + 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_sac_attachments + 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_sac_attachments + ] = mock_rpc + + request = {} + await client.list_sac_attachments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_sac_attachments(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACAttachmentsRequest(), + {}, + ], +) +async def test_list_sac_attachments_async( + request_type, transport: str = "grpc_asyncio" +): + client = SSERealmServiceAsyncClient( + 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_sac_attachments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACAttachmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_sac_attachments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.ListSACAttachmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACAttachmentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_sac_attachments_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACAttachmentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + call.return_value = sse_realm.ListSACAttachmentsResponse() + client.list_sac_attachments(request) + + # Establish that the 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_sac_attachments_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.ListSACAttachmentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACAttachmentsResponse() + ) + await client.list_sac_attachments(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_sac_attachments_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACAttachmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sac_attachments( + 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_sac_attachments_flattened_error(): + client = SSERealmServiceClient( + 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_sac_attachments( + sse_realm.ListSACAttachmentsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sac_attachments_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.ListSACAttachmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACAttachmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sac_attachments( + 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_sac_attachments_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_attachments( + sse_realm.ListSACAttachmentsRequest(), + parent="parent_value", + ) + + +def test_list_sac_attachments_pager(transport_name: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + next_page_token="abc", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[], + next_page_token="def", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sac_attachments(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, sse_realm.SACAttachment) for i in results) + + +def test_list_sac_attachments_pages(transport_name: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + next_page_token="abc", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[], + next_page_token="def", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sac_attachments(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_sac_attachments_async_pager(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + next_page_token="abc", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[], + next_page_token="def", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sac_attachments( + 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, sse_realm.SACAttachment) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sac_attachments_async_pages(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + next_page_token="abc", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[], + next_page_token="def", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_sac_attachments(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", + [ + sse_realm.GetSACAttachmentRequest(), + {}, + ], +) +def test_get_sac_attachment(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACAttachment( + name="name_value", + sac_realm="sac_realm_value", + ncc_gateway="ncc_gateway_value", + state=sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT, + ) + response = client.get_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.GetSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACAttachment) + assert response.name == "name_value" + assert response.sac_realm == "sac_realm_value" + assert response.ncc_gateway == "ncc_gateway_value" + assert response.state == sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT + + +def test_get_sac_attachment_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 = SSERealmServiceClient( + 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 = sse_realm.GetSACAttachmentRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sac_attachment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACAttachmentRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment 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_sac_attachment] = ( + mock_rpc + ) + request = {} + client.get_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sac_attachment(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_sac_attachment_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 = SSERealmServiceAsyncClient( + 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_sac_attachment + 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_sac_attachment + ] = mock_rpc + + request = {} + await client.get_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_sac_attachment(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.GetSACAttachmentRequest(), + {}, + ], +) +async def test_get_sac_attachment_async(request_type, transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACAttachment( + name="name_value", + sac_realm="sac_realm_value", + ncc_gateway="ncc_gateway_value", + state=sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT, + ) + ) + response = await client.get_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.GetSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACAttachment) + assert response.name == "name_value" + assert response.sac_realm == "sac_realm_value" + assert response.ncc_gateway == "ncc_gateway_value" + assert response.state == sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT + + +def test_get_sac_attachment_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.GetSACAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + call.return_value = sse_realm.SACAttachment() + client.get_sac_attachment(request) + + # Establish that the 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_sac_attachment_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.GetSACAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACAttachment() + ) + await client.get_sac_attachment(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_sac_attachment_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACAttachment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sac_attachment( + 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_sac_attachment_flattened_error(): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.GetSACAttachmentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sac_attachment_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = sse_realm.SACAttachment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACAttachment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sac_attachment( + 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_sac_attachment_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_attachment( + sse_realm.GetSACAttachmentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACAttachmentRequest(), + {}, + ], +) +def test_create_sac_attachment(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.CreateSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_sac_attachment_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 = SSERealmServiceClient( + 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 = sse_realm.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sac_attachment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACAttachmentRequest( + parent="parent_value", + sac_attachment_id="sac_attachment_id_value", + ) + assert args[0] == request_msg + + +def test_create_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment + 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_sac_attachment] = ( + mock_rpc + ) + request = {} + client.create_sac_attachment(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_sac_attachment(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_sac_attachment_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 = SSERealmServiceAsyncClient( + 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_sac_attachment + 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_sac_attachment + ] = mock_rpc + + request = {} + await client.create_sac_attachment(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_sac_attachment(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACAttachmentRequest(), + {}, + ], +) +async def test_create_sac_attachment_async( + request_type, transport: str = "grpc_asyncio" +): + client = SSERealmServiceAsyncClient( + 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_sac_attachment), "__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_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.CreateSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_sac_attachment_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.CreateSACAttachmentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_sac_attachment(request) + + # Establish that the 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_sac_attachment_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.CreateSACAttachmentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_sac_attachment(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_sac_attachment_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__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_sac_attachment( + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_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].sac_attachment + mock_val = sse_realm.SACAttachment(name="name_value") + assert arg == mock_val + arg = args[0].sac_attachment_id + mock_val = "sac_attachment_id_value" + assert arg == mock_val + + +def test_create_sac_attachment_flattened_error(): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.CreateSACAttachmentRequest(), + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_sac_attachment_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__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_sac_attachment( + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_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].sac_attachment + mock_val = sse_realm.SACAttachment(name="name_value") + assert arg == mock_val + arg = args[0].sac_attachment_id + mock_val = "sac_attachment_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sac_attachment_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_attachment( + sse_realm.CreateSACAttachmentRequest(), + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACAttachmentRequest(), + {}, + ], +) +def test_delete_sac_attachment(request_type, transport: str = "grpc"): + client = SSERealmServiceClient( + 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_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sse_realm.DeleteSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_sac_attachment_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 = SSERealmServiceClient( + 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 = sse_realm.DeleteSACAttachmentRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sac_attachment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACAttachmentRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment + 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_sac_attachment] = ( + mock_rpc + ) + request = {} + client.delete_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_sac_attachment(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_sac_attachment_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 = SSERealmServiceAsyncClient( + 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_sac_attachment + 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_sac_attachment + ] = mock_rpc + + request = {} + await client.delete_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_sac_attachment(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 +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACAttachmentRequest(), + {}, + ], +) +async def test_delete_sac_attachment_async( + request_type, transport: str = "grpc_asyncio" +): + client = SSERealmServiceAsyncClient( + 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_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sse_realm.DeleteSACAttachmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_sac_attachment_field_headers(): + client = SSERealmServiceClient( + 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 = sse_realm.DeleteSACAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_sac_attachment(request) + + # Establish that the 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_sac_attachment_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = sse_realm.DeleteSACAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_sac_attachment(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_sac_attachment_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_sac_attachment( + 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_sac_attachment_flattened_error(): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.DeleteSACAttachmentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sac_attachment_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_sac_attachment( + 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_sac_attachment_flattened_error_async(): + client = SSERealmServiceAsyncClient( + 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_sac_attachment( + sse_realm.DeleteSACAttachmentRequest(), + name="name_value", + ) + + +def test_list_sac_realms_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 = SSERealmServiceClient( + 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_sac_realms 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_sac_realms] = mock_rpc + + request = {} + client.list_sac_realms(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sac_realms(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_sac_realms_rest_required_fields( + request_type=sse_realm.ListSACRealmsRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_realms._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_sac_realms._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sse_realm.ListSACRealmsResponse() + # 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 = sse_realm.ListSACRealmsResponse.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_sac_realms(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_sac_realms_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sac_realms._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_sac_realms_rest_flattened(): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACRealmsResponse() + + # 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 = sse_realm.ListSACRealmsResponse.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_sac_realms(**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/v1/{parent=projects/*/locations/*}/sacRealms" % client.transport._host, + args[1], + ) + + +def test_list_sac_realms_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_realms( + sse_realm.ListSACRealmsRequest(), + parent="parent_value", + ) + + +def test_list_sac_realms_rest_pager(transport: str = "rest"): + client = SSERealmServiceClient( + 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 = ( + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + next_page_token="abc", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[], + next_page_token="def", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACRealmsResponse( + sac_realms=[ + sse_realm.SACRealm(), + sse_realm.SACRealm(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(sse_realm.ListSACRealmsResponse.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_sac_realms(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sse_realm.SACRealm) for i in results) + + pages = list(client.list_sac_realms(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = mock_rpc + + request = {} + client.get_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sac_realm(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_sac_realm_rest_required_fields(request_type=sse_realm.GetSACRealmRequest): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_realm._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_sac_realm._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 = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sse_realm.SACRealm() + # 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 = sse_realm.SACRealm.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_sac_realm(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_sac_realm_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sac_realm._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_sac_realm_rest_flattened(): + client = SSERealmServiceClient( + 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 = sse_realm.SACRealm() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sacRealms/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 = sse_realm.SACRealm.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_sac_realm(**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/v1/{name=projects/*/locations/*/sacRealms/*}" % client.transport._host, + args[1], + ) + + +def test_get_sac_realm_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.GetSACRealmRequest(), + name="name_value", + ) + + +def test_create_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = ( + mock_rpc + ) + + request = {} + client.create_sac_realm(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_sac_realm(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_sac_realm_rest_required_fields( + request_type=sse_realm.CreateSACRealmRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sac_realm_id"] = "" + 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 + assert "sacRealmId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sac_realm._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sacRealmId" in jsonified_request + assert jsonified_request["sacRealmId"] == request_init["sac_realm_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sacRealmId"] = "sac_realm_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sac_realm._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "sac_realm_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" + assert "sacRealmId" in jsonified_request + assert jsonified_request["sacRealmId"] == "sac_realm_id_value" + + client = SSERealmServiceClient( + 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_sac_realm(request) + + expected_params = [ + ( + "sacRealmId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_sac_realm_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sac_realm._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "sacRealmId", + ) + ) + & set( + ( + "parent", + "sacRealmId", + "sacRealm", + ) + ) + ) + + +def test_create_sac_realm_rest_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_sac_realm(**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/v1/{parent=projects/*/locations/*}/sacRealms" % client.transport._host, + args[1], + ) + + +def test_create_sac_realm_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.CreateSACRealmRequest(), + parent="parent_value", + sac_realm=sse_realm.SACRealm(name="name_value"), + sac_realm_id="sac_realm_id_value", + ) + + +def test_delete_sac_realm_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 = SSERealmServiceClient( + 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_sac_realm 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_sac_realm] = ( + mock_rpc + ) + + request = {} + client.delete_sac_realm(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_sac_realm(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_sac_realm_rest_required_fields( + request_type=sse_realm.DeleteSACRealmRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_realm._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_sac_realm._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_sac_realm(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_sac_realm_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sac_realm._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_sac_realm_rest_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sacRealms/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_sac_realm(**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/v1/{name=projects/*/locations/*/sacRealms/*}" % client.transport._host, + args[1], + ) + + +def test_delete_sac_realm_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_realm( + sse_realm.DeleteSACRealmRequest(), + name="name_value", + ) + + +def test_list_sac_attachments_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 = SSERealmServiceClient( + 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_sac_attachments 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_sac_attachments] = ( + mock_rpc + ) + + request = {} + client.list_sac_attachments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sac_attachments(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_sac_attachments_rest_required_fields( + request_type=sse_realm.ListSACAttachmentsRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_attachments._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_sac_attachments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sse_realm.ListSACAttachmentsResponse() + # 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 = sse_realm.ListSACAttachmentsResponse.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_sac_attachments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_sac_attachments_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sac_attachments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_sac_attachments_rest_flattened(): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACAttachmentsResponse() + + # 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 = sse_realm.ListSACAttachmentsResponse.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_sac_attachments(**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/v1/{parent=projects/*/locations/*}/sacAttachments" + % client.transport._host, + args[1], + ) + + +def test_list_sac_attachments_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_attachments( + sse_realm.ListSACAttachmentsRequest(), + parent="parent_value", + ) + + +def test_list_sac_attachments_rest_pager(transport: str = "rest"): + client = SSERealmServiceClient( + 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 = ( + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + next_page_token="abc", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[], + next_page_token="def", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + ], + next_page_token="ghi", + ), + sse_realm.ListSACAttachmentsResponse( + sac_attachments=[ + sse_realm.SACAttachment(), + sse_realm.SACAttachment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + sse_realm.ListSACAttachmentsResponse.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_sac_attachments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sse_realm.SACAttachment) for i in results) + + pages = list(client.list_sac_attachments(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment 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_sac_attachment] = ( + mock_rpc + ) + + request = {} + client.get_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sac_attachment(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_sac_attachment_rest_required_fields( + request_type=sse_realm.GetSACAttachmentRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_attachment._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_sac_attachment._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 = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sse_realm.SACAttachment() + # 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 = sse_realm.SACAttachment.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_sac_attachment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_sac_attachment_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sac_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_sac_attachment_rest_flattened(): + client = SSERealmServiceClient( + 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 = sse_realm.SACAttachment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sacAttachments/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 = sse_realm.SACAttachment.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_sac_attachment(**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/v1/{name=projects/*/locations/*/sacAttachments/*}" + % client.transport._host, + args[1], + ) + + +def test_get_sac_attachment_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.GetSACAttachmentRequest(), + name="name_value", + ) + + +def test_create_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment + 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_sac_attachment] = ( + mock_rpc + ) + + request = {} + client.create_sac_attachment(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_sac_attachment(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_sac_attachment_rest_required_fields( + request_type=sse_realm.CreateSACAttachmentRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["sac_attachment_id"] = "" + 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 + assert "sacAttachmentId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sac_attachment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "sacAttachmentId" in jsonified_request + assert jsonified_request["sacAttachmentId"] == request_init["sac_attachment_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["sacAttachmentId"] = "sac_attachment_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_sac_attachment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "sac_attachment_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" + assert "sacAttachmentId" in jsonified_request + assert jsonified_request["sacAttachmentId"] == "sac_attachment_id_value" + + client = SSERealmServiceClient( + 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_sac_attachment(request) + + expected_params = [ + ( + "sacAttachmentId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_sac_attachment_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sac_attachment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "sacAttachmentId", + ) + ) + & set( + ( + "parent", + "sacAttachmentId", + "sacAttachment", + ) + ) + ) + + +def test_create_sac_attachment_rest_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_sac_attachment(**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/v1/{parent=projects/*/locations/*}/sacAttachments" + % client.transport._host, + args[1], + ) + + +def test_create_sac_attachment_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.CreateSACAttachmentRequest(), + parent="parent_value", + sac_attachment=sse_realm.SACAttachment(name="name_value"), + sac_attachment_id="sac_attachment_id_value", + ) + + +def test_delete_sac_attachment_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 = SSERealmServiceClient( + 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_sac_attachment + 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_sac_attachment] = ( + mock_rpc + ) + + request = {} + client.delete_sac_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_sac_attachment(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_sac_attachment_rest_required_fields( + request_type=sse_realm.DeleteSACAttachmentRequest, +): + transport_class = transports.SSERealmServiceRestTransport + + 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_sac_attachment._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_sac_attachment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + 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 = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_sac_attachment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_sac_attachment_rest_unset_required_fields(): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sac_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_sac_attachment_rest_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sacAttachments/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_sac_attachment(**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/v1/{name=projects/*/locations/*/sacAttachments/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_sac_attachment_rest_flattened_error(transport: str = "rest"): + client = SSERealmServiceClient( + 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_sac_attachment( + sse_realm.DeleteSACAttachmentRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SSERealmServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SSERealmServiceClient( + 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 = SSERealmServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SSERealmServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SSERealmServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SSERealmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SSERealmServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + transports.SSERealmServiceRestTransport, + ], +) +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 = SSERealmServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_sac_realms_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + call.return_value = sse_realm.ListSACRealmsResponse() + client.list_sac_realms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACRealmsRequest() + assert args[0] == request_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_sac_realm_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + call.return_value = sse_realm.SACRealm() + client.get_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACRealmRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_sac_realm_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACRealmRequest() + assert args[0] == request_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_sac_realm_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACRealmRequest() + assert args[0] == request_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_sac_attachments_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + call.return_value = sse_realm.ListSACAttachmentsResponse() + client.list_sac_attachments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACAttachmentsRequest() + assert args[0] == request_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_sac_attachment_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + call.return_value = sse_realm.SACAttachment() + client.get_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACAttachmentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_sac_attachment_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACAttachmentRequest() + assert args[0] == request_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_sac_attachment_empty_call_grpc(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACAttachmentRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SSERealmServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_sac_realms_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACRealmsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_sac_realms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACRealmsRequest() + assert args[0] == request_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_sac_realm_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACRealm( + name="name_value", + security_service=sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS, + state=sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT, + ) + ) + await client.get_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACRealmRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_sac_realm_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__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_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACRealmRequest() + assert args[0] == request_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_sac_realm_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACRealmRequest() + assert args[0] == request_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_sac_attachments_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.ListSACAttachmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_sac_attachments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACAttachmentsRequest() + assert args[0] == request_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_sac_attachment_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sse_realm.SACAttachment( + name="name_value", + sac_realm="sac_realm_value", + ncc_gateway="ncc_gateway_value", + state=sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT, + ) + ) + await client.get_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACAttachmentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_sac_attachment_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__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_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACAttachmentRequest() + assert args[0] == request_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_sac_attachment_empty_call_grpc_asyncio(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACAttachmentRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SSERealmServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_sac_realms_rest_bad_request(request_type=sse_realm.ListSACRealmsRequest): + client = SSERealmServiceClient( + 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_sac_realms(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACRealmsRequest, + dict, + ], +) +def test_list_sac_realms_rest_call_success(request_type): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACRealmsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = sse_realm.ListSACRealmsResponse.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_sac_realms(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACRealmsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sac_realms_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_list_sac_realms" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_list_sac_realms_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_list_sac_realms" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.ListSACRealmsRequest.pb(sse_realm.ListSACRealmsRequest()) + 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 = sse_realm.ListSACRealmsResponse.to_json( + sse_realm.ListSACRealmsResponse() + ) + req.return_value.content = return_value + + request = sse_realm.ListSACRealmsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sse_realm.ListSACRealmsResponse() + post_with_metadata.return_value = sse_realm.ListSACRealmsResponse(), metadata + + client.list_sac_realms( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_sac_realm_rest_bad_request(request_type=sse_realm.GetSACRealmRequest): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacRealms/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_sac_realm(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.GetSACRealmRequest, + dict, + ], +) +def test_get_sac_realm_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacRealms/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 = sse_realm.SACRealm( + name="name_value", + security_service=sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS, + state=sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT, + ) + + # 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 = sse_realm.SACRealm.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_sac_realm(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACRealm) + assert response.name == "name_value" + assert ( + response.security_service + == sse_realm.SACRealm.SecurityService.PALO_ALTO_PRISMA_ACCESS + ) + assert response.state == sse_realm.SACRealm.State.PENDING_PARTNER_ATTACHMENT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sac_realm_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_get_sac_realm" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_get_sac_realm_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_get_sac_realm" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.GetSACRealmRequest.pb(sse_realm.GetSACRealmRequest()) + 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 = sse_realm.SACRealm.to_json(sse_realm.SACRealm()) + req.return_value.content = return_value + + request = sse_realm.GetSACRealmRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sse_realm.SACRealm() + post_with_metadata.return_value = sse_realm.SACRealm(), metadata + + client.get_sac_realm( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_sac_realm_rest_bad_request( + request_type=sse_realm.CreateSACRealmRequest, +): + client = SSERealmServiceClient( + 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_sac_realm(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACRealmRequest, + dict, + ], +) +def test_create_sac_realm_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["sac_realm"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "security_service": 1, + "pairing_key": {"key": "key_value", "expire_time": {}}, + "state": 7, + } + # 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 = sse_realm.CreateSACRealmRequest.meta.fields["sac_realm"] + + 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["sac_realm"].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["sac_realm"][field])): + del request_init["sac_realm"][field][i][subfield] + else: + del request_init["sac_realm"][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_sac_realm(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_sac_realm_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_create_sac_realm" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_create_sac_realm_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_create_sac_realm" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.CreateSACRealmRequest.pb( + sse_realm.CreateSACRealmRequest() + ) + 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 = sse_realm.CreateSACRealmRequest() + 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_sac_realm( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_sac_realm_rest_bad_request( + request_type=sse_realm.DeleteSACRealmRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacRealms/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_sac_realm(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACRealmRequest, + dict, + ], +) +def test_delete_sac_realm_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacRealms/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_sac_realm(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sac_realm_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_delete_sac_realm" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_delete_sac_realm_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_delete_sac_realm" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.DeleteSACRealmRequest.pb( + sse_realm.DeleteSACRealmRequest() + ) + 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 = sse_realm.DeleteSACRealmRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_sac_realm( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_sac_attachments_rest_bad_request( + request_type=sse_realm.ListSACAttachmentsRequest, +): + client = SSERealmServiceClient( + 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_sac_attachments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.ListSACAttachmentsRequest, + dict, + ], +) +def test_list_sac_attachments_rest_call_success(request_type): + client = SSERealmServiceClient( + 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 = sse_realm.ListSACAttachmentsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = sse_realm.ListSACAttachmentsResponse.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_sac_attachments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSACAttachmentsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sac_attachments_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_list_sac_attachments" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_list_sac_attachments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_list_sac_attachments" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.ListSACAttachmentsRequest.pb( + sse_realm.ListSACAttachmentsRequest() + ) + 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 = sse_realm.ListSACAttachmentsResponse.to_json( + sse_realm.ListSACAttachmentsResponse() + ) + req.return_value.content = return_value + + request = sse_realm.ListSACAttachmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sse_realm.ListSACAttachmentsResponse() + post_with_metadata.return_value = ( + sse_realm.ListSACAttachmentsResponse(), + metadata, + ) + + client.list_sac_attachments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_sac_attachment_rest_bad_request( + request_type=sse_realm.GetSACAttachmentRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacAttachments/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_sac_attachment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.GetSACAttachmentRequest, + dict, + ], +) +def test_get_sac_attachment_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacAttachments/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 = sse_realm.SACAttachment( + name="name_value", + sac_realm="sac_realm_value", + ncc_gateway="ncc_gateway_value", + state=sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT, + ) + + # 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 = sse_realm.SACAttachment.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_sac_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sse_realm.SACAttachment) + assert response.name == "name_value" + assert response.sac_realm == "sac_realm_value" + assert response.ncc_gateway == "ncc_gateway_value" + assert response.state == sse_realm.SACAttachment.State.PENDING_PARTNER_ATTACHMENT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sac_attachment_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_get_sac_attachment" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_get_sac_attachment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_get_sac_attachment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.GetSACAttachmentRequest.pb( + sse_realm.GetSACAttachmentRequest() + ) + 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 = sse_realm.SACAttachment.to_json(sse_realm.SACAttachment()) + req.return_value.content = return_value + + request = sse_realm.GetSACAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sse_realm.SACAttachment() + post_with_metadata.return_value = sse_realm.SACAttachment(), metadata + + client.get_sac_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_sac_attachment_rest_bad_request( + request_type=sse_realm.CreateSACAttachmentRequest, +): + client = SSERealmServiceClient( + 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_sac_attachment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.CreateSACAttachmentRequest, + dict, + ], +) +def test_create_sac_attachment_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["sac_attachment"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "sac_realm": "sac_realm_value", + "ncc_gateway": "ncc_gateway_value", + "state": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = sse_realm.CreateSACAttachmentRequest.meta.fields["sac_attachment"] + + 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["sac_attachment"].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["sac_attachment"][field])): + del request_init["sac_attachment"][field][i][subfield] + else: + del request_init["sac_attachment"][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_sac_attachment(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_sac_attachment_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_create_sac_attachment" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_create_sac_attachment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_create_sac_attachment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.CreateSACAttachmentRequest.pb( + sse_realm.CreateSACAttachmentRequest() + ) + 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 = sse_realm.CreateSACAttachmentRequest() + 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_sac_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_sac_attachment_rest_bad_request( + request_type=sse_realm.DeleteSACAttachmentRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacAttachments/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_sac_attachment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sse_realm.DeleteSACAttachmentRequest, + dict, + ], +) +def test_delete_sac_attachment_rest_call_success(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sacAttachments/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_sac_attachment(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sac_attachment_rest_interceptors(null_interceptor): + transport = transports.SSERealmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SSERealmServiceRestInterceptor(), + ) + client = SSERealmServiceClient(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.SSERealmServiceRestInterceptor, "post_delete_sac_attachment" + ) as post, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, + "post_delete_sac_attachment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SSERealmServiceRestInterceptor, "pre_delete_sac_attachment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sse_realm.DeleteSACAttachmentRequest.pb( + sse_realm.DeleteSACAttachmentRequest() + ) + 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 = sse_realm.DeleteSACAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_sac_attachment( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceClient( + 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_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # 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.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/addressGroups/sample3"}, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "resource": "projects/sample1/locations/sample2/addressGroups/sample3" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # 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.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_sac_realms_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sac_realms), "__call__") as call: + client.list_sac_realms(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACRealmsRequest() + assert args[0] == request_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_sac_realm_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sac_realm), "__call__") as call: + client.get_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACRealmRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_sac_realm_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sac_realm), "__call__") as call: + client.create_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACRealmRequest() + assert args[0] == request_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_sac_realm_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sac_realm), "__call__") as call: + client.delete_sac_realm(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACRealmRequest() + assert args[0] == request_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_sac_attachments_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sac_attachments), "__call__" + ) as call: + client.list_sac_attachments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.ListSACAttachmentsRequest() + assert args[0] == request_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_sac_attachment_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_sac_attachment), "__call__" + ) as call: + client.get_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.GetSACAttachmentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_sac_attachment_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_sac_attachment), "__call__" + ) as call: + client.create_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.CreateSACAttachmentRequest() + assert args[0] == request_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_sac_attachment_empty_call_rest(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_sac_attachment), "__call__" + ) as call: + client.delete_sac_attachment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sse_realm.DeleteSACAttachmentRequest() + assert args[0] == request_msg + + +def test_sse_realm_service_rest_lro_client(): + client = SSERealmServiceClient( + 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 = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SSERealmServiceGrpcTransport, + ) + + +def test_sse_realm_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SSERealmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sse_realm_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_security_v1.services.sse_realm_service.transports.SSERealmServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SSERealmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_sac_realms", + "get_sac_realm", + "create_sac_realm", + "delete_sac_realm", + "list_sac_attachments", + "get_sac_attachment", + "create_sac_attachment", + "delete_sac_attachment", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_sse_realm_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.network_security_v1.services.sse_realm_service.transports.SSERealmServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SSERealmServiceTransport( + 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",), + quota_project_id="octopus", + ) + + +def test_sse_realm_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.network_security_v1.services.sse_realm_service.transports.SSERealmServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SSERealmServiceTransport() + adc.assert_called_once() + + +def test_sse_realm_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SSERealmServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + ], +) +def test_sse_realm_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + transports.SSERealmServiceRestTransport, + ], +) +def test_sse_realm_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SSERealmServiceGrpcTransport, grpc_helpers), + (transports.SSERealmServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sse_realm_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + ], +) +def test_sse_realm_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_sse_realm_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SSERealmServiceRestTransport( + 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_sse_realm_service_host_no_port(transport_name): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_sse_realm_service_host_with_port(transport_name): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "networksecurity.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_sse_realm_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SSERealmServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SSERealmServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_sac_realms._session + session2 = client2.transport.list_sac_realms._session + assert session1 != session2 + session1 = client1.transport.get_sac_realm._session + session2 = client2.transport.get_sac_realm._session + assert session1 != session2 + session1 = client1.transport.create_sac_realm._session + session2 = client2.transport.create_sac_realm._session + assert session1 != session2 + session1 = client1.transport.delete_sac_realm._session + session2 = client2.transport.delete_sac_realm._session + assert session1 != session2 + session1 = client1.transport.list_sac_attachments._session + session2 = client2.transport.list_sac_attachments._session + assert session1 != session2 + session1 = client1.transport.get_sac_attachment._session + session2 = client2.transport.get_sac_attachment._session + assert session1 != session2 + session1 = client1.transport.create_sac_attachment._session + session2 = client2.transport.create_sac_attachment._session + assert session1 != session2 + session1 = client1.transport.delete_sac_attachment._session + session2 = client2.transport.delete_sac_attachment._session + assert session1 != session2 + + +def test_sse_realm_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SSERealmServiceGrpcTransport( + 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_sse_realm_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SSERealmServiceGrpcAsyncIOTransport( + 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.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + ], +) +def test_sse_realm_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SSERealmServiceGrpcTransport, + transports.SSERealmServiceGrpcAsyncIOTransport, + ], +) +def test_sse_realm_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_sse_realm_service_grpc_lro_client(): + client = SSERealmServiceClient( + 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_sse_realm_service_grpc_lro_async_client(): + client = SSERealmServiceAsyncClient( + 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_sac_attachment_path(): + project = "squid" + location = "clam" + sac_attachment = "whelk" + expected = "projects/{project}/locations/{location}/sacAttachments/{sac_attachment}".format( + project=project, + location=location, + sac_attachment=sac_attachment, + ) + actual = SSERealmServiceClient.sac_attachment_path( + project, location, sac_attachment + ) + assert expected == actual + + +def test_parse_sac_attachment_path(): + expected = { + "project": "octopus", + "location": "oyster", + "sac_attachment": "nudibranch", + } + path = SSERealmServiceClient.sac_attachment_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_sac_attachment_path(path) + assert expected == actual + + +def test_sac_realm_path(): + project = "cuttlefish" + location = "mussel" + sac_realm = "winkle" + expected = "projects/{project}/locations/{location}/sacRealms/{sac_realm}".format( + project=project, + location=location, + sac_realm=sac_realm, + ) + actual = SSERealmServiceClient.sac_realm_path(project, location, sac_realm) + assert expected == actual + + +def test_parse_sac_realm_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "sac_realm": "abalone", + } + path = SSERealmServiceClient.sac_realm_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_sac_realm_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SSERealmServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = SSERealmServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SSERealmServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = SSERealmServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SSERealmServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = SSERealmServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = SSERealmServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = SSERealmServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SSERealmServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = SSERealmServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SSERealmServiceClient.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.SSERealmServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SSERealmServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SSERealmServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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_cancel_operation_flattened(): + client = SSERealmServiceClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = SSERealmServiceAsyncClient( + 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) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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_get_operation_flattened(): + client = SSERealmServiceClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = SSERealmServiceAsyncClient( + 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() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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_operations_flattened(): + client = SSERealmServiceClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = SSERealmServiceAsyncClient( + 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() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_list_locations(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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_list_locations_flattened(): + client = SSERealmServiceClient( + 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() + + client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +@pytest.mark.asyncio +async def test_list_locations_flattened_async(): + client = SSERealmServiceAsyncClient( + 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() + ) + await client.list_locations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.ListLocationsRequest() + + +def test_get_location(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient(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 = SSERealmServiceAsyncClient(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 = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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_get_location_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +@pytest.mark.asyncio +async def test_get_location_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # 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() + ) + await client.get_location() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == locations_pb2.GetLocationRequest() + + +def test_set_iam_policy(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the 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, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(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 response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the 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, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(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 response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SSERealmServiceClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the 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", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SSERealmServiceAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(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", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = SSERealmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SSERealmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_transport_close_grpc(): + client = SSERealmServiceClient( + 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 = SSERealmServiceAsyncClient( + 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 = SSERealmServiceClient( + 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 = SSERealmServiceClient( + 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", + [ + (SSERealmServiceClient, transports.SSERealmServiceGrpcTransport), + (SSERealmServiceAsyncClient, transports.SSERealmServiceGrpcAsyncIOTransport), + ], +) +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-private-ca/google/cloud/security/privateca/__init__.py b/packages/google-cloud-private-ca/google/cloud/security/privateca/__init__.py index e6d757d998d8..78f274121bee 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca/__init__.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca/__init__.py @@ -36,6 +36,7 @@ CertificateIdentityConstraints, CertificateRevocationList, CertificateTemplate, + EncryptionSpec, KeyUsage, ObjectId, PublicKey, @@ -101,6 +102,7 @@ "CertificateIdentityConstraints", "CertificateRevocationList", "CertificateTemplate", + "EncryptionSpec", "KeyUsage", "ObjectId", "PublicKey", diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/__init__.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/__init__.py index c521c455d0f1..16edba16d777 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/__init__.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/__init__.py @@ -39,6 +39,7 @@ CertificateIdentityConstraints, CertificateRevocationList, CertificateTemplate, + EncryptionSpec, KeyUsage, ObjectId, PublicKey, @@ -198,6 +199,7 @@ def _get_version(dependency_name): "DeleteCertificateTemplateRequest", "DisableCertificateAuthorityRequest", "EnableCertificateAuthorityRequest", + "EncryptionSpec", "FetchCaCertsRequest", "FetchCaCertsResponse", "FetchCertificateAuthorityCsrRequest", diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py index 846a8c59f778..7f3d3962fdee 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py @@ -661,10 +661,20 @@ async def sample_list_certificates(): The request object. Request message for [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. parent (:class:`str`): - Required. The resource name of the location associated + Required. The resource name of the parent associated with the [Certificates][google.cloud.security.privateca.v1.Certificate], - in the format ``projects/*/locations/*/caPools/*``. + in the format ``projects/*/locations/*/caPools/*``. The + parent resource name can be in one of two forms: + + 1. **Specific CA Pool:** To list certificates within a + single CA Pool: ``projects/*/locations/*/caPools/*`` + + 2. **All CA Pools in a Location:** To list certificates + across *all* CA Pools in a given project and + location, use the wildcard character (``-``) in place + of the CA Pool ID. Example: + ``projects/*/locations/*/caPools/-`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py index 3928a970d2f3..49317ab34b9e 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py @@ -1158,10 +1158,20 @@ def sample_list_certificates(): The request object. Request message for [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. parent (str): - Required. The resource name of the location associated + Required. The resource name of the parent associated with the [Certificates][google.cloud.security.privateca.v1.Certificate], - in the format ``projects/*/locations/*/caPools/*``. + in the format ``projects/*/locations/*/caPools/*``. The + parent resource name can be in one of two forms: + + 1. **Specific CA Pool:** To list certificates within a + single CA Pool: ``projects/*/locations/*/caPools/*`` + + 2. **All CA Pools in a Location:** To list certificates + across *all* CA Pools in a given project and + location, use the wildcard character (``-``) in place + of the CA Pool ID. Example: + ``projects/*/locations/*/caPools/-`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/__init__.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/__init__.py index 7a2b359b67c0..904d458cf5db 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/__init__.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/__init__.py @@ -25,6 +25,7 @@ CertificateIdentityConstraints, CertificateRevocationList, CertificateTemplate, + EncryptionSpec, KeyUsage, ObjectId, PublicKey, @@ -88,6 +89,7 @@ "CertificateIdentityConstraints", "CertificateRevocationList", "CertificateTemplate", + "EncryptionSpec", "KeyUsage", "ObjectId", "PublicKey", diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/resources.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/resources.py index d4d05203716a..2b0f0f99c473 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/resources.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/resources.py @@ -30,6 +30,7 @@ "SubjectRequestMode", "CertificateAuthority", "CaPool", + "EncryptionSpec", "CertificateRevocationList", "Certificate", "CertificateTemplate", @@ -656,6 +657,14 @@ class CaPool(proto.Message): from any [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] in this [CaPool][google.cloud.security.privateca.v1.CaPool]. + encryption_spec (google.cloud.security.privateca_v1.types.EncryptionSpec): + Optional. When + [EncryptionSpec][google.cloud.security.privateca.v1.EncryptionSpec] + is provided, the + [Subject][google.cloud.security.privateca.v1.Subject], + [SubjectAltNames][google.cloud.security.privateca.v1.SubjectAltNames], + and the PEM-encoded certificate fields will be encrypted at + rest. labels (MutableMapping[str, str]): Optional. Labels with user-defined metadata. """ @@ -761,16 +770,30 @@ class IssuancePolicy(proto.Message): match one of the key types listed here. Otherwise, any key may be used. backdate_duration (google.protobuf.duration_pb2.Duration): - Optional. The duration to backdate all certificates issued - from this - [CaPool][google.cloud.security.privateca.v1.CaPool]. If not - set, the certificates will be issued with a not_before_time - of the issuance time (i.e. the current time). If set, the - certificates will be issued with a not_before_time of the - issuance time minus the backdate_duration. The - not_after_time will be adjusted to preserve the requested - lifetime. The backdate_duration must be less than or equal - to 48 hours. + Optional. If set, all certificates issued from this + [CaPool][google.cloud.security.privateca.v1.CaPool] will be + backdated by this duration. The 'not_before_time' will be + the issuance time minus this + [backdate_duration][google.cloud.security.privateca.v1.CaPool.IssuancePolicy.backdate_duration], + and the 'not_after_time' will be adjusted to preserve the + requested lifetime. The maximum duration that a certificate + can be backdated with these options is 48 hours in the past. + This option cannot be set if + [allow_requester_specified_not_before_time][google.cloud.security.privateca.v1.CaPool.IssuancePolicy.allow_requester_specified_not_before_time] + is set. + allow_requester_specified_not_before_time (bool): + Optional. If set to true, allows requesters to specify the + [requested_not_before_time][google.cloud.security.privateca.v1.Certificate.requested_not_before_time] + field when creating a + [Certificate][google.cloud.security.privateca.v1.Certificate]. + Certificates requested with this option enabled will have a + 'not_before_time' equal to the value specified in the + request. The 'not_after_time' will be adjusted to preserve + the requested lifetime. The maximum time that a certificate + can be backdated with these options is 48 hours in the past. + This option cannot be set if + [backdate_duration][google.cloud.security.privateca.v1.CaPool.IssuancePolicy.backdate_duration] + is set. maximum_lifetime (google.protobuf.duration_pb2.Duration): Optional. The maximum lifetime allowed for issued [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -983,6 +1006,10 @@ class IssuanceModes(proto.Message): number=7, message=duration_pb2.Duration, ) + allow_requester_specified_not_before_time: bool = proto.Field( + proto.BOOL, + number=8, + ) maximum_lifetime: duration_pb2.Duration = proto.Field( proto.MESSAGE, number=2, @@ -1028,6 +1055,11 @@ class IssuanceModes(proto.Message): number=4, message=PublishingOptions, ) + encryption_spec: "EncryptionSpec" = proto.Field( + proto.MESSAGE, + number=8, + message="EncryptionSpec", + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -1035,6 +1067,21 @@ class IssuanceModes(proto.Message): ) +class EncryptionSpec(proto.Message): + r"""The configuration used for encrypting data at rest. + + Attributes: + cloud_kms_key (str): + The resource name for a Cloud KMS key in the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + """ + + cloud_kms_key: str = proto.Field( + proto.STRING, + number=1, + ) + + class CertificateRevocationList(proto.Message): r"""A [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] @@ -1261,6 +1308,24 @@ class Certificate(proto.Message): was updated. labels (MutableMapping[str, str]): Optional. Labels with user-defined metadata. + requested_not_before_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The requested + [not_before_time][google.cloud.security.privateca.v1.CertificateDescription.SubjectDescription.not_before_time] + of this + [Certificate][google.cloud.security.privateca.v1.Certificate]. + This field may only be set if the + [CaPool.IssuancePolicy.allow_requester_specified_not_before_time][google.cloud.security.privateca.v1.CaPool.IssuancePolicy.allow_requester_specified_not_before_time] + field is set to true for the issuing + [CaPool][google.cloud.security.privateca.v1.CaPool]. + + If this field is specified, the certificate will be issued + with this 'not_before_time'. If this is not specified, the + 'not_before_time' will be set to the issuance time or + issuance time minus + [backdate_duration][google.cloud.security.privateca.v1.CaPool.IssuancePolicy.backdate_duration] + depending on the + [CaPool][google.cloud.security.privateca.v1.CaPool] + configuration. """ class RevocationDetails(proto.Message): @@ -1355,6 +1420,11 @@ class RevocationDetails(proto.Message): proto.STRING, number=14, ) + requested_not_before_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) class CertificateTemplate(proto.Message): diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/service.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/service.py index 6a62eba7dc48..49e8fd430019 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/service.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/types/service.py @@ -199,10 +199,19 @@ class ListCertificatesRequest(proto.Message): Attributes: parent (str): - Required. The resource name of the location associated with + Required. The resource name of the parent associated with the [Certificates][google.cloud.security.privateca.v1.Certificate], - in the format ``projects/*/locations/*/caPools/*``. + in the format ``projects/*/locations/*/caPools/*``. The + parent resource name can be in one of two forms: + + 1. **Specific CA Pool:** To list certificates within a + single CA Pool: ``projects/*/locations/*/caPools/*`` + + 2. **All CA Pools in a Location:** To list certificates + across *all* CA Pools in a given project and location, + use the wildcard character (``-``) in place of the CA + Pool ID. Example: ``projects/*/locations/*/caPools/-`` page_size (int): Optional. Limit on the number of [Certificates][google.cloud.security.privateca.v1.Certificate] diff --git a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py index 3768c353dd36..f583493c6f31 100644 --- a/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py +++ b/packages/google-cloud-private-ca/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py @@ -20440,6 +20440,7 @@ def test_create_certificate_rest_call_success(request_type): "create_time": {}, "update_time": {}, "labels": {}, + "requested_not_before_time": {}, } # 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 @@ -21233,6 +21234,7 @@ def test_update_certificate_rest_call_success(request_type): "create_time": {}, "update_time": {}, "labels": {}, + "requested_not_before_time": {}, } # 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 @@ -23297,6 +23299,7 @@ def test_create_ca_pool_rest_call_success(request_type): } ], "backdate_duration": {"seconds": 751, "nanos": 543}, + "allow_requester_specified_not_before_time": True, "maximum_lifetime": {}, "allowed_issuance_modes": { "allow_csr_based_issuance": True, @@ -23387,6 +23390,7 @@ def test_create_ca_pool_rest_call_success(request_type): "publish_crl": True, "encoding_format": 1, }, + "encryption_spec": {"cloud_kms_key": "cloud_kms_key_value"}, "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -23593,6 +23597,7 @@ def test_update_ca_pool_rest_call_success(request_type): } ], "backdate_duration": {"seconds": 751, "nanos": 543}, + "allow_requester_specified_not_before_time": True, "maximum_lifetime": {}, "allowed_issuance_modes": { "allow_csr_based_issuance": True, @@ -23683,6 +23688,7 @@ def test_update_ca_pool_rest_call_success(request_type): "publish_crl": True, "encoding_format": 1, }, + "encryption_spec": {"cloud_kms_key": "cloud_kms_key_value"}, "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight.py index 1c52cacd674b..92b98ebc716f 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight.py @@ -38,7 +38,7 @@ class Insight(proto.Message): Attributes: name (str): - Name of the insight. + Identifier. Name of the insight. description (str): Free-form human readable summary in English. The maximum length is 500 characters. diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight_type_config.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight_type_config.py index 5768a2038d98..33eac67af521 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight_type_config.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/insight_type_config.py @@ -35,7 +35,7 @@ class InsightTypeConfig(proto.Message): Attributes: name (str): - Name of insight type config. Eg, + Identifier. Name of insight type config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/config insight_type_generation_config (google.cloud.recommender_v1.types.InsightTypeGenerationConfig): InsightTypeGenerationConfig which configures diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommendation.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommendation.py index 675b9897ead3..eb6f4150ba74 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommendation.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommendation.py @@ -48,7 +48,7 @@ class Recommendation(proto.Message): Attributes: name (str): - Name of recommendation. + Identifier. Name of recommendation. description (str): Free-form human readable summary in English. The maximum length is 500 characters. @@ -97,6 +97,9 @@ class Recommendation(proto.Message): exclusive group. This means that only one recommendation within the group is suggested to be applied. + target_resources (MutableSequence[str]): + Fully qualified resource names that this + recommendation is targeting. """ class Priority(proto.Enum): @@ -194,6 +197,10 @@ class InsightReference(proto.Message): proto.STRING, number=18, ) + target_resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=19, + ) class RecommendationContent(proto.Message): @@ -577,6 +584,9 @@ class Impact(proto.Message): Use with CategoryType.RELIABILITY This field is a member of `oneof`_ ``projection``. + service (str): + The service that this impact is associated + with. """ class Category(proto.Enum): @@ -643,6 +653,10 @@ class Category(proto.Enum): oneof="projection", message="ReliabilityProjection", ) + service: str = proto.Field( + proto.STRING, + number=3, + ) class RecommendationStateInfo(proto.Message): diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommender_config.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommender_config.py index 5fddafa3cc04..9bc072a07a4e 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommender_config.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/types/recommender_config.py @@ -35,7 +35,7 @@ class RecommenderConfig(proto.Message): Attributes: name (str): - Name of recommender config. Eg, + Identifier. Name of recommender config. Eg, projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/config recommender_generation_config (google.cloud.recommender_v1.types.RecommenderGenerationConfig): RecommenderGenerationConfig which configures diff --git a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py index 7072b64e113a..a3b2f53fb2de 100644 --- a/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py +++ b/packages/google-cloud-recommender/tests/unit/gapic/recommender_v1/test_recommender.py @@ -3135,6 +3135,7 @@ def test_get_recommendation(request_type, transport: str = "grpc"): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) response = client.get_recommendation(request) @@ -3152,6 +3153,7 @@ def test_get_recommendation(request_type, transport: str = "grpc"): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_get_recommendation_non_empty_request_with_auto_populated_field(): @@ -3297,6 +3299,7 @@ async def test_get_recommendation_async(request_type, transport: str = "grpc_asy priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) response = await client.get_recommendation(request) @@ -3315,6 +3318,7 @@ async def test_get_recommendation_async(request_type, transport: str = "grpc_asy assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_get_recommendation_field_headers(): @@ -3497,6 +3501,7 @@ def test_mark_recommendation_dismissed(request_type, transport: str = "grpc"): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) response = client.mark_recommendation_dismissed(request) @@ -3514,6 +3519,7 @@ def test_mark_recommendation_dismissed(request_type, transport: str = "grpc"): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_dismissed_non_empty_request_with_auto_populated_field(): @@ -3664,6 +3670,7 @@ async def test_mark_recommendation_dismissed_async( priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) response = await client.mark_recommendation_dismissed(request) @@ -3682,6 +3689,7 @@ async def test_mark_recommendation_dismissed_async( assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_dismissed_field_headers(): @@ -3778,6 +3786,7 @@ def test_mark_recommendation_claimed(request_type, transport: str = "grpc"): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) response = client.mark_recommendation_claimed(request) @@ -3795,6 +3804,7 @@ def test_mark_recommendation_claimed(request_type, transport: str = "grpc"): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_claimed_non_empty_request_with_auto_populated_field(): @@ -3945,6 +3955,7 @@ async def test_mark_recommendation_claimed_async( priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) response = await client.mark_recommendation_claimed(request) @@ -3963,6 +3974,7 @@ async def test_mark_recommendation_claimed_async( assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_claimed_field_headers(): @@ -4165,6 +4177,7 @@ def test_mark_recommendation_succeeded(request_type, transport: str = "grpc"): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) response = client.mark_recommendation_succeeded(request) @@ -4182,6 +4195,7 @@ def test_mark_recommendation_succeeded(request_type, transport: str = "grpc"): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_succeeded_non_empty_request_with_auto_populated_field(): @@ -4332,6 +4346,7 @@ async def test_mark_recommendation_succeeded_async( priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) response = await client.mark_recommendation_succeeded(request) @@ -4350,6 +4365,7 @@ async def test_mark_recommendation_succeeded_async( assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_succeeded_field_headers(): @@ -4552,6 +4568,7 @@ def test_mark_recommendation_failed(request_type, transport: str = "grpc"): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) response = client.mark_recommendation_failed(request) @@ -4569,6 +4586,7 @@ def test_mark_recommendation_failed(request_type, transport: str = "grpc"): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_failed_non_empty_request_with_auto_populated_field(): @@ -4719,6 +4737,7 @@ async def test_mark_recommendation_failed_async( priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) response = await client.mark_recommendation_failed(request) @@ -4737,6 +4756,7 @@ async def test_mark_recommendation_failed_async( assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] def test_mark_recommendation_failed_field_headers(): @@ -9522,6 +9542,7 @@ async def test_get_recommendation_empty_call_grpc_asyncio(): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) await client.get_recommendation(request=None) @@ -9555,6 +9576,7 @@ async def test_mark_recommendation_dismissed_empty_call_grpc_asyncio(): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) await client.mark_recommendation_dismissed(request=None) @@ -9588,6 +9610,7 @@ async def test_mark_recommendation_claimed_empty_call_grpc_asyncio(): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) await client.mark_recommendation_claimed(request=None) @@ -9621,6 +9644,7 @@ async def test_mark_recommendation_succeeded_empty_call_grpc_asyncio(): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) await client.mark_recommendation_succeeded(request=None) @@ -9654,6 +9678,7 @@ async def test_mark_recommendation_failed_empty_call_grpc_asyncio(): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) ) await client.mark_recommendation_failed(request=None) @@ -10416,6 +10441,7 @@ def test_get_recommendation_rest_call_success(request_type): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) # Wrap the value into a proper Response obj @@ -10438,6 +10464,7 @@ def test_get_recommendation_rest_call_success(request_type): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10563,6 +10590,7 @@ def test_mark_recommendation_dismissed_rest_call_success(request_type): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) # Wrap the value into a proper Response obj @@ -10585,6 +10613,7 @@ def test_mark_recommendation_dismissed_rest_call_success(request_type): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10710,6 +10739,7 @@ def test_mark_recommendation_claimed_rest_call_success(request_type): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) # Wrap the value into a proper Response obj @@ -10732,6 +10762,7 @@ def test_mark_recommendation_claimed_rest_call_success(request_type): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10857,6 +10888,7 @@ def test_mark_recommendation_succeeded_rest_call_success(request_type): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) # Wrap the value into a proper Response obj @@ -10879,6 +10911,7 @@ def test_mark_recommendation_succeeded_rest_call_success(request_type): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -11004,6 +11037,7 @@ def test_mark_recommendation_failed_rest_call_success(request_type): priority=recommendation.Recommendation.Priority.P4, etag="etag_value", xor_group_id="xor_group_id_value", + target_resources=["target_resources_value"], ) # Wrap the value into a proper Response obj @@ -11026,6 +11060,7 @@ def test_mark_recommendation_failed_rest_call_success(request_type): assert response.priority == recommendation.Recommendation.Priority.P4 assert response.etag == "etag_value" assert response.xor_group_id == "xor_group_id_value" + assert response.target_resources == ["target_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt/__init__.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt/__init__.py index bffde2ad38f7..82d2df2bf8d7 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt/__init__.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt/__init__.py @@ -33,12 +33,16 @@ from google.cloud.saasplatform_saasservicemgmt_v1beta1.types.common import ( Aggregate, Blueprint, + SaasCondition, UnitCondition, UnitOperationCondition, UnitOperationErrorCategory, UnitVariable, ) from google.cloud.saasplatform_saasservicemgmt_v1beta1.types.deployments_resources import ( + AppParams, + ComponentRef, + CompositeRef, Dependency, Deprovision, FromMapping, @@ -124,10 +128,14 @@ "SaasRolloutsAsyncClient", "Aggregate", "Blueprint", + "SaasCondition", "UnitCondition", "UnitOperationCondition", "UnitVariable", "UnitOperationErrorCategory", + "AppParams", + "ComponentRef", + "CompositeRef", "Dependency", "Deprovision", "FromMapping", diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/__init__.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/__init__.py index 76ac0eac9bd5..8eaafcd4bde3 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/__init__.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/__init__.py @@ -30,12 +30,16 @@ from .types.common import ( Aggregate, Blueprint, + SaasCondition, UnitCondition, UnitOperationCondition, UnitOperationErrorCategory, UnitVariable, ) from .types.deployments_resources import ( + AppParams, + ComponentRef, + CompositeRef, Dependency, Deprovision, FromMapping, @@ -203,7 +207,10 @@ def _get_version(dependency_name): "SaasDeploymentsAsyncClient", "SaasRolloutsAsyncClient", "Aggregate", + "AppParams", "Blueprint", + "ComponentRef", + "CompositeRef", "CreateReleaseRequest", "CreateRolloutKindRequest", "CreateRolloutRequest", @@ -257,6 +264,7 @@ def _get_version(dependency_name): "RolloutKind", "RolloutStats", "Saas", + "SaasCondition", "SaasDeploymentsClient", "SaasRolloutsClient", "Schedule", diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/async_client.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/async_client.py index 3baddb461f02..9da1dee210d8 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/async_client.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/async_client.py @@ -48,6 +48,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -86,6 +87,20 @@ class SaasDeploymentsAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = SaasDeploymentsClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = SaasDeploymentsClient._DEFAULT_UNIVERSE + application_path = staticmethod(SaasDeploymentsClient.application_path) + parse_application_path = staticmethod(SaasDeploymentsClient.parse_application_path) + application_template_path = staticmethod( + SaasDeploymentsClient.application_template_path + ) + parse_application_template_path = staticmethod( + SaasDeploymentsClient.parse_application_template_path + ) + application_template_revision_path = staticmethod( + SaasDeploymentsClient.application_template_revision_path + ) + parse_application_template_revision_path = staticmethod( + SaasDeploymentsClient.parse_application_template_revision_path + ) release_path = staticmethod(SaasDeploymentsClient.release_path) parse_release_path = staticmethod(SaasDeploymentsClient.parse_release_path) rollout_path = staticmethod(SaasDeploymentsClient.rollout_path) @@ -2979,7 +2994,7 @@ async def sample_get_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. @@ -3127,7 +3142,7 @@ async def sample_create_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. @@ -3276,7 +3291,7 @@ async def sample_update_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/client.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/client.py index b9f3028ce6f6..4240d6c3c6ea 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/client.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/client.py @@ -65,6 +65,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore @@ -239,6 +240,80 @@ def transport(self) -> SaasDeploymentsTransport: """ return self._transport + @staticmethod + def application_path( + project: str, + location: str, + application: str, + ) -> str: + """Returns a fully-qualified application string.""" + return ( + "projects/{project}/locations/{location}/applications/{application}".format( + project=project, + location=location, + application=application, + ) + ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str, str]: + """Parses a application path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/applications/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def application_template_path( + project: str, + location: str, + space: str, + applicationTemplate: str, + ) -> str: + """Returns a fully-qualified application_template string.""" + return "projects/{project}/locations/{location}/spaces/{space}/applicationTemplates/{applicationTemplate}".format( + project=project, + location=location, + space=space, + applicationTemplate=applicationTemplate, + ) + + @staticmethod + def parse_application_template_path(path: str) -> Dict[str, str]: + """Parses a application_template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/spaces/(?P.+?)/applicationTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def application_template_revision_path( + project: str, + location: str, + space: str, + application_template: str, + revision: str, + ) -> str: + """Returns a fully-qualified application_template_revision string.""" + return "projects/{project}/locations/{location}/spaces/{space}/applicationTemplates/{application_template}/revisions/{revision}".format( + project=project, + location=location, + space=space, + application_template=application_template, + revision=revision, + ) + + @staticmethod + def parse_application_template_revision_path(path: str) -> Dict[str, str]: + """Parses a application_template_revision path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/spaces/(?P.+?)/applicationTemplates/(?P.+?)/revisions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def release_path( project: str, @@ -3472,7 +3547,7 @@ def sample_get_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. @@ -3617,7 +3692,7 @@ def sample_create_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. @@ -3763,7 +3838,7 @@ def sample_update_unit_operation(): This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/transports/rest.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/transports/rest.py index b0a3f87e2e27..2895a06572bd 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/transports/rest.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_deployments/transports/rest.py @@ -2571,7 +2571,7 @@ def __call__( This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ @@ -4151,7 +4151,7 @@ def __call__( This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ @@ -6006,7 +6006,7 @@ def __call__( This is a base object that contains the common fields in all unit operations. - Next: 19 + Next: 22 """ diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/async_client.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/async_client.py index ffc57a2946c5..cf622ff45262 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/async_client.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/async_client.py @@ -571,9 +571,13 @@ async def sample_create_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsAsyncClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.CreateRolloutRequest( parent="parent_value", rollout_id="rollout_id_value", + rollout=rollout, ) # Make the request @@ -700,7 +704,11 @@ async def sample_update_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsAsyncClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest( + rollout=rollout, ) # Make the request diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/client.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/client.py index 4a32fe7e780c..8940dc94e188 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/client.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/services/saas_rollouts/client.py @@ -1060,9 +1060,13 @@ def sample_create_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.CreateRolloutRequest( parent="parent_value", rollout_id="rollout_id_value", + rollout=rollout, ) # Make the request @@ -1186,7 +1190,11 @@ def sample_update_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest( + rollout=rollout, ) # Make the request diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/__init__.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/__init__.py index 63c42a47fb2a..c557ee143df6 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/__init__.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/__init__.py @@ -16,12 +16,16 @@ from .common import ( Aggregate, Blueprint, + SaasCondition, UnitCondition, UnitOperationCondition, UnitOperationErrorCategory, UnitVariable, ) from .deployments_resources import ( + AppParams, + ComponentRef, + CompositeRef, Dependency, Deprovision, FromMapping, @@ -103,10 +107,14 @@ __all__ = ( "Aggregate", "Blueprint", + "SaasCondition", "UnitCondition", "UnitOperationCondition", "UnitVariable", "UnitOperationErrorCategory", + "AppParams", + "ComponentRef", + "CompositeRef", "Dependency", "Deprovision", "FromMapping", diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py index 84c92f3dc793..95ae157c6029 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py @@ -28,6 +28,7 @@ "UnitVariable", "UnitCondition", "UnitOperationCondition", + "SaasCondition", "Aggregate", }, ) @@ -114,7 +115,8 @@ class UnitVariable(proto.Message): """ class Type(proto.Enum): - r"""Enumeration of variable types. + r"""Enumeration of variable types. ``STRUCT`` and ``LIST`` values should + be JSON-encoded strings. Values: TYPE_UNSPECIFIED (0): @@ -125,12 +127,18 @@ class Type(proto.Enum): Variable type is int. BOOL (3): Variable type is bool. + STRUCT (4): + Variable type is struct. + LIST (5): + Variable type is list. """ TYPE_UNSPECIFIED = 0 STRING = 1 INT = 2 BOOL = 3 + STRUCT = 4 + LIST = 5 variable: str = proto.Field( proto.STRING, @@ -294,6 +302,13 @@ class Type(proto.Enum): TYPE_APP_COMPONENTS_REGISTERED (7): Indicates if services and workloads have been registered with AppHub. + TYPE_WORKLOAD_SUCCEEDED (8): + Indicates if the UnitOperation's core + workload execution completed successfully. + The workload is the core execution operation + performed for a UnitOperation (e.g., + provisioning, updating, or deprovisioning + resources) excluding post-operation checks. """ TYPE_UNSPECIFIED = 0 @@ -303,6 +318,7 @@ class Type(proto.Enum): TYPE_CANCELLED = 5 TYPE_APP_CREATED = 6 TYPE_APP_COMPONENTS_REGISTERED = 7 + TYPE_WORKLOAD_SUCCEEDED = 8 status: Status = proto.Field( proto.ENUM, @@ -329,6 +345,85 @@ class Type(proto.Enum): ) +class SaasCondition(proto.Message): + r"""SaasCondition describes the status of a Saas. + + Attributes: + status (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.SaasCondition.Status): + Required. Status of the condition. + type_ (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.SaasCondition.Type): + Required. Type of the condition. + last_transition_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Last time the condition transited + from one status to another. + message (str): + Required. Human readable message indicating + details about the last transition. + reason (str): + Required. Brief reason for the condition's + last transition. + """ + + class Status(proto.Enum): + r"""Enumeration of condition statuses. + + Values: + STATUS_UNSPECIFIED (0): + Condition status is unspecified. + STATUS_UNKNOWN (1): + Condition is unknown. + STATUS_TRUE (2): + Condition is true. + STATUS_FALSE (3): + Condition is false. + """ + + STATUS_UNSPECIFIED = 0 + STATUS_UNKNOWN = 1 + STATUS_TRUE = 2 + STATUS_FALSE = 3 + + class Type(proto.Enum): + r"""Enumeration of condition types. + + Values: + TYPE_UNSPECIFIED (0): + Condition type is unspecified. + TYPE_READY (1): + Condition type is ready. + TYPE_SYNCHRONIZED (2): + Condition type is synchronized. + """ + + TYPE_UNSPECIFIED = 0 + TYPE_READY = 1 + TYPE_SYNCHRONIZED = 2 + + status: Status = proto.Field( + proto.ENUM, + number=1, + enum=Status, + ) + type_: Type = proto.Field( + proto.ENUM, + number=6, + enum=Type, + ) + last_transition_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + message: str = proto.Field( + proto.STRING, + number=4, + ) + reason: str = proto.Field( + proto.STRING, + number=5, + ) + + class Aggregate(proto.Message): r"""Represents the aggregation of a set of population of like records by a certain group. For example, a collection of unit diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/deployments_resources.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/deployments_resources.py index aa5a858e0521..abfa76a55a53 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/deployments_resources.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/deployments_resources.py @@ -18,6 +18,7 @@ from typing import MutableMapping, MutableSequence import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore import proto # type: ignore from google.cloud.saasplatform_saasservicemgmt_v1beta1.types import common @@ -41,6 +42,9 @@ "FromMapping", "ToMapping", "Dependency", + "CompositeRef", + "ComponentRef", + "AppParams", }, ) @@ -74,6 +78,29 @@ class Saas(proto.Message): Optional. List of locations that the service is available in. Rollout refers to the list to generate a rollout plan. + application_template (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.CompositeRef): + Reference to composite ApplicationTemplate. + When specified, the template components will be + imported into their equivalent UnitKind, Release + and Blueprint resources. Deleted references will + not delete imported resources. Should only be + specified on source regions, and be unspecified + on replica regions. + blueprint_repo (str): + Output only. Name of repository in Artifact + Registry for system-generated Blueprints, eg. + Blueprints of imported ApplicationTemplates. + state (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.Saas.State): + Output only. State of the Saas. It is always in ACTIVE state + if the application_template is empty. + conditions (MutableSequence[google.cloud.saasplatform_saasservicemgmt_v1beta1.types.SaasCondition]): + Output only. A set of conditions which + indicate the various conditions this resource + can have. + error (google.rpc.status_pb2.Status): + Output only. If the state is FAILED, the + corresponding error code and message. Defaults + to code=OK for all other states. labels (MutableMapping[str, str]): Optional. The labels on the resource, which can be used for categorization. similar to @@ -113,6 +140,38 @@ class Saas(proto.Message): this value. """ + class State(proto.Enum): + r"""State of the Saas. + + Values: + STATE_TYPE_UNSPECIFIED (0): + State type is unspecified. + STATE_ACTIVE (1): + The Saas is ready + STATE_RUNNING (2): + In the process of importing, synchronizing or + replicating ApplicationTemplates + STATE_FAILED (3): + Failure during process of importing, + synchronizing or replicating ApplicationTemplate + processing + ACTIVE (1): + Deprecated: Use STATE_ACTIVE. + RUNNING (2): + Deprecated: Use STATE_RUNNING. + FAILED (3): + Deprecated: Use STATE_FAILED. + """ + + _pb_options = {"allow_alias": True} + STATE_TYPE_UNSPECIFIED = 0 + STATE_ACTIVE = 1 + STATE_RUNNING = 2 + STATE_FAILED = 3 + ACTIVE = 1 + RUNNING = 2 + FAILED = 3 + name: str = proto.Field( proto.STRING, number=1, @@ -122,6 +181,30 @@ class Saas(proto.Message): number=4, message="Location", ) + application_template: "CompositeRef" = proto.Field( + proto.MESSAGE, + number=5, + message="CompositeRef", + ) + blueprint_repo: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + conditions: MutableSequence[common.SaasCondition] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=common.SaasCondition, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=9, + message=status_pb2.Status, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -311,6 +394,12 @@ class UnitKind(proto.Message): the producer wants to manage with App Lifecycle Manager. Part of the App Lifecycle Manager common data model. Immutable once set. + application_template_component (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.ComponentRef): + Output only. Reference to component and + revision in a composite ApplicationTemplate. + app_params (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.AppParams): + AppParams contains the parameters for + creating an AppHub Application. labels (MutableMapping[str, str]): Optional. The labels on the resource, which can be used for categorization. similar to @@ -377,6 +466,16 @@ class UnitKind(proto.Message): proto.STRING, number=8, ) + application_template_component: "ComponentRef" = proto.Field( + proto.MESSAGE, + number=10, + message="ComponentRef", + ) + app_params: "AppParams" = proto.Field( + proto.MESSAGE, + number=11, + message="AppParams", + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -487,6 +586,11 @@ class Unit(proto.Message): Optional. Output only. If set, indicates the time when the system will start removing the unit. + application (str): + Optional. Reference to the AppHub Application + this unit belongs to. All resources deployed in + this Unit will be associated with the specified + Application. labels (MutableMapping[str, str]): Optional. The labels on the resource, which can be used for categorization. similar to @@ -524,6 +628,12 @@ class Unit(proto.Message): made by users must refresh this value. Changes to a resource made by the service should refresh this value. + satisfies_pzs (bool): + Output only. Indicates whether the resource + location satisfies Zone Separation constraints. + This is false by default. + satisfies_pzi (bool): + Output only. Reserved for future use. """ class UnitState(proto.Enum): @@ -702,6 +812,10 @@ class MaintenanceSettings(proto.Message): number=26, message=timestamp_pb2.Timestamp, ) + application: str = proto.Field( + proto.STRING, + number=29, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -730,6 +844,14 @@ class MaintenanceSettings(proto.Message): number=10304, message=timestamp_pb2.Timestamp, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=10305, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=10306, + ) class UnitDependency(proto.Message): @@ -765,7 +887,7 @@ class UnitOperation(proto.Message): unit to focus only on the change they have requested. This is a base object that contains the common fields in all - unit operations. Next: 19 + unit operations. Next: 22 This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -866,6 +988,10 @@ class UnitOperation(proto.Message): made by users must refresh this value. Changes to a resource made by the service should refresh this value. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was marked for deletion (deletion is an + asynchronous operation). """ class UnitOperationState(proto.Enum): @@ -988,6 +1114,11 @@ class UnitOperationState(proto.Enum): number=10304, message=timestamp_pb2.Timestamp, ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10305, + message=timestamp_pb2.Timestamp, + ) class Provision(proto.Message): @@ -1100,6 +1231,9 @@ class Release(proto.Message): input_variable_defaults (MutableSequence[google.cloud.saasplatform_saasservicemgmt_v1beta1.types.UnitVariable]): Optional. Mapping of input variables to default values. Maximum 100 + application_template_component (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.ComponentRef): + Output only. Reference to component and + revision in a composite ApplicationTemplate. labels (MutableMapping[str, str]): Optional. The labels on the resource, which can be used for categorization. similar to @@ -1190,6 +1324,11 @@ class ReleaseRequirements(proto.Message): number=7, message=common.UnitVariable, ) + application_template_component: "ComponentRef" = proto.Field( + proto.MESSAGE, + number=9, + message="ComponentRef", + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -1340,4 +1479,134 @@ class Dependency(proto.Message): ) +class CompositeRef(proto.Message): + r"""CompositeRef represents a reference to a composite resource. + Next ID: 4 + + Attributes: + application_template (str): + Required. Reference to the + ApplicationTemplate resource. + revision (str): + Revision of the ApplicationTemplate to use. + Changes to revision will trigger manual + resynchronization. If empty, ApplicationTemplate + will be ignored. + sync_operation (str): + Output only. Reference to on-going AppTemplate import and + replication operation (i.e. the operation_id for the + long-running operation). This field is opaque for external + usage. + """ + + application_template: str = proto.Field( + proto.STRING, + number=1, + ) + revision: str = proto.Field( + proto.STRING, + number=2, + ) + sync_operation: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ComponentRef(proto.Message): + r"""ComponentRef represents a reference to a component resource. + Next ID: 4 + + Attributes: + composite_ref (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.CompositeRef): + Reference to the Composite + ApplicationTemplate. + component (str): + Name of the component in composite.Components + revision (str): + Revision of the component. + If the component does not have a revision, this + field will be explicitly set to the revision of + the composite ApplicationTemplate. + """ + + composite_ref: "CompositeRef" = proto.Field( + proto.MESSAGE, + number=1, + message="CompositeRef", + ) + component: str = proto.Field( + proto.STRING, + number=2, + ) + revision: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AppParams(proto.Message): + r"""AppParams contains the parameters for creating an AppHub + Application. + + Attributes: + group (str): + Grouping used to construct the name of the AppHub + Application. Multiple UnitKinds can specify the same group + to use the same Application across their respective units. + Corresponds to the app_boundary_id in the ADC composite + ApplicationTemplate. Defaults to UnitKind.name + scope (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.AppParams.Scope): + Corresponds to the scope in the ADC composite + ApplicationTemplate. Defaults to TYPE_REGIONAL. + """ + + class Scope(proto.Message): + r"""Scope of an application. + + Attributes: + type_ (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.AppParams.Scope.Type): + Required. Scope Type. + """ + + class Type(proto.Enum): + r"""Scope Type. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified type. + TYPE_REGIONAL (1): + Regional type. + TYPE_GLOBAL (2): + Global type. + REGIONAL (1): + Deprecated: Use TYPE_REGIONAL. + GLOBAL (2): + Deprecated: Use TYPE_GLOBAL. + """ + + _pb_options = {"allow_alias": True} + TYPE_UNSPECIFIED = 0 + TYPE_REGIONAL = 1 + TYPE_GLOBAL = 2 + REGIONAL = 1 + GLOBAL = 2 + + type_: "AppParams.Scope.Type" = proto.Field( + proto.ENUM, + number=1, + enum="AppParams.Scope.Type", + ) + + group: str = proto.Field( + proto.STRING, + number=1, + ) + scope: Scope = proto.Field( + proto.MESSAGE, + number=2, + message=Scope, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/rollouts_resources.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/rollouts_resources.py index b8967a150bba..4fdb7381cf81 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/rollouts_resources.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/rollouts_resources.py @@ -114,8 +114,8 @@ class Rollout(proto.Message): Optional. The strategy used for executing this Rollout. This strategy will override whatever strategy is specified in the - RolloutType. If not specified on creation, the - strategy from RolloutType will be used. + RolloutKind. If not specified on creation, the + strategy from RolloutKind will be used. There are two supported values strategies which are used to control @@ -130,9 +130,9 @@ class Rollout(proto.Message): filter string against Unit. The filter will be applied to determine the eligible unit population. This filter can only reduce, but not expand the scope of the rollout. If not - provided, the unit_filter from the RolloutType will be used. + provided, the unit_filter from the RolloutKind will be used. rollout_kind (str): - Optional. Immutable. Name of the RolloutKind + Required. Immutable. Name of the RolloutKind this rollout is stemming from and adhering to. stats (google.cloud.saasplatform_saasservicemgmt_v1beta1.types.RolloutStats): Optional. Output only. Details about the @@ -144,6 +144,15 @@ class Rollout(proto.Message): through all natural Rollout States (such as RUNNING -> SUCCEEDED or RUNNING -> FAILED). Requests can only be made when the Rollout is in a non-terminal state. + effective_unit_filter (str): + Optional. Output only. Output only snapshot of the effective + unit filter at Rollout start time. Contains a + CEL(https://github.com/google/cel-spec) expression + consisting of a conjunction of Rollout.unit_filter and + RolloutKind.unit_filter. This field captures the filter + applied by the Rollout to determine the Unit population. If + the associated RolloutKind's unit_filter is modified after + the rollout is started, it will not be updated here. labels (MutableMapping[str, str]): Optional. The labels on the resource, which can be used for categorization. similar to @@ -181,6 +190,10 @@ class Rollout(proto.Message): made by users must refresh this value. Changes to a resource made by the service should refresh this value. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was marked for deletion (deletion is an + asynchronous operation). """ class RolloutState(proto.Enum): @@ -283,6 +296,10 @@ class RolloutState(proto.Enum): number=25, message="RolloutControl", ) + effective_unit_filter: str = proto.Field( + proto.STRING, + number=26, + ) labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -311,6 +328,11 @@ class RolloutState(proto.Enum): number=10304, message=timestamp_pb2.Timestamp, ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10305, + message=timestamp_pb2.Timestamp, + ) class RolloutKind(proto.Message): @@ -483,23 +505,32 @@ class ErrorBudget(proto.Message): exceeds max(allowed_count, allowed_ratio \* total_units), the rollout will be paused. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: allowed_count (int): Optional. The maximum number of failed units allowed in a location without pausing the rollout. + + This field is a member of `oneof`_ ``_allowed_count``. allowed_percentage (int): Optional. The maximum percentage of units allowed to fail (0, 100] within a location without pausing the rollout. + + This field is a member of `oneof`_ ``_allowed_percentage``. """ allowed_count: int = proto.Field( proto.INT32, number=1, + optional=True, ) allowed_percentage: int = proto.Field( proto.INT32, number=2, + optional=True, ) @@ -507,13 +538,17 @@ class RolloutStats(proto.Message): r"""RolloutStats contains information about the progress of a rollout. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: operations_by_state (MutableSequence[google.cloud.saasplatform_saasservicemgmt_v1beta1.types.Aggregate]): - Output only. A breakdown of the progress of - operations triggered by the rollout. Provides a - count of Operations by their state. This can be - used to determine the number of units which have - been updated, or are scheduled to be updated. + Optional. Output only. Unordered list. A + breakdown of the progress of operations + triggered by the rollout. Provides a count of + Operations by their state. This can be used to + determine the number of units which have been + updated, or are scheduled to be updated. There will be at most one entry per group. Possible values for operation groups are: @@ -524,6 +559,12 @@ class RolloutStats(proto.Message): - "SUCCEEDED" - "FAILED" - "CANCELLED". + estimated_total_unit_count (int): + Optional. Output only. Estimated number of + units based. The estimation is computed upon + creation of the rollout. + + This field is a member of `oneof`_ ``_estimated_total_unit_count``. """ operations_by_state: MutableSequence[common.Aggregate] = proto.RepeatedField( @@ -531,6 +572,11 @@ class RolloutStats(proto.Message): number=2, message=common.Aggregate, ) + estimated_total_unit_count: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) class RolloutControl(proto.Message): diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_async.py b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_async.py index 37f02914d3ac..d6cc4d87a668 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_async.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_async.py @@ -39,9 +39,13 @@ async def sample_create_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsAsyncClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.CreateRolloutRequest( parent="parent_value", rollout_id="rollout_id_value", + rollout=rollout, ) # Make the request diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_sync.py b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_sync.py index 5dd97347f153..57a98c35bd71 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_sync.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_create_rollout_sync.py @@ -39,9 +39,13 @@ def sample_create_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsClient() # Initialize request argument(s) + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + request = saasplatform_saasservicemgmt_v1beta1.CreateRolloutRequest( parent="parent_value", rollout_id="rollout_id_value", + rollout=rollout, ) # Make the request diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_async.py b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_async.py index 2808a126f858..f4df73eeb5fd 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_async.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_async.py @@ -39,7 +39,12 @@ async def sample_update_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsAsyncClient() # Initialize request argument(s) - request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest() + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + + request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest( + rollout=rollout, + ) # Make the request response = await client.update_rollout(request=request) diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_sync.py b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_sync.py index 49e7a677f350..71d6d53fe5bc 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_sync.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/saasservicemgmt_v1beta1_generated_saas_rollouts_update_rollout_sync.py @@ -39,7 +39,12 @@ def sample_update_rollout(): client = saasplatform_saasservicemgmt_v1beta1.SaasRolloutsClient() # Initialize request argument(s) - request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest() + rollout = saasplatform_saasservicemgmt_v1beta1.Rollout() + rollout.rollout_kind = "rollout_kind_value" + + request = saasplatform_saasservicemgmt_v1beta1.UpdateRolloutRequest( + rollout=rollout, + ) # Make the request response = client.update_rollout(request=request) diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/snippet_metadata_google.cloud.saasplatform.saasservicemgmt.v1beta1.json b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/snippet_metadata_google.cloud.saasplatform.saasservicemgmt.v1beta1.json index a0a032fa7c10..571c7a688f14 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/snippet_metadata_google.cloud.saasplatform.saasservicemgmt.v1beta1.json +++ b/packages/google-cloud-saasplatform-saasservicemgmt/samples/generated_samples/snippet_metadata_google.cloud.saasplatform.saasservicemgmt.v1beta1.json @@ -5183,12 +5183,12 @@ "regionTag": "saasservicemgmt_v1beta1_generated_SaasRollouts_CreateRollout_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -5198,18 +5198,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], @@ -5271,12 +5271,12 @@ "regionTag": "saasservicemgmt_v1beta1_generated_SaasRollouts_CreateRollout_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -5286,18 +5286,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], @@ -6479,12 +6479,12 @@ "regionTag": "saasservicemgmt_v1beta1_generated_SaasRollouts_UpdateRollout_async", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -6494,18 +6494,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -6563,12 +6563,12 @@ "regionTag": "saasservicemgmt_v1beta1_generated_SaasRollouts_UpdateRollout_sync", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -6578,18 +6578,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_deployments.py b/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_deployments.py index bd8905d1d35d..7b6e55ca9b68 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_deployments.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_deployments.py @@ -39,8 +39,10 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.any_pb2 as any_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore from google.api_core import ( client_options, gapic_v1, @@ -1899,6 +1901,8 @@ def test_get_saas(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -1913,6 +1917,8 @@ def test_get_saas(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2045,6 +2051,8 @@ async def test_get_saas_async(request_type, transport: str = "grpc_asyncio"): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -2060,6 +2068,8 @@ async def test_get_saas_async(request_type, transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2229,6 +2239,8 @@ def test_create_saas(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -2243,6 +2255,8 @@ def test_create_saas(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2381,6 +2395,8 @@ async def test_create_saas_async(request_type, transport: str = "grpc_asyncio"): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -2396,6 +2412,8 @@ async def test_create_saas_async(request_type, transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2585,6 +2603,8 @@ def test_update_saas(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -2599,6 +2619,8 @@ def test_update_saas(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2733,6 +2755,8 @@ async def test_update_saas_async(request_type, transport: str = "grpc_asyncio"): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -2748,6 +2772,8 @@ async def test_update_saas_async(request_type, transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -7566,8 +7592,11 @@ def test_get_unit(request_type, transport: str = "grpc"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) response = client.get_unit(request) @@ -7598,8 +7627,11 @@ def test_get_unit(request_type, transport: str = "grpc"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_get_unit_non_empty_request_with_auto_populated_field(): @@ -7739,8 +7771,11 @@ async def test_get_unit_async(request_type, transport: str = "grpc_asyncio"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) response = await client.get_unit(request) @@ -7772,8 +7807,11 @@ async def test_get_unit_async(request_type, transport: str = "grpc_asyncio"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_get_unit_field_headers(): @@ -7950,8 +7988,11 @@ def test_create_unit(request_type, transport: str = "grpc"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) response = client.create_unit(request) @@ -7982,8 +8023,11 @@ def test_create_unit(request_type, transport: str = "grpc"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_create_unit_non_empty_request_with_auto_populated_field(): @@ -8129,8 +8173,11 @@ async def test_create_unit_async(request_type, transport: str = "grpc_asyncio"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) response = await client.create_unit(request) @@ -8162,8 +8209,11 @@ async def test_create_unit_async(request_type, transport: str = "grpc_asyncio"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_create_unit_field_headers(): @@ -8360,8 +8410,11 @@ def test_update_unit(request_type, transport: str = "grpc"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) response = client.update_unit(request) @@ -8392,8 +8445,11 @@ def test_update_unit(request_type, transport: str = "grpc"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_update_unit_non_empty_request_with_auto_populated_field(): @@ -8535,8 +8591,11 @@ async def test_update_unit_async(request_type, transport: str = "grpc_asyncio"): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) response = await client.update_unit(request) @@ -8568,8 +8627,11 @@ async def test_update_unit_async(request_type, transport: str = "grpc_asyncio"): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True def test_update_unit_field_headers(): @@ -20093,6 +20155,8 @@ async def test_get_saas_empty_call_grpc_asyncio(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -20121,6 +20185,8 @@ async def test_create_saas_empty_call_grpc_asyncio(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -20149,6 +20215,8 @@ async def test_update_saas_empty_call_grpc_asyncio(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -20513,8 +20581,11 @@ async def test_get_unit_empty_call_grpc_asyncio(): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) await client.get_unit(request=None) @@ -20550,8 +20621,11 @@ async def test_create_unit_empty_call_grpc_asyncio(): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) await client.create_unit(request=None) @@ -20587,8 +20661,11 @@ async def test_update_unit_empty_call_grpc_asyncio(): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) ) await client.update_unit(request=None) @@ -21109,6 +21186,8 @@ def test_get_saas_rest_call_success(request_type): # Designate an appropriate value for the returned response. return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -21128,6 +21207,8 @@ def test_get_saas_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -21239,11 +21320,37 @@ def test_create_saas_rest_call_success(request_type): request_init["saas"] = { "name": "name_value", "locations": [{"name": "name_value"}], + "application_template": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "blueprint_repo": "blueprint_repo_value", + "state": 1, + "conditions": [ + { + "status": 1, + "type_": 1, + "last_transition_time": {"seconds": 751, "nanos": 543}, + "message": "message_value", + "reason": "reason_value", + } + ], + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", - "create_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, "update_time": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -21320,6 +21427,8 @@ def get_message_fields(field): # Designate an appropriate value for the returned response. return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -21339,6 +21448,8 @@ def get_message_fields(field): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -21450,11 +21561,37 @@ def test_update_saas_rest_call_success(request_type): request_init["saas"] = { "name": "projects/sample1/locations/sample2/saas/sample3", "locations": [{"name": "name_value"}], + "application_template": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "blueprint_repo": "blueprint_repo_value", + "state": 1, + "conditions": [ + { + "status": 1, + "type_": 1, + "last_transition_time": {"seconds": 751, "nanos": 543}, + "message": "message_value", + "reason": "reason_value", + } + ], + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", - "create_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, "update_time": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -21531,6 +21668,8 @@ def get_message_fields(field): # Designate an appropriate value for the returned response. return_value = deployments_resources.Saas( name="name_value", + blueprint_repo="blueprint_repo_value", + state=deployments_resources.Saas.State.STATE_ACTIVE, uid="uid_value", etag="etag_value", ) @@ -21550,6 +21689,8 @@ def get_message_fields(field): # Establish that the response is the type that we expect. assert isinstance(response, deployments_resources.Saas) assert response.name == "name_value" + assert response.blueprint_repo == "blueprint_repo_value" + assert response.state == deployments_resources.Saas.State.STATE_ACTIVE assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -22894,6 +23035,16 @@ def test_create_unit_kind_rest_call_success(request_type): ], "output_variable_mappings": {}, "saas": "saas_value", + "application_template_component": { + "composite_ref": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "component": "component_value", + "revision": "revision_value", + }, + "app_params": {"group": "group_value", "scope": {"type_": 1}}, "labels": {}, "annotations": {}, "uid": "uid_value", @@ -23133,6 +23284,16 @@ def test_update_unit_kind_rest_call_success(request_type): ], "output_variable_mappings": {}, "saas": "saas_value", + "application_template_component": { + "composite_ref": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "component": "component_value", + "revision": "revision_value", + }, + "app_params": {"group": "group_value", "scope": {"type_": 1}}, "labels": {}, "annotations": {}, "uid": "uid_value", @@ -23607,8 +23768,11 @@ def test_get_unit_rest_call_success(request_type): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) # Wrap the value into a proper Response obj @@ -23644,8 +23808,11 @@ def test_get_unit_rest_call_success(request_type): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -23789,12 +23956,15 @@ def test_create_unit_rest_call_success(request_type): "management_mode": 1, "system_managed_state": 1, "system_cleanup_at": {}, + "application": "application_value", "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", "create_time": {}, "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 @@ -23879,8 +24049,11 @@ def get_message_fields(field): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) # Wrap the value into a proper Response obj @@ -23916,8 +24089,11 @@ def get_message_fields(field): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -24065,12 +24241,15 @@ def test_update_unit_rest_call_success(request_type): "management_mode": 1, "system_managed_state": 1, "system_cleanup_at": {}, + "application": "application_value", "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", "create_time": {}, "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 @@ -24155,8 +24334,11 @@ def get_message_fields(field): state=deployments_resources.Unit.UnitState.UNIT_STATE_NOT_PROVISIONED, management_mode=deployments_resources.Unit.ManagementMode.MANAGEMENT_MODE_USER, system_managed_state=deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE, + application="application_value", uid="uid_value", etag="etag_value", + satisfies_pzs=True, + satisfies_pzi=True, ) # Wrap the value into a proper Response obj @@ -24192,8 +24374,11 @@ def get_message_fields(field): response.system_managed_state == deployments_resources.Unit.SystemManagedState.SYSTEM_MANAGED_STATE_ACTIVE ) + assert response.application == "application_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -24738,6 +24923,7 @@ def test_create_unit_operation_rest_call_success(request_type): "etag": "etag_value", "create_time": {}, "update_time": {}, + "delete_time": {}, } # 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 @@ -25006,6 +25192,7 @@ def test_update_unit_operation_rest_call_success(request_type): "etag": "etag_value", "create_time": {}, "update_time": {}, + "delete_time": {}, } # 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 @@ -25638,6 +25825,15 @@ def test_create_release_rest_call_success(request_type): ], "output_variables": {}, "input_variable_defaults": {}, + "application_template_component": { + "composite_ref": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "component": "component_value", + "revision": "revision_value", + }, "labels": {}, "annotations": {}, "uid": "uid_value", @@ -25874,6 +26070,15 @@ def test_update_release_rest_call_success(request_type): ], "output_variables": {}, "input_variable_defaults": {}, + "application_template_component": { + "composite_ref": { + "application_template": "application_template_value", + "revision": "revision_value", + "sync_operation": "sync_operation_value", + }, + "component": "component_value", + "revision": "revision_value", + }, "labels": {}, "annotations": {}, "uid": "uid_value", @@ -27415,6 +27620,99 @@ def test_saas_deployments_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel +def test_application_path(): + project = "squid" + location = "clam" + application = "whelk" + expected = ( + "projects/{project}/locations/{location}/applications/{application}".format( + project=project, + location=location, + application=application, + ) + ) + actual = SaasDeploymentsClient.application_path(project, location, application) + assert expected == actual + + +def test_parse_application_path(): + expected = { + "project": "octopus", + "location": "oyster", + "application": "nudibranch", + } + path = SaasDeploymentsClient.application_path(**expected) + + # Check that the path construction is reversible. + actual = SaasDeploymentsClient.parse_application_path(path) + assert expected == actual + + +def test_application_template_path(): + project = "cuttlefish" + location = "mussel" + space = "winkle" + applicationTemplate = "nautilus" + expected = "projects/{project}/locations/{location}/spaces/{space}/applicationTemplates/{applicationTemplate}".format( + project=project, + location=location, + space=space, + applicationTemplate=applicationTemplate, + ) + actual = SaasDeploymentsClient.application_template_path( + project, location, space, applicationTemplate + ) + assert expected == actual + + +def test_parse_application_template_path(): + expected = { + "project": "scallop", + "location": "abalone", + "space": "squid", + "applicationTemplate": "clam", + } + path = SaasDeploymentsClient.application_template_path(**expected) + + # Check that the path construction is reversible. + actual = SaasDeploymentsClient.parse_application_template_path(path) + assert expected == actual + + +def test_application_template_revision_path(): + project = "whelk" + location = "octopus" + space = "oyster" + application_template = "nudibranch" + revision = "cuttlefish" + expected = "projects/{project}/locations/{location}/spaces/{space}/applicationTemplates/{application_template}/revisions/{revision}".format( + project=project, + location=location, + space=space, + application_template=application_template, + revision=revision, + ) + actual = SaasDeploymentsClient.application_template_revision_path( + project, location, space, application_template, revision + ) + assert expected == actual + + +def test_parse_application_template_revision_path(): + expected = { + "project": "mussel", + "location": "winkle", + "space": "nautilus", + "application_template": "scallop", + "revision": "abalone", + } + path = SaasDeploymentsClient.application_template_revision_path(**expected) + + # Check that the path construction is reversible. + actual = SaasDeploymentsClient.parse_application_template_revision_path(path) + assert expected == actual + + def test_release_path(): project = "squid" location = "clam" diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_rollouts.py b/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_rollouts.py index 8f3200132cf1..48362edd438c 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_rollouts.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/tests/unit/gapic/saasplatform_saasservicemgmt_v1beta1/test_saas_rollouts.py @@ -1862,6 +1862,7 @@ def test_get_rollout(request_type, transport: str = "grpc"): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -1889,6 +1890,7 @@ def test_get_rollout(request_type, transport: str = "grpc"): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2031,6 +2033,7 @@ async def test_get_rollout_async(request_type, transport: str = "grpc_asyncio"): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -2059,6 +2062,7 @@ async def test_get_rollout_async(request_type, transport: str = "grpc_asyncio"): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2236,6 +2240,7 @@ def test_create_rollout(request_type, transport: str = "grpc"): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -2263,6 +2268,7 @@ def test_create_rollout(request_type, transport: str = "grpc"): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2409,6 +2415,7 @@ async def test_create_rollout_async(request_type, transport: str = "grpc_asyncio rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -2437,6 +2444,7 @@ async def test_create_rollout_async(request_type, transport: str = "grpc_asyncio ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2634,6 +2642,7 @@ def test_update_rollout(request_type, transport: str = "grpc"): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -2661,6 +2670,7 @@ def test_update_rollout(request_type, transport: str = "grpc"): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -2803,6 +2813,7 @@ async def test_update_rollout_async(request_type, transport: str = "grpc_asyncio rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -2831,6 +2842,7 @@ async def test_update_rollout_async(request_type, transport: str = "grpc_asyncio ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -7826,6 +7838,7 @@ async def test_get_rollout_empty_call_grpc_asyncio(): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -7862,6 +7875,7 @@ async def test_create_rollout_empty_call_grpc_asyncio(): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -7898,6 +7912,7 @@ async def test_update_rollout_empty_call_grpc_asyncio(): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -8283,6 +8298,7 @@ def test_get_rollout_rest_call_success(request_type): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -8315,6 +8331,7 @@ def test_get_rollout_rest_call_success(request_type): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -8436,14 +8453,19 @@ def test_create_rollout_rest_call_success(request_type): "rollout_orchestration_strategy": "rollout_orchestration_strategy_value", "unit_filter": "unit_filter_value", "rollout_kind": "rollout_kind_value", - "stats": {"operations_by_state": [{"group": "group_value", "count": 553}]}, + "stats": { + "operations_by_state": [{"group": "group_value", "count": 553}], + "estimated_total_unit_count": 2794, + }, "control": {"run_params": {"retry_failed_operations": True}, "action": 1}, + "effective_unit_filter": "effective_unit_filter_value", "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", "create_time": {}, "update_time": {}, + "delete_time": {}, } # 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 @@ -8527,6 +8549,7 @@ def get_message_fields(field): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -8559,6 +8582,7 @@ def get_message_fields(field): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" @@ -8684,14 +8708,19 @@ def test_update_rollout_rest_call_success(request_type): "rollout_orchestration_strategy": "rollout_orchestration_strategy_value", "unit_filter": "unit_filter_value", "rollout_kind": "rollout_kind_value", - "stats": {"operations_by_state": [{"group": "group_value", "count": 553}]}, + "stats": { + "operations_by_state": [{"group": "group_value", "count": 553}], + "estimated_total_unit_count": 2794, + }, "control": {"run_params": {"retry_failed_operations": True}, "action": 1}, + "effective_unit_filter": "effective_unit_filter_value", "labels": {}, "annotations": {}, "uid": "uid_value", "etag": "etag_value", "create_time": {}, "update_time": {}, + "delete_time": {}, } # 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 @@ -8775,6 +8804,7 @@ def get_message_fields(field): rollout_orchestration_strategy="rollout_orchestration_strategy_value", unit_filter="unit_filter_value", rollout_kind="rollout_kind_value", + effective_unit_filter="effective_unit_filter_value", uid="uid_value", etag="etag_value", ) @@ -8807,6 +8837,7 @@ def get_message_fields(field): ) assert response.unit_filter == "unit_filter_value" assert response.rollout_kind == "rollout_kind_value" + assert response.effective_unit_filter == "effective_unit_filter_value" assert response.uid == "uid_value" assert response.etag == "etag_value" diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control/__init__.py b/packages/google-cloud-storage-control/google/cloud/storage_control/__init__.py index 70713e28e575..8d10e5e92d93 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control/__init__.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control/__init__.py @@ -36,19 +36,31 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + FindingCategory, + FindingSeverity, + FindingSummary, + FindingType, Folder, GetAnywhereCacheRequest, GetFolderIntelligenceConfigRequest, GetFolderRequest, + GetIntelligenceFindingRequest, + GetIntelligenceFindingRevisionRequest, GetManagedFolderRequest, GetOrganizationIntelligenceConfigRequest, GetProjectIntelligenceConfigRequest, GetStorageLayoutRequest, IntelligenceConfig, + IntelligenceFinding, + IntelligenceFindingRevision, ListAnywhereCachesRequest, ListAnywhereCachesResponse, ListFoldersRequest, ListFoldersResponse, + ListIntelligenceFindingRevisionsRequest, + ListIntelligenceFindingRevisionsResponse, + ListIntelligenceFindingsRequest, + ListIntelligenceFindingsResponse, ListManagedFoldersRequest, ListManagedFoldersResponse, ManagedFolder, @@ -58,6 +70,8 @@ RenameFolderRequest, ResumeAnywhereCacheRequest, StorageLayout, + SummarizeIntelligenceFindingsRequest, + SummarizeIntelligenceFindingsResponse, UpdateAnywhereCacheMetadata, UpdateAnywhereCacheRequest, UpdateFolderIntelligenceConfigRequest, @@ -79,19 +93,28 @@ "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "FindingSummary", "Folder", "GetAnywhereCacheRequest", "GetFolderIntelligenceConfigRequest", "GetFolderRequest", + "GetIntelligenceFindingRequest", + "GetIntelligenceFindingRevisionRequest", "GetManagedFolderRequest", "GetOrganizationIntelligenceConfigRequest", "GetProjectIntelligenceConfigRequest", "GetStorageLayoutRequest", "IntelligenceConfig", + "IntelligenceFinding", + "IntelligenceFindingRevision", "ListAnywhereCachesRequest", "ListAnywhereCachesResponse", "ListFoldersRequest", "ListFoldersResponse", + "ListIntelligenceFindingRevisionsRequest", + "ListIntelligenceFindingRevisionsResponse", + "ListIntelligenceFindingsRequest", + "ListIntelligenceFindingsResponse", "ListManagedFoldersRequest", "ListManagedFoldersResponse", "ManagedFolder", @@ -101,9 +124,14 @@ "RenameFolderRequest", "ResumeAnywhereCacheRequest", "StorageLayout", + "SummarizeIntelligenceFindingsRequest", + "SummarizeIntelligenceFindingsResponse", "UpdateAnywhereCacheMetadata", "UpdateAnywhereCacheRequest", "UpdateFolderIntelligenceConfigRequest", "UpdateOrganizationIntelligenceConfigRequest", "UpdateProjectIntelligenceConfigRequest", + "FindingCategory", + "FindingSeverity", + "FindingType", ) diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/__init__.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/__init__.py index 28fda7db746e..3b297eafced5 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/__init__.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/__init__.py @@ -36,19 +36,31 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + FindingCategory, + FindingSeverity, + FindingSummary, + FindingType, Folder, GetAnywhereCacheRequest, GetFolderIntelligenceConfigRequest, GetFolderRequest, + GetIntelligenceFindingRequest, + GetIntelligenceFindingRevisionRequest, GetManagedFolderRequest, GetOrganizationIntelligenceConfigRequest, GetProjectIntelligenceConfigRequest, GetStorageLayoutRequest, IntelligenceConfig, + IntelligenceFinding, + IntelligenceFindingRevision, ListAnywhereCachesRequest, ListAnywhereCachesResponse, ListFoldersRequest, ListFoldersResponse, + ListIntelligenceFindingRevisionsRequest, + ListIntelligenceFindingRevisionsResponse, + ListIntelligenceFindingsRequest, + ListIntelligenceFindingsResponse, ListManagedFoldersRequest, ListManagedFoldersResponse, ManagedFolder, @@ -58,6 +70,8 @@ RenameFolderRequest, ResumeAnywhereCacheRequest, StorageLayout, + SummarizeIntelligenceFindingsRequest, + SummarizeIntelligenceFindingsResponse, UpdateAnywhereCacheMetadata, UpdateAnywhereCacheRequest, UpdateFolderIntelligenceConfigRequest, @@ -161,19 +175,31 @@ def _get_version(dependency_name): "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "FindingCategory", + "FindingSeverity", + "FindingSummary", + "FindingType", "Folder", "GetAnywhereCacheRequest", "GetFolderIntelligenceConfigRequest", "GetFolderRequest", + "GetIntelligenceFindingRequest", + "GetIntelligenceFindingRevisionRequest", "GetManagedFolderRequest", "GetOrganizationIntelligenceConfigRequest", "GetProjectIntelligenceConfigRequest", "GetStorageLayoutRequest", "IntelligenceConfig", + "IntelligenceFinding", + "IntelligenceFindingRevision", "ListAnywhereCachesRequest", "ListAnywhereCachesResponse", "ListFoldersRequest", "ListFoldersResponse", + "ListIntelligenceFindingRevisionsRequest", + "ListIntelligenceFindingRevisionsResponse", + "ListIntelligenceFindingsRequest", + "ListIntelligenceFindingsResponse", "ListManagedFoldersRequest", "ListManagedFoldersResponse", "ManagedFolder", @@ -184,6 +210,8 @@ def _get_version(dependency_name): "ResumeAnywhereCacheRequest", "StorageControlClient", "StorageLayout", + "SummarizeIntelligenceFindingsRequest", + "SummarizeIntelligenceFindingsResponse", "UpdateAnywhereCacheMetadata", "UpdateAnywhereCacheRequest", "UpdateFolderIntelligenceConfigRequest", diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/gapic_metadata.json b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/gapic_metadata.json index 765d658a2b1a..7ad901c4da76 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/gapic_metadata.json +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/gapic_metadata.json @@ -65,6 +65,16 @@ "get_iam_policy" ] }, + "GetIntelligenceFinding": { + "methods": [ + "get_intelligence_finding" + ] + }, + "GetIntelligenceFindingRevision": { + "methods": [ + "get_intelligence_finding_revision" + ] + }, "GetManagedFolder": { "methods": [ "get_managed_folder" @@ -95,6 +105,16 @@ "list_folders" ] }, + "ListIntelligenceFindingRevisions": { + "methods": [ + "list_intelligence_finding_revisions" + ] + }, + "ListIntelligenceFindings": { + "methods": [ + "list_intelligence_findings" + ] + }, "ListManagedFolders": { "methods": [ "list_managed_folders" @@ -120,6 +140,11 @@ "set_iam_policy" ] }, + "SummarizeIntelligenceFindings": { + "methods": [ + "summarize_intelligence_findings" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" @@ -205,6 +230,16 @@ "get_iam_policy" ] }, + "GetIntelligenceFinding": { + "methods": [ + "get_intelligence_finding" + ] + }, + "GetIntelligenceFindingRevision": { + "methods": [ + "get_intelligence_finding_revision" + ] + }, "GetManagedFolder": { "methods": [ "get_managed_folder" @@ -235,6 +270,16 @@ "list_folders" ] }, + "ListIntelligenceFindingRevisions": { + "methods": [ + "list_intelligence_finding_revisions" + ] + }, + "ListIntelligenceFindings": { + "methods": [ + "list_intelligence_findings" + ] + }, "ListManagedFolders": { "methods": [ "list_managed_folders" @@ -260,6 +305,11 @@ "set_iam_policy" ] }, + "SummarizeIntelligenceFindings": { + "methods": [ + "summarize_intelligence_findings" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" @@ -345,6 +395,16 @@ "get_iam_policy" ] }, + "GetIntelligenceFinding": { + "methods": [ + "get_intelligence_finding" + ] + }, + "GetIntelligenceFindingRevision": { + "methods": [ + "get_intelligence_finding_revision" + ] + }, "GetManagedFolder": { "methods": [ "get_managed_folder" @@ -375,6 +435,16 @@ "list_folders" ] }, + "ListIntelligenceFindingRevisions": { + "methods": [ + "list_intelligence_finding_revisions" + ] + }, + "ListIntelligenceFindings": { + "methods": [ + "list_intelligence_findings" + ] + }, "ListManagedFolders": { "methods": [ "list_managed_folders" @@ -400,6 +470,11 @@ "set_iam_policy" ] }, + "SummarizeIntelligenceFindings": { + "methods": [ + "summarize_intelligence_findings" + ] + }, "TestIamPermissions": { "methods": [ "test_iam_permissions" diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/async_client.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/async_client.py index e3d6317b111e..3072ebf016ac 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/async_client.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/async_client.py @@ -53,6 +53,7 @@ import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.cloud.storage_control_v2.services.storage_control import pagers @@ -90,6 +91,8 @@ class StorageControlAsyncClient: parse_anywhere_cache_path = staticmethod( StorageControlClient.parse_anywhere_cache_path ) + bucket_path = staticmethod(StorageControlClient.bucket_path) + parse_bucket_path = staticmethod(StorageControlClient.parse_bucket_path) folder_path = staticmethod(StorageControlClient.folder_path) parse_folder_path = staticmethod(StorageControlClient.parse_folder_path) intelligence_config_path = staticmethod( @@ -98,6 +101,18 @@ class StorageControlAsyncClient: parse_intelligence_config_path = staticmethod( StorageControlClient.parse_intelligence_config_path ) + intelligence_finding_path = staticmethod( + StorageControlClient.intelligence_finding_path + ) + parse_intelligence_finding_path = staticmethod( + StorageControlClient.parse_intelligence_finding_path + ) + intelligence_finding_revision_path = staticmethod( + StorageControlClient.intelligence_finding_revision_path + ) + parse_intelligence_finding_revision_path = staticmethod( + StorageControlClient.parse_intelligence_finding_revision_path + ) managed_folder_path = staticmethod(StorageControlClient.managed_folder_path) parse_managed_folder_path = staticmethod( StorageControlClient.parse_managed_folder_path @@ -3939,6 +3954,647 @@ async def sample_test_iam_permissions(): # Done; return the response. return response + async def get_intelligence_finding( + self, + request: Optional[ + Union[storage_control.GetIntelligenceFindingRequest, 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]]] = (), + ) -> storage_control.IntelligenceFinding: + r"""Gets the ``IntelligenceFinding`` for a project. + + .. 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 storage_control_v2 + + async def sample_get_intelligence_finding(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_intelligence_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetIntelligenceFindingRequest, dict]]): + The request object. Request message to get the ``IntelligenceFinding`` + resource associated with a project. + name (:class:`str`): + Required. The name of the ``IntelligenceFinding`` + resource. + + Format: + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + + 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.storage_control_v2.types.IntelligenceFinding: + The IntelligenceFinding resource that represents a security, performance, + or cost-related finding about a project or bucket. + + """ + # 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, storage_control.GetIntelligenceFindingRequest): + request = storage_control.GetIntelligenceFindingRequest(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_intelligence_finding + ] + + # 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_intelligence_findings( + self, + request: Optional[ + Union[storage_control.ListIntelligenceFindingsRequest, 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.ListIntelligenceFindingsAsyncPager: + r"""Lists the ``IntelligenceFinding`` resources for the specified + project. + + .. 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 storage_control_v2 + + async def sample_list_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ListIntelligenceFindingsRequest, dict]]): + The request object. Request message to list ``IntelligenceFinding`` + resources associated with a project. + parent (:class:`str`): + Required. The parent of the ``IntelligenceFinding`` + resource. + + Format: ``projects/{project}/locations/{location}`` + + 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.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingsAsyncPager: + Response message to list the IntelligenceFinding resources associated with + a project. + + 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, storage_control.ListIntelligenceFindingsRequest): + request = storage_control.ListIntelligenceFindingsRequest(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_intelligence_findings + ] + + # 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.ListIntelligenceFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def summarize_intelligence_findings( + self, + request: Optional[ + Union[storage_control.SummarizeIntelligenceFindingsRequest, 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.SummarizeIntelligenceFindingsAsyncPager: + r"""Summarize the intelligence findings for the specified + scope(org, folder or project). + + .. 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 storage_control_v2 + + async def sample_summarize_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.summarize_intelligence_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsRequest, dict]]): + The request object. Request message to summarize the + intelligence findings for the specified + scope(org, folder or project). + parent (:class:`str`): + Required. The scope to summarize the findings for. + Format: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` + + 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.storage_control_v2.services.storage_control.pagers.SummarizeIntelligenceFindingsAsyncPager: + Response message to summarize the + intelligence findings for a specified + scope(org, folder or project). + + 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, storage_control.SummarizeIntelligenceFindingsRequest + ): + request = storage_control.SummarizeIntelligenceFindingsRequest(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.summarize_intelligence_findings + ] + + # 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.SummarizeIntelligenceFindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_intelligence_finding_revision( + self, + request: Optional[ + Union[storage_control.GetIntelligenceFindingRevisionRequest, 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]]] = (), + ) -> storage_control.IntelligenceFindingRevision: + r"""Gets the ``IntelligenceFindingRevision`` resource. + + .. 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 storage_control_v2 + + async def sample_get_intelligence_finding_revision(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_intelligence_finding_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.GetIntelligenceFindingRevisionRequest, dict]]): + The request object. Request message to get the + ``IntelligenceFindingRevision`` resource associated with + a project. + name (:class:`str`): + Required. The name of the + ``IntelligenceFindingRevision`` resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}`` + + 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.storage_control_v2.types.IntelligenceFindingRevision: + An IntelligenceFindingRevision represents a specific revision of an + IntelligenceFinding resource. + + """ + # 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, storage_control.GetIntelligenceFindingRevisionRequest + ): + request = storage_control.GetIntelligenceFindingRevisionRequest(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_intelligence_finding_revision + ] + + # 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_intelligence_finding_revisions( + self, + request: Optional[ + Union[storage_control.ListIntelligenceFindingRevisionsRequest, 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.ListIntelligenceFindingRevisionsAsyncPager: + r"""Lists all the revisions of an ``IntelligenceFinding`` resource. + + .. 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 storage_control_v2 + + async def sample_list_intelligence_finding_revisions(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_finding_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest, dict]]): + The request object. Request message to list ``IntelligenceFindingRevision`` + resources associated with a project. + parent (:class:`str`): + Required. The parent of the + ``IntelligenceFindingRevision`` resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + + 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.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingRevisionsAsyncPager: + Response message to list IntelligenceFindingRevision resources associated + with a project. + + 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, storage_control.ListIntelligenceFindingRevisionsRequest + ): + request = storage_control.ListIntelligenceFindingRevisionsRequest(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_intelligence_finding_revisions + ] + + # 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.ListIntelligenceFindingRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "StorageControlAsyncClient": return self diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/client.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/client.py index 91f3ea0ea12b..0537dda3284b 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/client.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/client.py @@ -70,6 +70,7 @@ import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.cloud.storage_control_v2.services.storage_control import pagers @@ -261,6 +262,23 @@ def parse_anywhere_cache_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def bucket_path( + project: str, + bucket: str, + ) -> str: + """Returns a fully-qualified bucket string.""" + return "projects/{project}/buckets/{bucket}".format( + project=project, + bucket=bucket, + ) + + @staticmethod + def parse_bucket_path(path: str) -> Dict[str, str]: + """Parses a bucket path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/buckets/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def folder_path( project: str, @@ -303,6 +321,52 @@ def parse_intelligence_config_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def intelligence_finding_path( + project: str, + location: str, + intelligence_finding: str, + ) -> str: + """Returns a fully-qualified intelligence_finding string.""" + return "projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}".format( + project=project, + location=location, + intelligence_finding=intelligence_finding, + ) + + @staticmethod + def parse_intelligence_finding_path(path: str) -> Dict[str, str]: + """Parses a intelligence_finding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/intelligenceFindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def intelligence_finding_revision_path( + project: str, + location: str, + intelligence_finding: str, + revision: str, + ) -> str: + """Returns a fully-qualified intelligence_finding_revision string.""" + return "projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}".format( + project=project, + location=location, + intelligence_finding=intelligence_finding, + revision=revision, + ) + + @staticmethod + def parse_intelligence_finding_revision_path(path: str) -> Dict[str, str]: + """Parses a intelligence_finding_revision path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/intelligenceFindings/(?P.+?)/revisions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def managed_folder_path( project: str, @@ -4411,6 +4475,640 @@ def sample_test_iam_permissions(): # Done; return the response. return response + def get_intelligence_finding( + self, + request: Optional[ + Union[storage_control.GetIntelligenceFindingRequest, 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]]] = (), + ) -> storage_control.IntelligenceFinding: + r"""Gets the ``IntelligenceFinding`` for a project. + + .. 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 storage_control_v2 + + def sample_get_intelligence_finding(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_intelligence_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetIntelligenceFindingRequest, dict]): + The request object. Request message to get the ``IntelligenceFinding`` + resource associated with a project. + name (str): + Required. The name of the ``IntelligenceFinding`` + resource. + + Format: + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + + 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.storage_control_v2.types.IntelligenceFinding: + The IntelligenceFinding resource that represents a security, performance, + or cost-related finding about a project or bucket. + + """ + # 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, storage_control.GetIntelligenceFindingRequest): + request = storage_control.GetIntelligenceFindingRequest(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_intelligence_finding] + + # 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_intelligence_findings( + self, + request: Optional[ + Union[storage_control.ListIntelligenceFindingsRequest, 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.ListIntelligenceFindingsPager: + r"""Lists the ``IntelligenceFinding`` resources for the specified + project. + + .. 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 storage_control_v2 + + def sample_list_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ListIntelligenceFindingsRequest, dict]): + The request object. Request message to list ``IntelligenceFinding`` + resources associated with a project. + parent (str): + Required. The parent of the ``IntelligenceFinding`` + resource. + + Format: ``projects/{project}/locations/{location}`` + + 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.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingsPager: + Response message to list the IntelligenceFinding resources associated with + a project. + + 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, storage_control.ListIntelligenceFindingsRequest): + request = storage_control.ListIntelligenceFindingsRequest(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_intelligence_findings + ] + + # 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.ListIntelligenceFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def summarize_intelligence_findings( + self, + request: Optional[ + Union[storage_control.SummarizeIntelligenceFindingsRequest, 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.SummarizeIntelligenceFindingsPager: + r"""Summarize the intelligence findings for the specified + scope(org, folder or project). + + .. 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 storage_control_v2 + + def sample_summarize_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.summarize_intelligence_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsRequest, dict]): + The request object. Request message to summarize the + intelligence findings for the specified + scope(org, folder or project). + parent (str): + Required. The scope to summarize the findings for. + Format: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` + + 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.storage_control_v2.services.storage_control.pagers.SummarizeIntelligenceFindingsPager: + Response message to summarize the + intelligence findings for a specified + scope(org, folder or project). + + 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, storage_control.SummarizeIntelligenceFindingsRequest + ): + request = storage_control.SummarizeIntelligenceFindingsRequest(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.summarize_intelligence_findings + ] + + # 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.SummarizeIntelligenceFindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_intelligence_finding_revision( + self, + request: Optional[ + Union[storage_control.GetIntelligenceFindingRevisionRequest, 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]]] = (), + ) -> storage_control.IntelligenceFindingRevision: + r"""Gets the ``IntelligenceFindingRevision`` resource. + + .. 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 storage_control_v2 + + def sample_get_intelligence_finding_revision(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_intelligence_finding_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.GetIntelligenceFindingRevisionRequest, dict]): + The request object. Request message to get the + ``IntelligenceFindingRevision`` resource associated with + a project. + name (str): + Required. The name of the + ``IntelligenceFindingRevision`` resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}`` + + 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.storage_control_v2.types.IntelligenceFindingRevision: + An IntelligenceFindingRevision represents a specific revision of an + IntelligenceFinding resource. + + """ + # 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, storage_control.GetIntelligenceFindingRevisionRequest + ): + request = storage_control.GetIntelligenceFindingRevisionRequest(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_intelligence_finding_revision + ] + + # 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_intelligence_finding_revisions( + self, + request: Optional[ + Union[storage_control.ListIntelligenceFindingRevisionsRequest, 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.ListIntelligenceFindingRevisionsPager: + r"""Lists all the revisions of an ``IntelligenceFinding`` resource. + + .. 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 storage_control_v2 + + def sample_list_intelligence_finding_revisions(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_finding_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest, dict]): + The request object. Request message to list ``IntelligenceFindingRevision`` + resources associated with a project. + parent (str): + Required. The parent of the + ``IntelligenceFindingRevision`` resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + + 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.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingRevisionsPager: + Response message to list IntelligenceFindingRevision resources associated + with a project. + + 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, storage_control.ListIntelligenceFindingRevisionsRequest + ): + request = storage_control.ListIntelligenceFindingRevisionsRequest(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_intelligence_finding_revisions + ] + + # 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.ListIntelligenceFindingRevisionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "StorageControlClient": return self diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/pagers.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/pagers.py index 1a4f38192bb3..10f47b0b1f8b 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/pagers.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/pagers.py @@ -507,3 +507,485 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListIntelligenceFindingsPager: + """A pager for iterating through ``list_intelligence_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``intelligence_findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIntelligenceFindings`` requests and continue to iterate + through the ``intelligence_findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse` + 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[..., storage_control.ListIntelligenceFindingsResponse], + request: storage_control.ListIntelligenceFindingsRequest, + response: storage_control.ListIntelligenceFindingsResponse, + *, + 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.storage_control_v2.types.ListIntelligenceFindingsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse): + 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 = storage_control.ListIntelligenceFindingsRequest(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[storage_control.ListIntelligenceFindingsResponse]: + 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[storage_control.IntelligenceFinding]: + for page in self.pages: + yield from page.intelligence_findings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListIntelligenceFindingsAsyncPager: + """A pager for iterating through ``list_intelligence_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``intelligence_findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIntelligenceFindings`` requests and continue to iterate + through the ``intelligence_findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse` + 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[storage_control.ListIntelligenceFindingsResponse] + ], + request: storage_control.ListIntelligenceFindingsRequest, + response: storage_control.ListIntelligenceFindingsResponse, + *, + 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.storage_control_v2.types.ListIntelligenceFindingsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListIntelligenceFindingsResponse): + 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 = storage_control.ListIntelligenceFindingsRequest(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[storage_control.ListIntelligenceFindingsResponse]: + 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[storage_control.IntelligenceFinding]: + async def async_generator(): + async for page in self.pages: + for response in page.intelligence_findings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SummarizeIntelligenceFindingsPager: + """A pager for iterating through ``summarize_intelligence_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``finding_summaries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SummarizeIntelligenceFindings`` requests and continue to iterate + through the ``finding_summaries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse` + 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[..., storage_control.SummarizeIntelligenceFindingsResponse], + request: storage_control.SummarizeIntelligenceFindingsRequest, + response: storage_control.SummarizeIntelligenceFindingsResponse, + *, + 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.storage_control_v2.types.SummarizeIntelligenceFindingsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse): + 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 = storage_control.SummarizeIntelligenceFindingsRequest(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[storage_control.SummarizeIntelligenceFindingsResponse]: + 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[storage_control.FindingSummary]: + for page in self.pages: + yield from page.finding_summaries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SummarizeIntelligenceFindingsAsyncPager: + """A pager for iterating through ``summarize_intelligence_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``finding_summaries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SummarizeIntelligenceFindings`` requests and continue to iterate + through the ``finding_summaries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse` + 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[storage_control.SummarizeIntelligenceFindingsResponse] + ], + request: storage_control.SummarizeIntelligenceFindingsRequest, + response: storage_control.SummarizeIntelligenceFindingsResponse, + *, + 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.storage_control_v2.types.SummarizeIntelligenceFindingsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsResponse): + 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 = storage_control.SummarizeIntelligenceFindingsRequest(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[storage_control.SummarizeIntelligenceFindingsResponse]: + 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[storage_control.FindingSummary]: + async def async_generator(): + async for page in self.pages: + for response in page.finding_summaries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListIntelligenceFindingRevisionsPager: + """A pager for iterating through ``list_intelligence_finding_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``intelligence_finding_revisions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIntelligenceFindingRevisions`` requests and continue to iterate + through the ``intelligence_finding_revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse` + 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[..., storage_control.ListIntelligenceFindingRevisionsResponse], + request: storage_control.ListIntelligenceFindingRevisionsRequest, + response: storage_control.ListIntelligenceFindingRevisionsResponse, + *, + 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.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse): + 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 = storage_control.ListIntelligenceFindingRevisionsRequest(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[storage_control.ListIntelligenceFindingRevisionsResponse]: + 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[storage_control.IntelligenceFindingRevision]: + for page in self.pages: + yield from page.intelligence_finding_revisions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListIntelligenceFindingRevisionsAsyncPager: + """A pager for iterating through ``list_intelligence_finding_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``intelligence_finding_revisions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIntelligenceFindingRevisions`` requests and continue to iterate + through the ``intelligence_finding_revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse` + 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[storage_control.ListIntelligenceFindingRevisionsResponse] + ], + request: storage_control.ListIntelligenceFindingRevisionsRequest, + response: storage_control.ListIntelligenceFindingRevisionsResponse, + *, + 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.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest): + The initial request object. + response (google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsResponse): + 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 = storage_control.ListIntelligenceFindingRevisionsRequest(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[storage_control.ListIntelligenceFindingRevisionsResponse]: + 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[storage_control.IntelligenceFindingRevision]: + async def async_generator(): + async for page in self.pages: + for response in page.intelligence_finding_revisions: + 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-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/base.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/base.py index 4703b0fc6bc9..2da4754fb5f0 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/base.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/base.py @@ -560,6 +560,96 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_intelligence_finding: gapic_v1.method.wrap_method( + self.get_intelligence_finding, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_intelligence_findings: gapic_v1.method.wrap_method( + self.list_intelligence_findings, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.summarize_intelligence_findings: gapic_v1.method.wrap_method( + self.summarize_intelligence_findings, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_intelligence_finding_revision: gapic_v1.method.wrap_method( + self.get_intelligence_finding_revision, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_intelligence_finding_revisions: gapic_v1.method.wrap_method( + self.list_intelligence_finding_revisions, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -849,6 +939,66 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def get_intelligence_finding( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRequest], + Union[ + storage_control.IntelligenceFinding, + Awaitable[storage_control.IntelligenceFinding], + ], + ]: + raise NotImplementedError() + + @property + def list_intelligence_findings( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingsRequest], + Union[ + storage_control.ListIntelligenceFindingsResponse, + Awaitable[storage_control.ListIntelligenceFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def summarize_intelligence_findings( + self, + ) -> Callable[ + [storage_control.SummarizeIntelligenceFindingsRequest], + Union[ + storage_control.SummarizeIntelligenceFindingsResponse, + Awaitable[storage_control.SummarizeIntelligenceFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_intelligence_finding_revision( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRevisionRequest], + Union[ + storage_control.IntelligenceFindingRevision, + Awaitable[storage_control.IntelligenceFindingRevision], + ], + ]: + raise NotImplementedError() + + @property + def list_intelligence_finding_revisions( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingRevisionsRequest], + Union[ + storage_control.ListIntelligenceFindingRevisionsResponse, + Awaitable[storage_control.ListIntelligenceFindingRevisionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py index 995173b360c1..d2aa00ce2f14 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc.py @@ -1154,6 +1154,164 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def get_intelligence_finding( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRequest], + storage_control.IntelligenceFinding, + ]: + r"""Return a callable for the get intelligence finding method over gRPC. + + Gets the ``IntelligenceFinding`` for a project. + + Returns: + Callable[[~.GetIntelligenceFindingRequest], + ~.IntelligenceFinding]: + 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_intelligence_finding" not in self._stubs: + self._stubs["get_intelligence_finding"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIntelligenceFinding", + request_serializer=storage_control.GetIntelligenceFindingRequest.serialize, + response_deserializer=storage_control.IntelligenceFinding.deserialize, + ) + return self._stubs["get_intelligence_finding"] + + @property + def list_intelligence_findings( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingsRequest], + storage_control.ListIntelligenceFindingsResponse, + ]: + r"""Return a callable for the list intelligence findings method over gRPC. + + Lists the ``IntelligenceFinding`` resources for the specified + project. + + Returns: + Callable[[~.ListIntelligenceFindingsRequest], + ~.ListIntelligenceFindingsResponse]: + 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_intelligence_findings" not in self._stubs: + self._stubs["list_intelligence_findings"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListIntelligenceFindings", + request_serializer=storage_control.ListIntelligenceFindingsRequest.serialize, + response_deserializer=storage_control.ListIntelligenceFindingsResponse.deserialize, + ) + ) + return self._stubs["list_intelligence_findings"] + + @property + def summarize_intelligence_findings( + self, + ) -> Callable[ + [storage_control.SummarizeIntelligenceFindingsRequest], + storage_control.SummarizeIntelligenceFindingsResponse, + ]: + r"""Return a callable for the summarize intelligence + findings method over gRPC. + + Summarize the intelligence findings for the specified + scope(org, folder or project). + + Returns: + Callable[[~.SummarizeIntelligenceFindingsRequest], + ~.SummarizeIntelligenceFindingsResponse]: + 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 "summarize_intelligence_findings" not in self._stubs: + self._stubs["summarize_intelligence_findings"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/SummarizeIntelligenceFindings", + request_serializer=storage_control.SummarizeIntelligenceFindingsRequest.serialize, + response_deserializer=storage_control.SummarizeIntelligenceFindingsResponse.deserialize, + ) + ) + return self._stubs["summarize_intelligence_findings"] + + @property + def get_intelligence_finding_revision( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRevisionRequest], + storage_control.IntelligenceFindingRevision, + ]: + r"""Return a callable for the get intelligence finding + revision method over gRPC. + + Gets the ``IntelligenceFindingRevision`` resource. + + Returns: + Callable[[~.GetIntelligenceFindingRevisionRequest], + ~.IntelligenceFindingRevision]: + 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_intelligence_finding_revision" not in self._stubs: + self._stubs["get_intelligence_finding_revision"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIntelligenceFindingRevision", + request_serializer=storage_control.GetIntelligenceFindingRevisionRequest.serialize, + response_deserializer=storage_control.IntelligenceFindingRevision.deserialize, + ) + ) + return self._stubs["get_intelligence_finding_revision"] + + @property + def list_intelligence_finding_revisions( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingRevisionsRequest], + storage_control.ListIntelligenceFindingRevisionsResponse, + ]: + r"""Return a callable for the list intelligence finding + revisions method over gRPC. + + Lists all the revisions of an ``IntelligenceFinding`` resource. + + Returns: + Callable[[~.ListIntelligenceFindingRevisionsRequest], + ~.ListIntelligenceFindingRevisionsResponse]: + 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_intelligence_finding_revisions" not in self._stubs: + self._stubs["list_intelligence_finding_revisions"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListIntelligenceFindingRevisions", + request_serializer=storage_control.ListIntelligenceFindingRevisionsRequest.serialize, + response_deserializer=storage_control.ListIntelligenceFindingRevisionsResponse.deserialize, + ) + ) + return self._stubs["list_intelligence_finding_revisions"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py index 9e0c79260dfa..977f265b2ad9 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/grpc_asyncio.py @@ -1181,6 +1181,164 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def get_intelligence_finding( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRequest], + Awaitable[storage_control.IntelligenceFinding], + ]: + r"""Return a callable for the get intelligence finding method over gRPC. + + Gets the ``IntelligenceFinding`` for a project. + + Returns: + Callable[[~.GetIntelligenceFindingRequest], + Awaitable[~.IntelligenceFinding]]: + 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_intelligence_finding" not in self._stubs: + self._stubs["get_intelligence_finding"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIntelligenceFinding", + request_serializer=storage_control.GetIntelligenceFindingRequest.serialize, + response_deserializer=storage_control.IntelligenceFinding.deserialize, + ) + return self._stubs["get_intelligence_finding"] + + @property + def list_intelligence_findings( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingsRequest], + Awaitable[storage_control.ListIntelligenceFindingsResponse], + ]: + r"""Return a callable for the list intelligence findings method over gRPC. + + Lists the ``IntelligenceFinding`` resources for the specified + project. + + Returns: + Callable[[~.ListIntelligenceFindingsRequest], + Awaitable[~.ListIntelligenceFindingsResponse]]: + 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_intelligence_findings" not in self._stubs: + self._stubs["list_intelligence_findings"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListIntelligenceFindings", + request_serializer=storage_control.ListIntelligenceFindingsRequest.serialize, + response_deserializer=storage_control.ListIntelligenceFindingsResponse.deserialize, + ) + ) + return self._stubs["list_intelligence_findings"] + + @property + def summarize_intelligence_findings( + self, + ) -> Callable[ + [storage_control.SummarizeIntelligenceFindingsRequest], + Awaitable[storage_control.SummarizeIntelligenceFindingsResponse], + ]: + r"""Return a callable for the summarize intelligence + findings method over gRPC. + + Summarize the intelligence findings for the specified + scope(org, folder or project). + + Returns: + Callable[[~.SummarizeIntelligenceFindingsRequest], + Awaitable[~.SummarizeIntelligenceFindingsResponse]]: + 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 "summarize_intelligence_findings" not in self._stubs: + self._stubs["summarize_intelligence_findings"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/SummarizeIntelligenceFindings", + request_serializer=storage_control.SummarizeIntelligenceFindingsRequest.serialize, + response_deserializer=storage_control.SummarizeIntelligenceFindingsResponse.deserialize, + ) + ) + return self._stubs["summarize_intelligence_findings"] + + @property + def get_intelligence_finding_revision( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRevisionRequest], + Awaitable[storage_control.IntelligenceFindingRevision], + ]: + r"""Return a callable for the get intelligence finding + revision method over gRPC. + + Gets the ``IntelligenceFindingRevision`` resource. + + Returns: + Callable[[~.GetIntelligenceFindingRevisionRequest], + Awaitable[~.IntelligenceFindingRevision]]: + 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_intelligence_finding_revision" not in self._stubs: + self._stubs["get_intelligence_finding_revision"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/GetIntelligenceFindingRevision", + request_serializer=storage_control.GetIntelligenceFindingRevisionRequest.serialize, + response_deserializer=storage_control.IntelligenceFindingRevision.deserialize, + ) + ) + return self._stubs["get_intelligence_finding_revision"] + + @property + def list_intelligence_finding_revisions( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingRevisionsRequest], + Awaitable[storage_control.ListIntelligenceFindingRevisionsResponse], + ]: + r"""Return a callable for the list intelligence finding + revisions method over gRPC. + + Lists all the revisions of an ``IntelligenceFinding`` resource. + + Returns: + Callable[[~.ListIntelligenceFindingRevisionsRequest], + Awaitable[~.ListIntelligenceFindingRevisionsResponse]]: + 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_intelligence_finding_revisions" not in self._stubs: + self._stubs["list_intelligence_finding_revisions"] = ( + self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/ListIntelligenceFindingRevisions", + request_serializer=storage_control.ListIntelligenceFindingRevisionsRequest.serialize, + response_deserializer=storage_control.ListIntelligenceFindingRevisionsResponse.deserialize, + ) + ) + return self._stubs["list_intelligence_finding_revisions"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1592,6 +1750,96 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_intelligence_finding: self._wrap_method( + self.get_intelligence_finding, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_intelligence_findings: self._wrap_method( + self.list_intelligence_findings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.summarize_intelligence_findings: self._wrap_method( + self.summarize_intelligence_findings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_intelligence_finding_revision: self._wrap_method( + self.get_intelligence_finding_revision, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_intelligence_finding_revisions: self._wrap_method( + self.list_intelligence_finding_revisions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=2, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest.py index 0bd21ae8393c..b17a22298df2 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest.py @@ -156,6 +156,22 @@ def post_get_iam_policy(self, response): logging.log(f"Received response: {response}") return response + def pre_get_intelligence_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_intelligence_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_intelligence_finding_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_intelligence_finding_revision(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_managed_folder(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -204,6 +220,22 @@ def post_list_folders(self, response): logging.log(f"Received response: {response}") return response + def pre_list_intelligence_finding_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_intelligence_finding_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_intelligence_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_intelligence_findings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_managed_folders(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -244,6 +276,14 @@ def post_set_iam_policy(self, response): logging.log(f"Received response: {response}") return response + def pre_summarize_intelligence_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_summarize_intelligence_findings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_test_iam_permissions(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -341,6 +381,109 @@ def post_get_folder_intelligence_config_with_metadata( """ return response, metadata + def pre_get_intelligence_finding( + self, + request: storage_control.GetIntelligenceFindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.GetIntelligenceFindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_intelligence_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_get_intelligence_finding( + self, response: storage_control.IntelligenceFinding + ) -> storage_control.IntelligenceFinding: + """Post-rpc interceptor for get_intelligence_finding + + DEPRECATED. Please use the `post_get_intelligence_finding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_get_intelligence_finding` interceptor runs + before the `post_get_intelligence_finding_with_metadata` interceptor. + """ + return response + + def post_get_intelligence_finding_with_metadata( + self, + response: storage_control.IntelligenceFinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceFinding, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_intelligence_finding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_get_intelligence_finding_with_metadata` + interceptor in new development instead of the `post_get_intelligence_finding` interceptor. + When both interceptors are used, this `post_get_intelligence_finding_with_metadata` interceptor runs after the + `post_get_intelligence_finding` interceptor. The (possibly modified) response returned by + `post_get_intelligence_finding` will be passed to + `post_get_intelligence_finding_with_metadata`. + """ + return response, metadata + + def pre_get_intelligence_finding_revision( + self, + request: storage_control.GetIntelligenceFindingRevisionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.GetIntelligenceFindingRevisionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_intelligence_finding_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_get_intelligence_finding_revision( + self, response: storage_control.IntelligenceFindingRevision + ) -> storage_control.IntelligenceFindingRevision: + """Post-rpc interceptor for get_intelligence_finding_revision + + DEPRECATED. Please use the `post_get_intelligence_finding_revision_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_get_intelligence_finding_revision` interceptor runs + before the `post_get_intelligence_finding_revision_with_metadata` interceptor. + """ + return response + + def post_get_intelligence_finding_revision_with_metadata( + self, + response: storage_control.IntelligenceFindingRevision, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.IntelligenceFindingRevision, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_intelligence_finding_revision + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_get_intelligence_finding_revision_with_metadata` + interceptor in new development instead of the `post_get_intelligence_finding_revision` interceptor. + When both interceptors are used, this `post_get_intelligence_finding_revision_with_metadata` interceptor runs after the + `post_get_intelligence_finding_revision` interceptor. The (possibly modified) response returned by + `post_get_intelligence_finding_revision` will be passed to + `post_get_intelligence_finding_revision_with_metadata`. + """ + return response, metadata + def pre_get_organization_intelligence_config( self, request: storage_control.GetOrganizationIntelligenceConfigRequest, @@ -443,6 +586,162 @@ def post_get_project_intelligence_config_with_metadata( """ return response, metadata + def pre_list_intelligence_finding_revisions( + self, + request: storage_control.ListIntelligenceFindingRevisionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.ListIntelligenceFindingRevisionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_intelligence_finding_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_list_intelligence_finding_revisions( + self, response: storage_control.ListIntelligenceFindingRevisionsResponse + ) -> storage_control.ListIntelligenceFindingRevisionsResponse: + """Post-rpc interceptor for list_intelligence_finding_revisions + + DEPRECATED. Please use the `post_list_intelligence_finding_revisions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_list_intelligence_finding_revisions` interceptor runs + before the `post_list_intelligence_finding_revisions_with_metadata` interceptor. + """ + return response + + def post_list_intelligence_finding_revisions_with_metadata( + self, + response: storage_control.ListIntelligenceFindingRevisionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.ListIntelligenceFindingRevisionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_intelligence_finding_revisions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_list_intelligence_finding_revisions_with_metadata` + interceptor in new development instead of the `post_list_intelligence_finding_revisions` interceptor. + When both interceptors are used, this `post_list_intelligence_finding_revisions_with_metadata` interceptor runs after the + `post_list_intelligence_finding_revisions` interceptor. The (possibly modified) response returned by + `post_list_intelligence_finding_revisions` will be passed to + `post_list_intelligence_finding_revisions_with_metadata`. + """ + return response, metadata + + def pre_list_intelligence_findings( + self, + request: storage_control.ListIntelligenceFindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.ListIntelligenceFindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_intelligence_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_list_intelligence_findings( + self, response: storage_control.ListIntelligenceFindingsResponse + ) -> storage_control.ListIntelligenceFindingsResponse: + """Post-rpc interceptor for list_intelligence_findings + + DEPRECATED. Please use the `post_list_intelligence_findings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_list_intelligence_findings` interceptor runs + before the `post_list_intelligence_findings_with_metadata` interceptor. + """ + return response + + def post_list_intelligence_findings_with_metadata( + self, + response: storage_control.ListIntelligenceFindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.ListIntelligenceFindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_intelligence_findings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_list_intelligence_findings_with_metadata` + interceptor in new development instead of the `post_list_intelligence_findings` interceptor. + When both interceptors are used, this `post_list_intelligence_findings_with_metadata` interceptor runs after the + `post_list_intelligence_findings` interceptor. The (possibly modified) response returned by + `post_list_intelligence_findings` will be passed to + `post_list_intelligence_findings_with_metadata`. + """ + return response, metadata + + def pre_summarize_intelligence_findings( + self, + request: storage_control.SummarizeIntelligenceFindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.SummarizeIntelligenceFindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for summarize_intelligence_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the StorageControl server. + """ + return request, metadata + + def post_summarize_intelligence_findings( + self, response: storage_control.SummarizeIntelligenceFindingsResponse + ) -> storage_control.SummarizeIntelligenceFindingsResponse: + """Post-rpc interceptor for summarize_intelligence_findings + + DEPRECATED. Please use the `post_summarize_intelligence_findings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the StorageControl server but before + it is returned to user code. This `post_summarize_intelligence_findings` interceptor runs + before the `post_summarize_intelligence_findings_with_metadata` interceptor. + """ + return response + + def post_summarize_intelligence_findings_with_metadata( + self, + response: storage_control.SummarizeIntelligenceFindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + storage_control.SummarizeIntelligenceFindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for summarize_intelligence_findings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the StorageControl server but before it is returned to user code. + + We recommend only using this `post_summarize_intelligence_findings_with_metadata` + interceptor in new development instead of the `post_summarize_intelligence_findings` interceptor. + When both interceptors are used, this `post_summarize_intelligence_findings_with_metadata` interceptor runs after the + `post_summarize_intelligence_findings` interceptor. The (possibly modified) response returned by + `post_summarize_intelligence_findings` will be passed to + `post_summarize_intelligence_findings_with_metadata`. + """ + return response, metadata + def pre_update_folder_intelligence_config( self, request: storage_control.UpdateFolderIntelligenceConfigRequest, @@ -1065,30 +1364,12 @@ def __call__( "Method GetIamPolicy is not available over REST transport" ) - class _GetManagedFolder( - _BaseStorageControlRestTransport._BaseGetManagedFolder, StorageControlRestStub - ): - def __hash__(self): - return hash("StorageControlRestTransport.GetManagedFolder") - - def __call__( - self, - request: storage_control.GetManagedFolderRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.ManagedFolder: - raise NotImplementedError( - "Method GetManagedFolder is not available over REST transport" - ) - - class _GetOrganizationIntelligenceConfig( - _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig, + class _GetIntelligenceFinding( + _BaseStorageControlRestTransport._BaseGetIntelligenceFinding, StorageControlRestStub, ): def __hash__(self): - return hash("StorageControlRestTransport.GetOrganizationIntelligenceConfig") + return hash("StorageControlRestTransport.GetIntelligenceFinding") @staticmethod def _get_response( @@ -1114,53 +1395,45 @@ def _get_response( def __call__( self, - request: storage_control.GetOrganizationIntelligenceConfigRequest, + request: storage_control.GetIntelligenceFindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.IntelligenceConfig: - r"""Call the get organization - intelligence config method over HTTP. - - Args: - request (~.storage_control.GetOrganizationIntelligenceConfigRequest): - The request object. Request message to get the ``IntelligenceConfig`` - resource associated with your organization. - - **IAM Permissions** - - Requires ``storage.intelligenceConfigs.get`` - `IAM `__ - permission on the organization. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.storage_control.IntelligenceConfig: - The ``IntelligenceConfig`` resource associated with your - organization, folder, or project. + ) -> storage_control.IntelligenceFinding: + r"""Call the get intelligence finding method over HTTP. + + Args: + request (~.storage_control.GetIntelligenceFindingRequest): + The request object. Request message to get the ``IntelligenceFinding`` + resource associated with a project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.IntelligenceFinding: + The ``IntelligenceFinding`` resource that represents a + security, performance, or cost-related finding about a + project or bucket. """ - http_options = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_http_options() + http_options = _BaseStorageControlRestTransport._BaseGetIntelligenceFinding._get_http_options() - request, metadata = ( - self._interceptor.pre_get_organization_intelligence_config( - request, metadata - ) + request, metadata = self._interceptor.pre_get_intelligence_finding( + request, metadata ) - transcoded_request = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_transcoded_request( + transcoded_request = _BaseStorageControlRestTransport._BaseGetIntelligenceFinding._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_query_params_json( + query_params = _BaseStorageControlRestTransport._BaseGetIntelligenceFinding._get_query_params_json( transcoded_request ) @@ -1182,40 +1455,534 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.storage.control_v2.StorageControlClient.GetOrganizationIntelligenceConfig", + f"Sending request for google.storage.control_v2.StorageControlClient.GetIntelligenceFinding", extra={ "serviceName": "google.storage.control.v2.StorageControl", - "rpcName": "GetOrganizationIntelligenceConfig", + "rpcName": "GetIntelligenceFinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = StorageControlRestTransport._GetOrganizationIntelligenceConfig._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) - + response = ( + StorageControlRestTransport._GetIntelligenceFinding._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 = storage_control.IntelligenceFinding() + pb_resp = storage_control.IntelligenceFinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_intelligence_finding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_intelligence_finding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceFinding.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.storage.control_v2.StorageControlClient.get_intelligence_finding", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetIntelligenceFinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetIntelligenceFindingRevision( + _BaseStorageControlRestTransport._BaseGetIntelligenceFindingRevision, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetIntelligenceFindingRevision") + + @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: storage_control.GetIntelligenceFindingRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceFindingRevision: + r"""Call the get intelligence finding + revision method over HTTP. + + Args: + request (~.storage_control.GetIntelligenceFindingRevisionRequest): + The request object. Request message to get the + ``IntelligenceFindingRevision`` resource associated with + a project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.IntelligenceFindingRevision: + An ``IntelligenceFindingRevision`` represents a specific + revision of an ``IntelligenceFinding`` resource. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetIntelligenceFindingRevision._get_http_options() + + request, metadata = self._interceptor.pre_get_intelligence_finding_revision( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetIntelligenceFindingRevision._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetIntelligenceFindingRevision._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.storage.control_v2.StorageControlClient.GetIntelligenceFindingRevision", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetIntelligenceFindingRevision", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._GetIntelligenceFindingRevision._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 = storage_control.IntelligenceFindingRevision() + pb_resp = storage_control.IntelligenceFindingRevision.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_intelligence_finding_revision(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_intelligence_finding_revision_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + storage_control.IntelligenceFindingRevision.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.storage.control_v2.StorageControlClient.get_intelligence_finding_revision", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetIntelligenceFindingRevision", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetManagedFolder( + _BaseStorageControlRestTransport._BaseGetManagedFolder, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetManagedFolder") + + def __call__( + self, + request: storage_control.GetManagedFolderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ManagedFolder: + raise NotImplementedError( + "Method GetManagedFolder is not available over REST transport" + ) + + class _GetOrganizationIntelligenceConfig( + _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetOrganizationIntelligenceConfig") + + @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: storage_control.GetOrganizationIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the get organization + intelligence config method over HTTP. + + Args: + request (~.storage_control.GetOrganizationIntelligenceConfigRequest): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your organization. + + **IAM Permissions** + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the organization. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_organization_intelligence_config( + request, metadata + ) + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetOrganizationIntelligenceConfig._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.storage.control_v2.StorageControlClient.GetOrganizationIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetOrganizationIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._GetOrganizationIntelligenceConfig._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 = storage_control.IntelligenceConfig() + pb_resp = storage_control.IntelligenceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_organization_intelligence_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_organization_intelligence_config_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.IntelligenceConfig.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.storage.control_v2.StorageControlClient.get_organization_intelligence_config", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetOrganizationIntelligenceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetProjectIntelligenceConfig( + _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetProjectIntelligenceConfig") + + @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: storage_control.GetProjectIntelligenceConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.IntelligenceConfig: + r"""Call the get project intelligence + config method over HTTP. + + Args: + request (~.storage_control.GetProjectIntelligenceConfigRequest): + The request object. Request message to get the ``IntelligenceConfig`` + resource associated with your project. + + **IAM Permissions**: + + Requires ``storage.intelligenceConfigs.get`` + `IAM `__ + permission on the project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.IntelligenceConfig: + The ``IntelligenceConfig`` resource associated with your + organization, folder, or project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_project_intelligence_config( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._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.storage.control_v2.StorageControlClient.GetProjectIntelligenceConfig", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "GetProjectIntelligenceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + StorageControlRestTransport._GetProjectIntelligenceConfig._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 = storage_control.IntelligenceConfig() pb_resp = storage_control.IntelligenceConfig.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_organization_intelligence_config(resp) + resp = self._interceptor.post_get_project_intelligence_config(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_get_organization_intelligence_config_with_metadata( + self._interceptor.post_get_project_intelligence_config_with_metadata( resp, response_metadata ) ) @@ -1234,22 +2001,76 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.storage.control_v2.StorageControlClient.get_organization_intelligence_config", + "Received response for google.storage.control_v2.StorageControlClient.get_project_intelligence_config", extra={ "serviceName": "google.storage.control.v2.StorageControl", - "rpcName": "GetOrganizationIntelligenceConfig", + "rpcName": "GetProjectIntelligenceConfig", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetProjectIntelligenceConfig( - _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig, + class _GetStorageLayout( + _BaseStorageControlRestTransport._BaseGetStorageLayout, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.GetStorageLayout") + + def __call__( + self, + request: storage_control.GetStorageLayoutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.StorageLayout: + raise NotImplementedError( + "Method GetStorageLayout is not available over REST transport" + ) + + class _ListAnywhereCaches( + _BaseStorageControlRestTransport._BaseListAnywhereCaches, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListAnywhereCaches") + + def __call__( + self, + request: storage_control.ListAnywhereCachesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListAnywhereCachesResponse: + raise NotImplementedError( + "Method ListAnywhereCaches is not available over REST transport" + ) + + class _ListFolders( + _BaseStorageControlRestTransport._BaseListFolders, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListFolders") + + def __call__( + self, + request: storage_control.ListFoldersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListFoldersResponse: + raise NotImplementedError( + "Method ListFolders is not available over REST transport" + ) + + class _ListIntelligenceFindingRevisions( + _BaseStorageControlRestTransport._BaseListIntelligenceFindingRevisions, StorageControlRestStub, ): def __hash__(self): - return hash("StorageControlRestTransport.GetProjectIntelligenceConfig") + return hash("StorageControlRestTransport.ListIntelligenceFindingRevisions") @staticmethod def _get_response( @@ -1275,25 +2096,174 @@ def _get_response( def __call__( self, - request: storage_control.GetProjectIntelligenceConfigRequest, + request: storage_control.ListIntelligenceFindingRevisionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.IntelligenceConfig: - r"""Call the get project intelligence - config method over HTTP. + ) -> storage_control.ListIntelligenceFindingRevisionsResponse: + r"""Call the list intelligence finding + revisions method over HTTP. Args: - request (~.storage_control.GetProjectIntelligenceConfigRequest): - The request object. Request message to get the ``IntelligenceConfig`` - resource associated with your project. + request (~.storage_control.ListIntelligenceFindingRevisionsRequest): + The request object. Request message to list ``IntelligenceFindingRevision`` + resources associated with a project. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.ListIntelligenceFindingRevisionsResponse: + Response message to list ``IntelligenceFindingRevision`` + resources associated with a project. + + """ + + http_options = _BaseStorageControlRestTransport._BaseListIntelligenceFindingRevisions._get_http_options() + + request, metadata = ( + self._interceptor.pre_list_intelligence_finding_revisions( + request, metadata + ) + ) + transcoded_request = _BaseStorageControlRestTransport._BaseListIntelligenceFindingRevisions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseListIntelligenceFindingRevisions._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.storage.control_v2.StorageControlClient.ListIntelligenceFindingRevisions", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "ListIntelligenceFindingRevisions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._ListIntelligenceFindingRevisions._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 = storage_control.ListIntelligenceFindingRevisionsResponse() + pb_resp = storage_control.ListIntelligenceFindingRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_intelligence_finding_revisions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_intelligence_finding_revisions_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = storage_control.ListIntelligenceFindingRevisionsResponse.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.storage.control_v2.StorageControlClient.list_intelligence_finding_revisions", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "ListIntelligenceFindingRevisions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListIntelligenceFindings( + _BaseStorageControlRestTransport._BaseListIntelligenceFindings, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.ListIntelligenceFindings") + + @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 - **IAM Permissions**: + def __call__( + self, + request: storage_control.ListIntelligenceFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.ListIntelligenceFindingsResponse: + r"""Call the list intelligence + findings method over HTTP. - Requires ``storage.intelligenceConfigs.get`` - `IAM `__ - permission on the project. + Args: + request (~.storage_control.ListIntelligenceFindingsRequest): + The request object. Request message to list ``IntelligenceFinding`` + resources associated with a project. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1303,23 +2273,23 @@ def __call__( be of type `bytes`. Returns: - ~.storage_control.IntelligenceConfig: - The ``IntelligenceConfig`` resource associated with your - organization, folder, or project. + ~.storage_control.ListIntelligenceFindingsResponse: + Response message to list the ``IntelligenceFinding`` + resources associated with a project. """ - http_options = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_http_options() + http_options = _BaseStorageControlRestTransport._BaseListIntelligenceFindings._get_http_options() - request, metadata = self._interceptor.pre_get_project_intelligence_config( + request, metadata = self._interceptor.pre_list_intelligence_findings( request, metadata ) - transcoded_request = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_transcoded_request( + transcoded_request = _BaseStorageControlRestTransport._BaseListIntelligenceFindings._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseStorageControlRestTransport._BaseGetProjectIntelligenceConfig._get_query_params_json( + query_params = _BaseStorageControlRestTransport._BaseListIntelligenceFindings._get_query_params_json( transcoded_request ) @@ -1341,10 +2311,10 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.storage.control_v2.StorageControlClient.GetProjectIntelligenceConfig", + f"Sending request for google.storage.control_v2.StorageControlClient.ListIntelligenceFindings", extra={ "serviceName": "google.storage.control.v2.StorageControl", - "rpcName": "GetProjectIntelligenceConfig", + "rpcName": "ListIntelligenceFindings", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -1352,7 +2322,7 @@ def __call__( # Send the request response = ( - StorageControlRestTransport._GetProjectIntelligenceConfig._get_response( + StorageControlRestTransport._ListIntelligenceFindings._get_response( self._host, metadata, query_params, @@ -1368,24 +2338,24 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = storage_control.IntelligenceConfig() - pb_resp = storage_control.IntelligenceConfig.pb(resp) + resp = storage_control.ListIntelligenceFindingsResponse() + pb_resp = storage_control.ListIntelligenceFindingsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_project_intelligence_config(resp) + resp = self._interceptor.post_list_intelligence_findings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_get_project_intelligence_config_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_intelligence_findings_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = storage_control.IntelligenceConfig.to_json( - response + response_payload = ( + storage_control.ListIntelligenceFindingsResponse.to_json( + response + ) ) except: response_payload = None @@ -1395,70 +2365,16 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.storage.control_v2.StorageControlClient.get_project_intelligence_config", + "Received response for google.storage.control_v2.StorageControlClient.list_intelligence_findings", extra={ "serviceName": "google.storage.control.v2.StorageControl", - "rpcName": "GetProjectIntelligenceConfig", + "rpcName": "ListIntelligenceFindings", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetStorageLayout( - _BaseStorageControlRestTransport._BaseGetStorageLayout, StorageControlRestStub - ): - def __hash__(self): - return hash("StorageControlRestTransport.GetStorageLayout") - - def __call__( - self, - request: storage_control.GetStorageLayoutRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.StorageLayout: - raise NotImplementedError( - "Method GetStorageLayout is not available over REST transport" - ) - - class _ListAnywhereCaches( - _BaseStorageControlRestTransport._BaseListAnywhereCaches, StorageControlRestStub - ): - def __hash__(self): - return hash("StorageControlRestTransport.ListAnywhereCaches") - - def __call__( - self, - request: storage_control.ListAnywhereCachesRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.ListAnywhereCachesResponse: - raise NotImplementedError( - "Method ListAnywhereCaches is not available over REST transport" - ) - - class _ListFolders( - _BaseStorageControlRestTransport._BaseListFolders, StorageControlRestStub - ): - def __hash__(self): - return hash("StorageControlRestTransport.ListFolders") - - def __call__( - self, - request: storage_control.ListFoldersRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> storage_control.ListFoldersResponse: - raise NotImplementedError( - "Method ListFolders is not available over REST transport" - ) - class _ListManagedFolders( _BaseStorageControlRestTransport._BaseListManagedFolders, StorageControlRestStub ): @@ -1550,6 +2466,163 @@ def __call__( "Method SetIamPolicy is not available over REST transport" ) + class _SummarizeIntelligenceFindings( + _BaseStorageControlRestTransport._BaseSummarizeIntelligenceFindings, + StorageControlRestStub, + ): + def __hash__(self): + return hash("StorageControlRestTransport.SummarizeIntelligenceFindings") + + @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: storage_control.SummarizeIntelligenceFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> storage_control.SummarizeIntelligenceFindingsResponse: + r"""Call the summarize intelligence + findings method over HTTP. + + Args: + request (~.storage_control.SummarizeIntelligenceFindingsRequest): + The request object. Request message to summarize the + intelligence findings for the specified + scope(org, folder or project). + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.storage_control.SummarizeIntelligenceFindingsResponse: + Response message to summarize the + intelligence findings for a specified + scope(org, folder or project). + + """ + + http_options = _BaseStorageControlRestTransport._BaseSummarizeIntelligenceFindings._get_http_options() + + request, metadata = self._interceptor.pre_summarize_intelligence_findings( + request, metadata + ) + transcoded_request = _BaseStorageControlRestTransport._BaseSummarizeIntelligenceFindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseStorageControlRestTransport._BaseSummarizeIntelligenceFindings._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.storage.control_v2.StorageControlClient.SummarizeIntelligenceFindings", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "SummarizeIntelligenceFindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = StorageControlRestTransport._SummarizeIntelligenceFindings._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 = storage_control.SummarizeIntelligenceFindingsResponse() + pb_resp = storage_control.SummarizeIntelligenceFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_summarize_intelligence_findings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_summarize_intelligence_findings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + storage_control.SummarizeIntelligenceFindingsResponse.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.storage.control_v2.StorageControlClient.summarize_intelligence_findings", + extra={ + "serviceName": "google.storage.control.v2.StorageControl", + "rpcName": "SummarizeIntelligenceFindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _TestIamPermissions( _BaseStorageControlRestTransport._BaseTestIamPermissions, StorageControlRestStub ): @@ -2191,6 +3264,32 @@ def get_iam_policy( # In C++ this would require a dynamic_cast return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_intelligence_finding( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRequest], + storage_control.IntelligenceFinding, + ]: + # 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._GetIntelligenceFinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_intelligence_finding_revision( + self, + ) -> Callable[ + [storage_control.GetIntelligenceFindingRevisionRequest], + storage_control.IntelligenceFindingRevision, + ]: + # 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._GetIntelligenceFindingRevision( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_managed_folder( self, @@ -2258,6 +3357,32 @@ def list_folders( # In C++ this would require a dynamic_cast return self._ListFolders(self._session, self._host, self._interceptor) # type: ignore + @property + def list_intelligence_finding_revisions( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingRevisionsRequest], + storage_control.ListIntelligenceFindingRevisionsResponse, + ]: + # 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._ListIntelligenceFindingRevisions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_intelligence_findings( + self, + ) -> Callable[ + [storage_control.ListIntelligenceFindingsRequest], + storage_control.ListIntelligenceFindingsResponse, + ]: + # 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._ListIntelligenceFindings( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_managed_folders( self, @@ -2305,6 +3430,19 @@ def set_iam_policy( # In C++ this would require a dynamic_cast return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def summarize_intelligence_findings( + self, + ) -> Callable[ + [storage_control.SummarizeIntelligenceFindingsRequest], + storage_control.SummarizeIntelligenceFindingsResponse, + ]: + # 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._SummarizeIntelligenceFindings( + self._session, self._host, self._interceptor + ) # type: ignore + @property def test_iam_permissions( self, diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py index f7e79b156bf3..018f6b406b37 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/services/storage_control/transports/rest_base.py @@ -178,6 +178,102 @@ class _BaseGetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + class _BaseGetIntelligenceFinding: + 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/*/intelligenceFindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.GetIntelligenceFindingRequest.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( + _BaseStorageControlRestTransport._BaseGetIntelligenceFinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIntelligenceFindingRevision: + 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/*/intelligenceFindings/*/revisions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.GetIntelligenceFindingRevisionRequest.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( + _BaseStorageControlRestTransport._BaseGetIntelligenceFindingRevision._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetManagedFolder: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -290,6 +386,102 @@ class _BaseListFolders: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + class _BaseListIntelligenceFindingRevisions: + 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/*/intelligenceFindings/*}/revisions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.ListIntelligenceFindingRevisionsRequest.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( + _BaseStorageControlRestTransport._BaseListIntelligenceFindingRevisions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListIntelligenceFindings: + 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/*}/intelligenceFindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.ListIntelligenceFindingsRequest.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( + _BaseStorageControlRestTransport._BaseListIntelligenceFindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListManagedFolders: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -310,6 +502,63 @@ class _BaseSetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + class _BaseSummarizeIntelligenceFindings: + 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/*}/intelligenceFindings:summarize", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/locations/*}/intelligenceFindings:summarize", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/intelligenceFindings:summarize", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = storage_control.SummarizeIntelligenceFindingsRequest.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( + _BaseStorageControlRestTransport._BaseSummarizeIntelligenceFindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseTestIamPermissions: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/__init__.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/__init__.py index 9e3022355421..7cc78e7b90b9 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/__init__.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/__init__.py @@ -25,19 +25,31 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + FindingCategory, + FindingSeverity, + FindingSummary, + FindingType, Folder, GetAnywhereCacheRequest, GetFolderIntelligenceConfigRequest, GetFolderRequest, + GetIntelligenceFindingRequest, + GetIntelligenceFindingRevisionRequest, GetManagedFolderRequest, GetOrganizationIntelligenceConfigRequest, GetProjectIntelligenceConfigRequest, GetStorageLayoutRequest, IntelligenceConfig, + IntelligenceFinding, + IntelligenceFindingRevision, ListAnywhereCachesRequest, ListAnywhereCachesResponse, ListFoldersRequest, ListFoldersResponse, + ListIntelligenceFindingRevisionsRequest, + ListIntelligenceFindingRevisionsResponse, + ListIntelligenceFindingsRequest, + ListIntelligenceFindingsResponse, ListManagedFoldersRequest, ListManagedFoldersResponse, ManagedFolder, @@ -47,6 +59,8 @@ RenameFolderRequest, ResumeAnywhereCacheRequest, StorageLayout, + SummarizeIntelligenceFindingsRequest, + SummarizeIntelligenceFindingsResponse, UpdateAnywhereCacheMetadata, UpdateAnywhereCacheRequest, UpdateFolderIntelligenceConfigRequest, @@ -66,19 +80,28 @@ "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "FindingSummary", "Folder", "GetAnywhereCacheRequest", "GetFolderIntelligenceConfigRequest", "GetFolderRequest", + "GetIntelligenceFindingRequest", + "GetIntelligenceFindingRevisionRequest", "GetManagedFolderRequest", "GetOrganizationIntelligenceConfigRequest", "GetProjectIntelligenceConfigRequest", "GetStorageLayoutRequest", "IntelligenceConfig", + "IntelligenceFinding", + "IntelligenceFindingRevision", "ListAnywhereCachesRequest", "ListAnywhereCachesResponse", "ListFoldersRequest", "ListFoldersResponse", + "ListIntelligenceFindingRevisionsRequest", + "ListIntelligenceFindingRevisionsResponse", + "ListIntelligenceFindingsRequest", + "ListIntelligenceFindingsResponse", "ListManagedFoldersRequest", "ListManagedFoldersResponse", "ManagedFolder", @@ -88,9 +111,14 @@ "RenameFolderRequest", "ResumeAnywhereCacheRequest", "StorageLayout", + "SummarizeIntelligenceFindingsRequest", + "SummarizeIntelligenceFindingsResponse", "UpdateAnywhereCacheMetadata", "UpdateAnywhereCacheRequest", "UpdateFolderIntelligenceConfigRequest", "UpdateOrganizationIntelligenceConfigRequest", "UpdateProjectIntelligenceConfigRequest", + "FindingCategory", + "FindingSeverity", + "FindingType", ) diff --git a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/storage_control.py b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/storage_control.py index c0063192870c..51def0916783 100644 --- a/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/storage_control.py +++ b/packages/google-cloud-storage-control/google/cloud/storage_control_v2/types/storage_control.py @@ -20,11 +20,16 @@ import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( package="google.storage.control.v2", manifest={ + "FindingType", + "FindingCategory", + "FindingSeverity", "PendingRenameInfo", "Folder", "GetFolderRequest", @@ -63,10 +68,80 @@ "GetOrganizationIntelligenceConfigRequest", "GetFolderIntelligenceConfigRequest", "GetProjectIntelligenceConfigRequest", + "IntelligenceFinding", + "IntelligenceFindingRevision", + "GetIntelligenceFindingRequest", + "ListIntelligenceFindingsRequest", + "ListIntelligenceFindingsResponse", + "SummarizeIntelligenceFindingsRequest", + "SummarizeIntelligenceFindingsResponse", + "GetIntelligenceFindingRevisionRequest", + "ListIntelligenceFindingRevisionsRequest", + "ListIntelligenceFindingRevisionsResponse", + "FindingSummary", }, ) +class FindingType(proto.Enum): + r"""List the finding types. + + Values: + FINDING_TYPE_UNSPECIFIED (0): + Finding type is unspecified. + FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE (1): + Finding is about a spike in Class A/B + operations on Coldline or Archive Cloud Storage + objects. + FINDING_TYPE_THROTTLED_REQUEST_SPIKE (2): + Finding is about a spike in throttled + requests (429 errors) within a project. + FINDING_TYPE_CROSS_REGION_EGRESS_SPIKE (3): + Finding is about a spike in cross region + egress in Cloud Storage. + FINDING_TYPE_STORAGE_GROWTH_ABOVE_TREND (4): + Finding is about growth in storage above the + expected trend. + """ + + FINDING_TYPE_UNSPECIFIED = 0 + FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE = 1 + FINDING_TYPE_THROTTLED_REQUEST_SPIKE = 2 + FINDING_TYPE_CROSS_REGION_EGRESS_SPIKE = 3 + FINDING_TYPE_STORAGE_GROWTH_ABOVE_TREND = 4 + + +class FindingCategory(proto.Enum): + r"""List of categories a finding falls under. + + Values: + FINDING_CATEGORY_UNSPECIFIED (0): + Category is unspecified. + FINDING_CATEGORY_DATA_MANAGEMENT (1): + Category is 'Data Management'. + FINDING_CATEGORY_PERFORMANCE (2): + Category is 'Performance'. + """ + + FINDING_CATEGORY_UNSPECIFIED = 0 + FINDING_CATEGORY_DATA_MANAGEMENT = 1 + FINDING_CATEGORY_PERFORMANCE = 2 + + +class FindingSeverity(proto.Enum): + r"""Severity of the ``IntelligenceFinding`` resource. + + Values: + FINDING_SEVERITY_UNSPECIFIED (0): + Severity is unspecified. + FINDING_SEVERITY_CRITICAL (1): + Severity is critical. + """ + + FINDING_SEVERITY_UNSPECIFIED = 0 + FINDING_SEVERITY_CRITICAL = 1 + + class PendingRenameInfo(proto.Message): r"""Contains information about a pending rename operation. @@ -1846,4 +1921,1086 @@ class GetProjectIntelligenceConfigRequest(proto.Message): ) +class IntelligenceFinding(proto.Message): + r"""The ``IntelligenceFinding`` resource that represents a security, + performance, or cost-related finding about a project or bucket. + + 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): + Identifier. The resource name of ``IntelligenceFinding``. + Format: + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + description (str): + Output only. A short description about the + finding. + type_ (google.cloud.storage_control_v2.types.FindingType): + Output only. Type of this finding. + category (google.cloud.storage_control_v2.types.FindingCategory): + Output only. Category of this finding. + severity (google.cloud.storage_control_v2.types.FindingSeverity): + Output only. Severity of the finding. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the finding + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the finding + was last updated. + target_resource (str): + Output only. The fully qualified resource name of the + resource that this ``IntelligenceFinding`` applies to. eg: + + - ``storage.googleapis.com/projects/_/buckets/b1`` + - ``cloudresourecemanager.googleapis.com/projects/p1`` + associated_resources (MutableSequence[str]): + Output only. Contains GCP resource names that are relevant + to this ``IntelligenceFinding``. The ``target_resource`` is + also added as part of ``associated_resources``. eg: + + - ``storage.googleapis.com/projects/_/buckets/b1`` + - ``cloudresourecemanager.googleapis.com/projects/p1`` + observation_period (google.type.interval_pb2.Interval): + Output only. The time interval during which the underlying + data was used to generate this ``IntelligenceFinding``. + coldline_and_archival_storage_operations_spike (google.cloud.storage_control_v2.types.IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike): + Output only. ``IntelligenceFinding`` about a spike in Class + A/B operations on Coldline or Archive Cloud Storage objects. + + This field is a member of `oneof`_ ``intelligence_finding_details``. + throttled_requests_spike (google.cloud.storage_control_v2.types.IntelligenceFinding.ThrottledRequestSpike): + Output only. ``IntelligenceFinding`` about a spike in + throttled requests (429 errors) within a project. + + This field is a member of `oneof`_ ``intelligence_finding_details``. + cross_region_egress_spike (google.cloud.storage_control_v2.types.IntelligenceFinding.CrossRegionEgressSpike): + Output only. ``IntelligenceFinding`` about a spike in + cross-region egress. + + This field is a member of `oneof`_ ``intelligence_finding_details``. + storage_growth_above_trend (google.cloud.storage_control_v2.types.IntelligenceFinding.StorageGrowthAboveTrend): + Output only. ``IntelligenceFinding`` about growth in storage + above the expected trend. + + This field is a member of `oneof`_ ``intelligence_finding_details``. + """ + + class ColdlineAndArchivalStorageOperationsSpike(proto.Message): + r"""Represents a finding about a spike in Class A/B operations on + Coldline or Archive Cloud Storage objects. This corresponds to the + ``COLD_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE`` finding type. + + Attributes: + percentage_increase (float): + Output only. The percentage increase in + operations across the project. + total_operations_count (int): + Output only. The total count of operations + across the project. + top_buckets (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution]): + Output only. A list of the top buckets + driving the increase in operations. + """ + + class BucketContribution(proto.Message): + r"""Represents the operation spike details for a bucket. + + 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: + bucket (str): + Output only. The name of the bucket. + percentage_increase (float): + Output only. The percentage increase in + operations for the bucket. + total_operations_count (int): + Output only. The total count of operations + for the bucket. + contribution (google.cloud.storage_control_v2.types.IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution): + Output only. The details about the + contribution of the bucket. + + This field is a member of `oneof`_ ``details``. + error (google.rpc.status_pb2.Status): + Output only. The error related to accessing + the details about the contribution of the + bucket. + + This field is a member of `oneof`_ ``details``. + """ + + class Contribution(proto.Message): + r"""Represents the contribution of the bucket towards the + ``IntelligenceFinding``. + + Attributes: + top_prefixes (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution.PrefixContribution]): + Output only. A list of the top object + prefixes driving the increase in operations. + """ + + class PrefixContribution(proto.Message): + r"""Represents the operation spike details for an object prefix. + + Attributes: + prefix (str): + Output only. The object prefix. Format: ``a/b/c``, 'a/b/d', + etc. + percentage_increase (float): + Output only. The percentage increase in + operations for the object prefix. + total_operations_count (int): + Output only. The total count of operations + for the object prefix. + """ + + prefix: str = proto.Field( + proto.STRING, + number=1, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=2, + ) + total_operations_count: int = proto.Field( + proto.INT64, + number=3, + ) + + top_prefixes: MutableSequence[ + "IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution.PrefixContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution.PrefixContribution", + ) + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=2, + ) + total_operations_count: int = proto.Field( + proto.INT64, + number=3, + ) + contribution: "IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution" = proto.Field( + proto.MESSAGE, + number=4, + oneof="details", + message="IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution.Contribution", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + oneof="details", + message=status_pb2.Status, + ) + + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=1, + ) + total_operations_count: int = proto.Field( + proto.INT64, + number=2, + ) + top_buckets: MutableSequence[ + "IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="IntelligenceFinding.ColdlineAndArchivalStorageOperationsSpike.BucketContribution", + ) + + class CrossRegionEgressSpike(proto.Message): + r"""Represents a finding about a spike in cross-region egress from Cloud + Storage. This corresponds to the ``CROSS_REGION_EGRESS_SPIKE`` + finding type. + + Attributes: + total_egress_bytes (int): + Output only. The total cross-region egress + volume in bytes across the project. + percentage_increase (float): + Output only. The percentage increase in + cross-region egress across the project. + top_buckets (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.CrossRegionEgressSpike.BucketContribution]): + Output only. A list of top buckets driving + the increase in cross-region egress. + """ + + class BucketContribution(proto.Message): + r"""Represents the cross-region egress spike details for a + bucket. + + 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: + bucket (str): + Output only. The name of the bucket. + total_egress_bytes (int): + Output only. The total cross-region egress + volume in bytes for the bucket. + percentage_increase (float): + Output only. The percentage increase in + cross-region egress for the bucket. + contribution (google.cloud.storage_control_v2.types.IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution): + Output only. The details about the + contribution of the bucket. + + This field is a member of `oneof`_ ``details``. + error (google.rpc.status_pb2.Status): + Output only. The error related to accessing + the details about the contribution of the + bucket. + + This field is a member of `oneof`_ ``details``. + """ + + class Contribution(proto.Message): + r"""Represents the contribution of the bucket towards the + ``IntelligenceFinding``. + + Attributes: + top_prefixes (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution.PrefixContribution]): + Output only. A list of the top object + prefixes driving the increase in cross-region + egress. + """ + + class PrefixContribution(proto.Message): + r"""Represents the cross-region egress spike details for an + object prefix. + + Attributes: + prefix (str): + Output only. The object prefix. Format: ``a/b/c``, 'a/b/d', + etc. + total_egress_bytes (int): + Output only. The total cross-region egress + volume in bytes from the object prefix. + percentage_increase (float): + Output only. The percentage increase in + cross-region egress for the object prefix. + """ + + prefix: str = proto.Field( + proto.STRING, + number=1, + ) + total_egress_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + top_prefixes: MutableSequence[ + "IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution.PrefixContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution.PrefixContribution", + ) + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + total_egress_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=3, + ) + contribution: "IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution" = proto.Field( + proto.MESSAGE, + number=4, + oneof="details", + message="IntelligenceFinding.CrossRegionEgressSpike.BucketContribution.Contribution", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + oneof="details", + message=status_pb2.Status, + ) + + total_egress_bytes: int = proto.Field( + proto.INT64, + number=1, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_buckets: MutableSequence[ + "IntelligenceFinding.CrossRegionEgressSpike.BucketContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="IntelligenceFinding.CrossRegionEgressSpike.BucketContribution", + ) + + class ThrottledRequestSpike(proto.Message): + r"""Represents a finding about a spike in throttled requests (429 + errors) within a project. This corresponds to the + ``THROTTLED_REQUEST_SPIKE`` finding type. + + Attributes: + throttled_requests (int): + Output only. The count of throttled requests + across the project. + percentage_increase (float): + Output only. The percentage increase in + throttled requests across the project. + top_buckets (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.ThrottledRequestSpike.BucketContribution]): + Output only. A list of top buckets driving + the increase in throttled requests. + """ + + class BucketContribution(proto.Message): + r"""Represents the throttled requests details for a bucket. + + 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: + bucket (str): + Output only. The name of the bucket. + throttled_requests (int): + Output only. The count of throttled requests + for the bucket. + percentage_increase (float): + Output only. The percentage increase in + throttled requests for the bucket. + contribution (google.cloud.storage_control_v2.types.IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution): + Output only. The details about the + contribution of the bucket. + + This field is a member of `oneof`_ ``details``. + error (google.rpc.status_pb2.Status): + Output only. The error related to accessing + the details about the contribution of the + bucket. + + This field is a member of `oneof`_ ``details``. + """ + + class Contribution(proto.Message): + r"""Represents the contribution of the bucket towards the + ``IntelligenceFinding``. + + Attributes: + top_prefixes (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution.PrefixContribution]): + Output only. A list of top object prefixes + driving the increase in throttled requests. + """ + + class PrefixContribution(proto.Message): + r"""Represents throttled requests details for an object prefix. + + Attributes: + prefix (str): + Output only. The object prefix. Format: ``a/b/c``, 'a/b/d', + etc. + throttled_requests (int): + Output only. The count of throttled requests + for the object prefix. + percentage_increase (float): + Output only. The percentage increase in + throttled requests for the object prefix. + """ + + prefix: str = proto.Field( + proto.STRING, + number=1, + ) + throttled_requests: int = proto.Field( + proto.INT64, + number=2, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + top_prefixes: MutableSequence[ + "IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution.PrefixContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution.PrefixContribution", + ) + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + throttled_requests: int = proto.Field( + proto.INT64, + number=2, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=3, + ) + contribution: "IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution" = proto.Field( + proto.MESSAGE, + number=4, + oneof="details", + message="IntelligenceFinding.ThrottledRequestSpike.BucketContribution.Contribution", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + oneof="details", + message=status_pb2.Status, + ) + + throttled_requests: int = proto.Field( + proto.INT64, + number=1, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_buckets: MutableSequence[ + "IntelligenceFinding.ThrottledRequestSpike.BucketContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="IntelligenceFinding.ThrottledRequestSpike.BucketContribution", + ) + + class StorageGrowthAboveTrend(proto.Message): + r"""Represents a finding about a storage growth above the expected + trend. This corresponds to the ``STORAGE_GROWTH_ABOVE_TREND`` + finding type. + + Attributes: + total_storage_growth_bytes (int): + Output only. The total storage growth in + bytes. + percentage_increase (float): + Output only. The percentage increase in + storage growth. + top_buckets (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding.StorageGrowthAboveTrend.BucketContribution]): + Output only. A list of top buckets driving + the increase in storage growth. + """ + + class BucketContribution(proto.Message): + r"""Represents the storage growth details for a bucket. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + bucket (str): + Output only. The name of the bucket. + total_storage_growth_bytes (int): + Output only. The total storage growth in + bytes for the bucket. + percentage_increase (float): + Output only. The percentage increase in + storage growth for the bucket. + error (google.rpc.status_pb2.Status): + Output only. The error related to accessing + the details about the contribution of the + bucket. + + This field is a member of `oneof`_ ``details``. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + total_storage_growth_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=3, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + oneof="details", + message=status_pb2.Status, + ) + + total_storage_growth_bytes: int = proto.Field( + proto.INT64, + number=1, + ) + percentage_increase: float = proto.Field( + proto.DOUBLE, + number=2, + ) + top_buckets: MutableSequence[ + "IntelligenceFinding.StorageGrowthAboveTrend.BucketContribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="IntelligenceFinding.StorageGrowthAboveTrend.BucketContribution", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + type_: "FindingType" = proto.Field( + proto.ENUM, + number=3, + enum="FindingType", + ) + category: "FindingCategory" = proto.Field( + proto.ENUM, + number=4, + enum="FindingCategory", + ) + severity: "FindingSeverity" = proto.Field( + proto.ENUM, + number=5, + enum="FindingSeverity", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + target_resource: str = proto.Field( + proto.STRING, + number=8, + ) + associated_resources: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + observation_period: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=10, + message=interval_pb2.Interval, + ) + coldline_and_archival_storage_operations_spike: ColdlineAndArchivalStorageOperationsSpike = proto.Field( + proto.MESSAGE, + number=11, + oneof="intelligence_finding_details", + message=ColdlineAndArchivalStorageOperationsSpike, + ) + throttled_requests_spike: ThrottledRequestSpike = proto.Field( + proto.MESSAGE, + number=12, + oneof="intelligence_finding_details", + message=ThrottledRequestSpike, + ) + cross_region_egress_spike: CrossRegionEgressSpike = proto.Field( + proto.MESSAGE, + number=13, + oneof="intelligence_finding_details", + message=CrossRegionEgressSpike, + ) + storage_growth_above_trend: StorageGrowthAboveTrend = proto.Field( + proto.MESSAGE, + number=14, + oneof="intelligence_finding_details", + message=StorageGrowthAboveTrend, + ) + + +class IntelligenceFindingRevision(proto.Message): + r"""An ``IntelligenceFindingRevision`` represents a specific revision of + an ``IntelligenceFinding`` resource. + + Attributes: + name (str): + Identifier. The resource name of + ``IntelligenceFindingRevision``. Format: + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}`` + snapshot (google.cloud.storage_control_v2.types.IntelligenceFinding): + Output only. The snapshot of the ``IntelligenceFinding`` at + the time the revision was created. This field contains the + full finding details as they existed for the revision. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the revision + was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot: "IntelligenceFinding" = proto.Field( + proto.MESSAGE, + number=2, + message="IntelligenceFinding", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GetIntelligenceFindingRequest(proto.Message): + r"""Request message to get the ``IntelligenceFinding`` resource + associated with a project. + + Attributes: + name (str): + Required. The name of the ``IntelligenceFinding`` resource. + + Format: + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListIntelligenceFindingsRequest(proto.Message): + r"""Request message to list ``IntelligenceFinding`` resources associated + with a project. + + Attributes: + parent (str): + Required. The parent of the ``IntelligenceFinding`` + resource. + + Format: ``projects/{project}/locations/{location}`` + filter (str): + Optional. The filter expression to be applied. Supports + filtering by ``type`` and ``associated_resources``. + page_size (int): + Optional. The maximum number of ``IntelligenceFinding`` + resources to return. + + The maximum value is ``100``; values above ``100`` will be + coerced to ``100``. The default value is ``100``. + page_token (str): + Optional. A page token, received from a previous + ``ListIntelligenceFindings`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListIntelligenceFindings`` must match the call that + provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIntelligenceFindingsResponse(proto.Message): + r"""Response message to list the ``IntelligenceFinding`` resources + associated with a project. + + Attributes: + intelligence_findings (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFinding]): + The ``IntelligenceFinding`` resources from the specified + project. + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in the ``page_token`` field in the subsequent call. + """ + + @property + def raw_page(self): + return self + + intelligence_findings: MutableSequence["IntelligenceFinding"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IntelligenceFinding", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SummarizeIntelligenceFindingsRequest(proto.Message): + r"""Request message to summarize the intelligence findings for + the specified scope(org, folder or project). + + Attributes: + parent (str): + Required. The scope to summarize the findings for. Format: + + - ``organizations/{organization}/locations/{location}`` + - ``folders/{folder}/locations/{location}`` + - ``projects/{project}/locations/{location}`` + resource_scope (google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsRequest.ResourceScope): + Optional. Determines the granularity of the findings when + the ``parent`` is an organization or folder. + + - ``PARENT`` (or not set): A single summary is returned for + each insight type, aggregated across the entire ``parent`` + scope. + - ``PROJECT``: A separate summary is returned for each + insight type for every project within the ``parent`` + scope. + + The only supported values are ``PARENT`` and ``PROJECT``. If + no value is specified, the API behaviour defaults to the + ``PARENT``. + filter (str): + Optional. The filter expression, following + AIP-160. Supports filtering by FindingType. + page_size (int): + Optional. The maximum number of findings to return. + + The maximum value is ``100``; values above ``100`` will be + coerced to ``100``. The default value is ``100``. + page_token (str): + Optional. A page token, received from a previous + ``SummarizeIntelligenceFindings`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``SummarizeIntelligenceFindings`` must match the call that + provided the page token. + """ + + class ResourceScope(proto.Enum): + r"""The list of resource scopes. + + Values: + RESOURCE_SCOPE_UNSPECIFIED (0): + The default behavior. Falls back to PARENT + behaviour + PARENT (1): + Summaries are aggregated at the level of the ``parent`` + resource. + PROJECT (2): + Summaries are broken down by each project within the + ``parent`` scope. + """ + + RESOURCE_SCOPE_UNSPECIFIED = 0 + PARENT = 1 + PROJECT = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_scope: ResourceScope = proto.Field( + proto.ENUM, + number=2, + enum=ResourceScope, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class SummarizeIntelligenceFindingsResponse(proto.Message): + r"""Response message to summarize the intelligence findings for a + specified scope(org, folder or project). + + Attributes: + finding_summaries (MutableSequence[google.cloud.storage_control_v2.types.FindingSummary]): + The list of ``FindingSummary`` summaries. + next_page_token (str): + A token to retrieve the next page of results. Pass this + value in the ``page_token`` field in the subsequent call to + ``SummarizeIntelligenceFindings`` to retrieve the next page + of results. + """ + + @property + def raw_page(self): + return self + + finding_summaries: MutableSequence["FindingSummary"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="FindingSummary", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetIntelligenceFindingRevisionRequest(proto.Message): + r"""Request message to get the ``IntelligenceFindingRevision`` resource + associated with a project. + + Attributes: + name (str): + Required. The name of the ``IntelligenceFindingRevision`` + resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListIntelligenceFindingRevisionsRequest(proto.Message): + r"""Request message to list ``IntelligenceFindingRevision`` resources + associated with a project. + + Attributes: + parent (str): + Required. The parent of the ``IntelligenceFindingRevision`` + resource. + + Format: + ------- + + ``projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}`` + page_size (int): + Optional. The maximum number of + ``IntelligenceFindingRevision`` resources to return. + + The maximum value is ``100``; values above ``100`` will be + coerced to ``100``. The default value is ``100``. + page_token (str): + Optional. A page token, received from a previous + ``ListIntelligenceFindingRevisions`` call. Provide this to + retrieve the subsequent page. + """ + + 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 ListIntelligenceFindingRevisionsResponse(proto.Message): + r"""Response message to list ``IntelligenceFindingRevision`` resources + associated with a project. + + Attributes: + intelligence_finding_revisions (MutableSequence[google.cloud.storage_control_v2.types.IntelligenceFindingRevision]): + The ``IntelligenceFindingRevision`` resources from the + specified project. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. + """ + + @property + def raw_page(self): + return self + + intelligence_finding_revisions: MutableSequence["IntelligenceFindingRevision"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="IntelligenceFindingRevision", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class FindingSummary(proto.Message): + r"""A summary of findings generated for an organization, a + folder, or a project. + + Attributes: + type_ (google.cloud.storage_control_v2.types.FindingType): + Output only. The type of the finding. + category (google.cloud.storage_control_v2.types.FindingCategory): + Output only. The category of finding. + target_resource (str): + Output only. The fully qualified Cloud resource name for + which this summary was generated. eg: + ``//cloudresourcemanager.googleapis.com/projects/p1`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + earliest finding that this summary is based on. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time of the most recent + update among all the findings that this summary + is based on. + severity (google.cloud.storage_control_v2.types.FindingSeverity): + Severity of the finding. + summary_details (MutableSequence[google.cloud.storage_control_v2.types.FindingSummary.SummaryDetails]): + Output only. List of ``SummaryDetails``. + """ + + class SummaryDetails(proto.Message): + r"""Details about the ``FindingSummary`` resource. + + 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: + count (int): + The count of impacted resources. + + This field is a member of `oneof`_ ``magnitude``. + percentage (float): + The percentage of impacted resources. + + This field is a member of `oneof`_ ``magnitude``. + resource_type (google.cloud.storage_control_v2.types.FindingSummary.SummaryDetails.ResourceType): + Output only. The type of Cloud resource this + summary detail applies to. + description (str): + Output only. A short description about the + FindingSummary + """ + + class ResourceType(proto.Enum): + r"""The list of resource types. + + Values: + RESOURCE_TYPE_UNSPECIFIED (0): + Resource type is unspecified. + PROJECT (1): + Resource type is project. + BUCKET (2): + Resource type is bucket. + """ + + RESOURCE_TYPE_UNSPECIFIED = 0 + PROJECT = 1 + BUCKET = 2 + + count: int = proto.Field( + proto.INT64, + number=1, + oneof="magnitude", + ) + percentage: float = proto.Field( + proto.FLOAT, + number=2, + oneof="magnitude", + ) + resource_type: "FindingSummary.SummaryDetails.ResourceType" = proto.Field( + proto.ENUM, + number=3, + enum="FindingSummary.SummaryDetails.ResourceType", + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + + type_: "FindingType" = proto.Field( + proto.ENUM, + number=1, + enum="FindingType", + ) + category: "FindingCategory" = proto.Field( + proto.ENUM, + number=2, + enum="FindingCategory", + ) + target_resource: str = proto.Field( + proto.STRING, + number=4, + ) + 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, + ) + severity: "FindingSeverity" = proto.Field( + proto.ENUM, + number=7, + enum="FindingSeverity", + ) + summary_details: MutableSequence[SummaryDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=SummaryDetails, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-storage-control/samples/generated_samples/snippet_metadata_google.storage.control.v2.json b/packages/google-cloud-storage-control/samples/generated_samples/snippet_metadata_google.storage.control.v2.json index 428dc1ad3e10..be03a8c979f3 100644 --- a/packages/google-cloud-storage-control/samples/generated_samples/snippet_metadata_google.storage.control.v2.json +++ b/packages/google-cloud-storage-control/samples/generated_samples/snippet_metadata_google.storage.control.v2.json @@ -1818,19 +1818,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_managed_folder", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_intelligence_finding_revision", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetManagedFolder", + "fullName": "google.storage.control.v2.StorageControl.GetIntelligenceFindingRevision", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetManagedFolder" + "shortName": "GetIntelligenceFindingRevision" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetManagedFolderRequest" + "type": "google.cloud.storage_control_v2.types.GetIntelligenceFindingRevisionRequest" }, { "name": "name", @@ -1849,14 +1849,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.ManagedFolder", - "shortName": "get_managed_folder" + "resultType": "google.cloud.storage_control_v2.types.IntelligenceFindingRevision", + "shortName": "get_intelligence_finding_revision" }, - "description": "Sample for GetManagedFolder", - "file": "storage_v2_generated_storage_control_get_managed_folder_async.py", + "description": "Sample for GetIntelligenceFindingRevision", + "file": "storage_v2_generated_storage_control_get_intelligence_finding_revision_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetManagedFolder_async", + "regionTag": "storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_async", "segments": [ { "end": 51, @@ -1889,7 +1889,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_managed_folder_async.py" + "title": "storage_v2_generated_storage_control_get_intelligence_finding_revision_async.py" }, { "canonical": true, @@ -1898,19 +1898,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_managed_folder", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_intelligence_finding_revision", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetManagedFolder", + "fullName": "google.storage.control.v2.StorageControl.GetIntelligenceFindingRevision", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetManagedFolder" + "shortName": "GetIntelligenceFindingRevision" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetManagedFolderRequest" + "type": "google.cloud.storage_control_v2.types.GetIntelligenceFindingRevisionRequest" }, { "name": "name", @@ -1929,14 +1929,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.ManagedFolder", - "shortName": "get_managed_folder" + "resultType": "google.cloud.storage_control_v2.types.IntelligenceFindingRevision", + "shortName": "get_intelligence_finding_revision" }, - "description": "Sample for GetManagedFolder", - "file": "storage_v2_generated_storage_control_get_managed_folder_sync.py", + "description": "Sample for GetIntelligenceFindingRevision", + "file": "storage_v2_generated_storage_control_get_intelligence_finding_revision_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetManagedFolder_sync", + "regionTag": "storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_sync", "segments": [ { "end": 51, @@ -1969,7 +1969,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_managed_folder_sync.py" + "title": "storage_v2_generated_storage_control_get_intelligence_finding_revision_sync.py" }, { "canonical": true, @@ -1979,19 +1979,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_organization_intelligence_config", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_intelligence_finding", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetOrganizationIntelligenceConfig", + "fullName": "google.storage.control.v2.StorageControl.GetIntelligenceFinding", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetOrganizationIntelligenceConfig" + "shortName": "GetIntelligenceFinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest" + "type": "google.cloud.storage_control_v2.types.GetIntelligenceFindingRequest" }, { "name": "name", @@ -2010,14 +2010,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.IntelligenceConfig", - "shortName": "get_organization_intelligence_config" + "resultType": "google.cloud.storage_control_v2.types.IntelligenceFinding", + "shortName": "get_intelligence_finding" }, - "description": "Sample for GetOrganizationIntelligenceConfig", - "file": "storage_v2_generated_storage_control_get_organization_intelligence_config_async.py", + "description": "Sample for GetIntelligenceFinding", + "file": "storage_v2_generated_storage_control_get_intelligence_finding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetOrganizationIntelligenceConfig_async", + "regionTag": "storage_v2_generated_StorageControl_GetIntelligenceFinding_async", "segments": [ { "end": 51, @@ -2050,7 +2050,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_organization_intelligence_config_async.py" + "title": "storage_v2_generated_storage_control_get_intelligence_finding_async.py" }, { "canonical": true, @@ -2059,19 +2059,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_organization_intelligence_config", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_intelligence_finding", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetOrganizationIntelligenceConfig", + "fullName": "google.storage.control.v2.StorageControl.GetIntelligenceFinding", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetOrganizationIntelligenceConfig" + "shortName": "GetIntelligenceFinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest" + "type": "google.cloud.storage_control_v2.types.GetIntelligenceFindingRequest" }, { "name": "name", @@ -2090,14 +2090,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.IntelligenceConfig", - "shortName": "get_organization_intelligence_config" + "resultType": "google.cloud.storage_control_v2.types.IntelligenceFinding", + "shortName": "get_intelligence_finding" }, - "description": "Sample for GetOrganizationIntelligenceConfig", - "file": "storage_v2_generated_storage_control_get_organization_intelligence_config_sync.py", + "description": "Sample for GetIntelligenceFinding", + "file": "storage_v2_generated_storage_control_get_intelligence_finding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetOrganizationIntelligenceConfig_sync", + "regionTag": "storage_v2_generated_StorageControl_GetIntelligenceFinding_sync", "segments": [ { "end": 51, @@ -2130,7 +2130,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_organization_intelligence_config_sync.py" + "title": "storage_v2_generated_storage_control_get_intelligence_finding_sync.py" }, { "canonical": true, @@ -2140,19 +2140,180 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_project_intelligence_config", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_managed_folder", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetProjectIntelligenceConfig", + "fullName": "google.storage.control.v2.StorageControl.GetManagedFolder", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetProjectIntelligenceConfig" + "shortName": "GetManagedFolder" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest" + "type": "google.cloud.storage_control_v2.types.GetManagedFolderRequest" + }, + { + "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.storage_control_v2.types.ManagedFolder", + "shortName": "get_managed_folder" + }, + "description": "Sample for GetManagedFolder", + "file": "storage_v2_generated_storage_control_get_managed_folder_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetManagedFolder_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": "storage_v2_generated_storage_control_get_managed_folder_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_managed_folder", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetManagedFolder", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetManagedFolder" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetManagedFolderRequest" + }, + { + "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.storage_control_v2.types.ManagedFolder", + "shortName": "get_managed_folder" + }, + "description": "Sample for GetManagedFolder", + "file": "storage_v2_generated_storage_control_get_managed_folder_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetManagedFolder_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": "storage_v2_generated_storage_control_get_managed_folder_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_organization_intelligence_config", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetOrganizationIntelligenceConfig", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetOrganizationIntelligenceConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest" }, { "name": "name", @@ -2172,13 +2333,13 @@ } ], "resultType": "google.cloud.storage_control_v2.types.IntelligenceConfig", - "shortName": "get_project_intelligence_config" + "shortName": "get_organization_intelligence_config" }, - "description": "Sample for GetProjectIntelligenceConfig", - "file": "storage_v2_generated_storage_control_get_project_intelligence_config_async.py", + "description": "Sample for GetOrganizationIntelligenceConfig", + "file": "storage_v2_generated_storage_control_get_organization_intelligence_config_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetProjectIntelligenceConfig_async", + "regionTag": "storage_v2_generated_StorageControl_GetOrganizationIntelligenceConfig_async", "segments": [ { "end": 51, @@ -2211,7 +2372,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_project_intelligence_config_async.py" + "title": "storage_v2_generated_storage_control_get_organization_intelligence_config_async.py" }, { "canonical": true, @@ -2220,19 +2381,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_project_intelligence_config", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_organization_intelligence_config", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetProjectIntelligenceConfig", + "fullName": "google.storage.control.v2.StorageControl.GetOrganizationIntelligenceConfig", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetProjectIntelligenceConfig" + "shortName": "GetOrganizationIntelligenceConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest" + "type": "google.cloud.storage_control_v2.types.GetOrganizationIntelligenceConfigRequest" }, { "name": "name", @@ -2251,22 +2412,505 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.IntelligenceConfig", - "shortName": "get_project_intelligence_config" + "resultType": "google.cloud.storage_control_v2.types.IntelligenceConfig", + "shortName": "get_organization_intelligence_config" + }, + "description": "Sample for GetOrganizationIntelligenceConfig", + "file": "storage_v2_generated_storage_control_get_organization_intelligence_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetOrganizationIntelligenceConfig_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": "storage_v2_generated_storage_control_get_organization_intelligence_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_project_intelligence_config", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetProjectIntelligenceConfig", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetProjectIntelligenceConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest" + }, + { + "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.storage_control_v2.types.IntelligenceConfig", + "shortName": "get_project_intelligence_config" + }, + "description": "Sample for GetProjectIntelligenceConfig", + "file": "storage_v2_generated_storage_control_get_project_intelligence_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetProjectIntelligenceConfig_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": "storage_v2_generated_storage_control_get_project_intelligence_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_project_intelligence_config", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetProjectIntelligenceConfig", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetProjectIntelligenceConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetProjectIntelligenceConfigRequest" + }, + { + "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.storage_control_v2.types.IntelligenceConfig", + "shortName": "get_project_intelligence_config" + }, + "description": "Sample for GetProjectIntelligenceConfig", + "file": "storage_v2_generated_storage_control_get_project_intelligence_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetProjectIntelligenceConfig_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": "storage_v2_generated_storage_control_get_project_intelligence_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_storage_layout", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetStorageLayout", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetStorageLayout" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetStorageLayoutRequest" + }, + { + "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.storage_control_v2.types.StorageLayout", + "shortName": "get_storage_layout" + }, + "description": "Sample for GetStorageLayout", + "file": "storage_v2_generated_storage_control_get_storage_layout_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetStorageLayout_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": "storage_v2_generated_storage_control_get_storage_layout_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_storage_layout", + "method": { + "fullName": "google.storage.control.v2.StorageControl.GetStorageLayout", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "GetStorageLayout" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.GetStorageLayoutRequest" + }, + { + "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.storage_control_v2.types.StorageLayout", + "shortName": "get_storage_layout" + }, + "description": "Sample for GetStorageLayout", + "file": "storage_v2_generated_storage_control_get_storage_layout_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_GetStorageLayout_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": "storage_v2_generated_storage_control_get_storage_layout_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_anywhere_caches", + "method": { + "fullName": "google.storage.control.v2.StorageControl.ListAnywhereCaches", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "ListAnywhereCaches" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.ListAnywhereCachesRequest" + }, + { + "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.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesAsyncPager", + "shortName": "list_anywhere_caches" + }, + "description": "Sample for ListAnywhereCaches", + "file": "storage_v2_generated_storage_control_list_anywhere_caches_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_ListAnywhereCaches_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": "storage_v2_generated_storage_control_list_anywhere_caches_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_anywhere_caches", + "method": { + "fullName": "google.storage.control.v2.StorageControl.ListAnywhereCaches", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "ListAnywhereCaches" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.ListAnywhereCachesRequest" + }, + { + "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.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesPager", + "shortName": "list_anywhere_caches" }, - "description": "Sample for GetProjectIntelligenceConfig", - "file": "storage_v2_generated_storage_control_get_project_intelligence_config_sync.py", + "description": "Sample for ListAnywhereCaches", + "file": "storage_v2_generated_storage_control_list_anywhere_caches_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetProjectIntelligenceConfig_sync", + "regionTag": "storage_v2_generated_StorageControl_ListAnywhereCaches_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2286,12 +2930,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_project_intelligence_config_sync.py" + "title": "storage_v2_generated_storage_control_list_anywhere_caches_sync.py" }, { "canonical": true, @@ -2301,22 +2945,22 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.get_storage_layout", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_folders", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetStorageLayout", + "fullName": "google.storage.control.v2.StorageControl.ListFolders", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetStorageLayout" + "shortName": "ListFolders" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetStorageLayoutRequest" + "type": "google.cloud.storage_control_v2.types.ListFoldersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2332,22 +2976,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.StorageLayout", - "shortName": "get_storage_layout" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListFoldersAsyncPager", + "shortName": "list_folders" }, - "description": "Sample for GetStorageLayout", - "file": "storage_v2_generated_storage_control_get_storage_layout_async.py", + "description": "Sample for ListFolders", + "file": "storage_v2_generated_storage_control_list_folders_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetStorageLayout_async", + "regionTag": "storage_v2_generated_StorageControl_ListFolders_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2367,12 +3011,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_storage_layout_async.py" + "title": "storage_v2_generated_storage_control_list_folders_async.py" }, { "canonical": true, @@ -2381,22 +3025,22 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.get_storage_layout", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_folders", "method": { - "fullName": "google.storage.control.v2.StorageControl.GetStorageLayout", + "fullName": "google.storage.control.v2.StorageControl.ListFolders", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "GetStorageLayout" + "shortName": "ListFolders" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.GetStorageLayoutRequest" + "type": "google.cloud.storage_control_v2.types.ListFoldersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2412,22 +3056,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.types.StorageLayout", - "shortName": "get_storage_layout" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListFoldersPager", + "shortName": "list_folders" }, - "description": "Sample for GetStorageLayout", - "file": "storage_v2_generated_storage_control_get_storage_layout_sync.py", + "description": "Sample for ListFolders", + "file": "storage_v2_generated_storage_control_list_folders_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_GetStorageLayout_sync", + "regionTag": "storage_v2_generated_StorageControl_ListFolders_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2447,12 +3091,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_get_storage_layout_sync.py" + "title": "storage_v2_generated_storage_control_list_folders_sync.py" }, { "canonical": true, @@ -2462,19 +3106,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_anywhere_caches", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_intelligence_finding_revisions", "method": { - "fullName": "google.storage.control.v2.StorageControl.ListAnywhereCaches", + "fullName": "google.storage.control.v2.StorageControl.ListIntelligenceFindingRevisions", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "ListAnywhereCaches" + "shortName": "ListIntelligenceFindingRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.ListAnywhereCachesRequest" + "type": "google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest" }, { "name": "parent", @@ -2493,14 +3137,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesAsyncPager", - "shortName": "list_anywhere_caches" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingRevisionsAsyncPager", + "shortName": "list_intelligence_finding_revisions" }, - "description": "Sample for ListAnywhereCaches", - "file": "storage_v2_generated_storage_control_list_anywhere_caches_async.py", + "description": "Sample for ListIntelligenceFindingRevisions", + "file": "storage_v2_generated_storage_control_list_intelligence_finding_revisions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_ListAnywhereCaches_async", + "regionTag": "storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_async", "segments": [ { "end": 52, @@ -2533,7 +3177,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_list_anywhere_caches_async.py" + "title": "storage_v2_generated_storage_control_list_intelligence_finding_revisions_async.py" }, { "canonical": true, @@ -2542,19 +3186,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_anywhere_caches", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_intelligence_finding_revisions", "method": { - "fullName": "google.storage.control.v2.StorageControl.ListAnywhereCaches", + "fullName": "google.storage.control.v2.StorageControl.ListIntelligenceFindingRevisions", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "ListAnywhereCaches" + "shortName": "ListIntelligenceFindingRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.ListAnywhereCachesRequest" + "type": "google.cloud.storage_control_v2.types.ListIntelligenceFindingRevisionsRequest" }, { "name": "parent", @@ -2573,14 +3217,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListAnywhereCachesPager", - "shortName": "list_anywhere_caches" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingRevisionsPager", + "shortName": "list_intelligence_finding_revisions" }, - "description": "Sample for ListAnywhereCaches", - "file": "storage_v2_generated_storage_control_list_anywhere_caches_sync.py", + "description": "Sample for ListIntelligenceFindingRevisions", + "file": "storage_v2_generated_storage_control_list_intelligence_finding_revisions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_ListAnywhereCaches_sync", + "regionTag": "storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_sync", "segments": [ { "end": 52, @@ -2613,7 +3257,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_list_anywhere_caches_sync.py" + "title": "storage_v2_generated_storage_control_list_intelligence_finding_revisions_sync.py" }, { "canonical": true, @@ -2623,19 +3267,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", "shortName": "StorageControlAsyncClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_folders", + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.list_intelligence_findings", "method": { - "fullName": "google.storage.control.v2.StorageControl.ListFolders", + "fullName": "google.storage.control.v2.StorageControl.ListIntelligenceFindings", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "ListFolders" + "shortName": "ListIntelligenceFindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.ListFoldersRequest" + "type": "google.cloud.storage_control_v2.types.ListIntelligenceFindingsRequest" }, { "name": "parent", @@ -2654,14 +3298,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListFoldersAsyncPager", - "shortName": "list_folders" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingsAsyncPager", + "shortName": "list_intelligence_findings" }, - "description": "Sample for ListFolders", - "file": "storage_v2_generated_storage_control_list_folders_async.py", + "description": "Sample for ListIntelligenceFindings", + "file": "storage_v2_generated_storage_control_list_intelligence_findings_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_ListFolders_async", + "regionTag": "storage_v2_generated_StorageControl_ListIntelligenceFindings_async", "segments": [ { "end": 52, @@ -2694,7 +3338,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_list_folders_async.py" + "title": "storage_v2_generated_storage_control_list_intelligence_findings_async.py" }, { "canonical": true, @@ -2703,19 +3347,19 @@ "fullName": "google.cloud.storage_control_v2.StorageControlClient", "shortName": "StorageControlClient" }, - "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_folders", + "fullName": "google.cloud.storage_control_v2.StorageControlClient.list_intelligence_findings", "method": { - "fullName": "google.storage.control.v2.StorageControl.ListFolders", + "fullName": "google.storage.control.v2.StorageControl.ListIntelligenceFindings", "service": { "fullName": "google.storage.control.v2.StorageControl", "shortName": "StorageControl" }, - "shortName": "ListFolders" + "shortName": "ListIntelligenceFindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.storage_control_v2.types.ListFoldersRequest" + "type": "google.cloud.storage_control_v2.types.ListIntelligenceFindingsRequest" }, { "name": "parent", @@ -2734,14 +3378,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListFoldersPager", - "shortName": "list_folders" + "resultType": "google.cloud.storage_control_v2.services.storage_control.pagers.ListIntelligenceFindingsPager", + "shortName": "list_intelligence_findings" }, - "description": "Sample for ListFolders", - "file": "storage_v2_generated_storage_control_list_folders_sync.py", + "description": "Sample for ListIntelligenceFindings", + "file": "storage_v2_generated_storage_control_list_intelligence_findings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "storage_v2_generated_StorageControl_ListFolders_sync", + "regionTag": "storage_v2_generated_StorageControl_ListIntelligenceFindings_sync", "segments": [ { "end": 52, @@ -2774,7 +3418,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "storage_v2_generated_storage_control_list_folders_sync.py" + "title": "storage_v2_generated_storage_control_list_intelligence_findings_sync.py" }, { "canonical": true, @@ -3589,6 +4233,167 @@ ], "title": "storage_v2_generated_storage_control_set_iam_policy_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.summarize_intelligence_findings", + "method": { + "fullName": "google.storage.control.v2.StorageControl.SummarizeIntelligenceFindings", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "SummarizeIntelligenceFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsRequest" + }, + { + "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.storage_control_v2.services.storage_control.pagers.SummarizeIntelligenceFindingsAsyncPager", + "shortName": "summarize_intelligence_findings" + }, + "description": "Sample for SummarizeIntelligenceFindings", + "file": "storage_v2_generated_storage_control_summarize_intelligence_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_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": "storage_v2_generated_storage_control_summarize_intelligence_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.summarize_intelligence_findings", + "method": { + "fullName": "google.storage.control.v2.StorageControl.SummarizeIntelligenceFindings", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "SummarizeIntelligenceFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.SummarizeIntelligenceFindingsRequest" + }, + { + "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.storage_control_v2.services.storage_control.pagers.SummarizeIntelligenceFindingsPager", + "shortName": "summarize_intelligence_findings" + }, + "description": "Sample for SummarizeIntelligenceFindings", + "file": "storage_v2_generated_storage_control_summarize_intelligence_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_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": "storage_v2_generated_storage_control_summarize_intelligence_findings_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_async.py new file mode 100644 index 000000000000..f5c72287cdc9 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIntelligenceFinding +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_GetIntelligenceFinding_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 storage_control_v2 + + +async def sample_get_intelligence_finding(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_intelligence_finding(request=request) + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_GetIntelligenceFinding_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_async.py new file mode 100644 index 000000000000..3cc91f993462 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIntelligenceFindingRevision +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_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 storage_control_v2 + + +async def sample_get_intelligence_finding_revision(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_intelligence_finding_revision(request=request) + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_sync.py new file mode 100644 index 000000000000..b1be35d7bc94 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_revision_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIntelligenceFindingRevision +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_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 storage_control_v2 + + +def sample_get_intelligence_finding_revision(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_intelligence_finding_revision(request=request) + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_GetIntelligenceFindingRevision_sync] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_sync.py new file mode 100644 index 000000000000..7d0621f04dcf --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_get_intelligence_finding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIntelligenceFinding +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_GetIntelligenceFinding_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 storage_control_v2 + + +def sample_get_intelligence_finding(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.GetIntelligenceFindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_intelligence_finding(request=request) + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_GetIntelligenceFinding_sync] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_async.py new file mode 100644 index 000000000000..d4ac7e425dee --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIntelligenceFindingRevisions +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_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 storage_control_v2 + + +async def sample_list_intelligence_finding_revisions(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_finding_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_sync.py new file mode 100644 index 000000000000..6777c5948618 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_finding_revisions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIntelligenceFindingRevisions +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_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 storage_control_v2 + + +def sample_list_intelligence_finding_revisions(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_finding_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_ListIntelligenceFindingRevisions_sync] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_async.py new file mode 100644 index 000000000000..b3aad7f171dd --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIntelligenceFindings +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_ListIntelligenceFindings_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 storage_control_v2 + + +async def sample_list_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_ListIntelligenceFindings_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_sync.py new file mode 100644 index 000000000000..f67681f9aefa --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_list_intelligence_findings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListIntelligenceFindings +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_ListIntelligenceFindings_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 storage_control_v2 + + +def sample_list_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.ListIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_intelligence_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_ListIntelligenceFindings_sync] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_async.py new file mode 100644 index 000000000000..c592ec52651c --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SummarizeIntelligenceFindings +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_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 storage_control_v2 + + +async def sample_summarize_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.summarize_intelligence_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_sync.py new file mode 100644 index 000000000000..62d835b30ab3 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_summarize_intelligence_findings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SummarizeIntelligenceFindings +# 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-storage-control + + +# [START storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_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 storage_control_v2 + + +def sample_summarize_intelligence_findings(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.summarize_intelligence_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END storage_v2_generated_StorageControl_SummarizeIntelligenceFindings_sync] diff --git a/packages/google-cloud-storage-control/tests/unit/gapic/storage_control_v2/test_storage_control.py b/packages/google-cloud-storage-control/tests/unit/gapic/storage_control_v2/test_storage_control.py index 146876b8f09c..c3bb6e2cceaa 100644 --- a/packages/google-cloud-storage-control/tests/unit/gapic/storage_control_v2/test_storage_control.py +++ b/packages/google-cloud-storage-control/tests/unit/gapic/storage_control_v2/test_storage_control.py @@ -49,6 +49,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.type.expr_pb2 as expr_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore from google.api_core import ( client_options, future, @@ -10480,193 +10481,102 @@ async def test_test_iam_permissions_flattened_error_async(): ) -def test_create_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.CreateFolderRequest() - with pytest.raises(RuntimeError): - client.create_folder(request) - - -def test_delete_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.DeleteFolderRequest() - with pytest.raises(RuntimeError): - client.delete_folder(request) - - -def test_get_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.GetFolderRequest() - with pytest.raises(RuntimeError): - client.get_folder(request) - - -def test_list_folders_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.ListFoldersRequest() - with pytest.raises(RuntimeError): - client.list_folders(request) - - -def test_rename_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.RenameFolderRequest() - with pytest.raises(RuntimeError): - client.rename_folder(request) - - -def test_delete_folder_recursive_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.DeleteFolderRecursiveRequest() - with pytest.raises(RuntimeError): - client.delete_folder_recursive(request) - - -def test_get_storage_layout_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.GetStorageLayoutRequest() - with pytest.raises(RuntimeError): - client.get_storage_layout(request) - - -def test_create_managed_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.CreateManagedFolderRequest() - with pytest.raises(RuntimeError): - client.create_managed_folder(request) - - -def test_delete_managed_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.DeleteManagedFolderRequest() - with pytest.raises(RuntimeError): - client.delete_managed_folder(request) - - -def test_get_managed_folder_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.GetManagedFolderRequest() - with pytest.raises(RuntimeError): - client.get_managed_folder(request) - - -def test_list_managed_folders_rest_no_http_options(): +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetIntelligenceFindingRequest(), + {}, + ], +) +def test_get_intelligence_finding(request_type, transport: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = storage_control.ListManagedFoldersRequest() - with pytest.raises(RuntimeError): - client.list_managed_folders(request) + # Everything is optional 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 -def test_create_anywhere_cache_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.CreateAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.create_anywhere_cache(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFinding( + name="name_value", + description="description_value", + type_=storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE, + category=storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT, + severity=storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL, + target_resource="target_resource_value", + associated_resources=["associated_resources_value"], + ) + response = client.get_intelligence_finding(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.GetIntelligenceFindingRequest() + assert args[0] == request -def test_update_anywhere_cache_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceFinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.type_ + == storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE ) - request = storage_control.UpdateAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.update_anywhere_cache(request) - - -def test_disable_anywhere_cache_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + assert ( + response.category + == storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT ) - request = storage_control.DisableAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.disable_anywhere_cache(request) - - -def test_pause_anywhere_cache_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + assert ( + response.severity == storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL ) - request = storage_control.PauseAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.pause_anywhere_cache(request) + assert response.target_resource == "target_resource_value" + assert response.associated_resources == ["associated_resources_value"] -def test_resume_anywhere_cache_rest_no_http_options(): +def test_get_intelligence_finding_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - request = storage_control.ResumeAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.resume_anywhere_cache(request) - -def test_get_anywhere_cache_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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 = storage_control.GetIntelligenceFindingRequest( + name="name_value", ) - request = storage_control.GetAnywhereCacheRequest() - with pytest.raises(RuntimeError): - client.get_anywhere_cache(request) - -def test_list_anywhere_caches_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = storage_control.ListAnywhereCachesRequest() - with pytest.raises(RuntimeError): - client.list_anywhere_caches(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_intelligence_finding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRequest( + name="name_value", + ) + assert args[0] == request_msg -def test_get_project_intelligence_config_rest_use_cached_wrapped_rpc(): +def test_get_intelligence_finding_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -10675,7 +10585,7 @@ def test_get_project_intelligence_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_project_intelligence_config + client._transport.get_intelligence_finding in client._transport._wrapped_methods ) @@ -10685,384 +10595,357 @@ def test_get_project_intelligence_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_project_intelligence_config + client._transport.get_intelligence_finding ] = mock_rpc - request = {} - client.get_project_intelligence_config(request) + client.get_intelligence_finding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_project_intelligence_config(request) + client.get_intelligence_finding(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_project_intelligence_config_rest_required_fields( - request_type=storage_control.GetProjectIntelligenceConfigRequest, +@pytest.mark.asyncio +async def test_get_intelligence_finding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.StorageControlRestTransport + # Clients should use _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 = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.get_intelligence_finding + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_project_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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_intelligence_finding + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.get_intelligence_finding(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_project_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.get_intelligence_finding(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # 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 +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetIntelligenceFindingRequest(), + {}, + ], +) +async def test_get_intelligence_finding_async( + request_type, transport: str = "grpc_asyncio" +): + client = StorageControlAsyncClient( + 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_intelligence_finding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFinding( + name="name_value", + description="description_value", + type_=storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE, + category=storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT, + severity=storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL, + target_resource="target_resource_value", + associated_resources=["associated_resources_value"], + ) + ) + response = await client.get_intelligence_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = storage_control.GetIntelligenceFindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceFinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.type_ + == storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE + ) + assert ( + response.category + == storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT + ) + assert ( + response.severity == storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL + ) + assert response.target_resource == "target_resource_value" + assert response.associated_resources == ["associated_resources_value"] + +def test_get_intelligence_finding_field_headers(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.GetIntelligenceFindingRequest() - # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceFinding() + client.get_intelligence_finding(request) - response = client.get_project_intelligence_config(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_project_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_intelligence_finding_field_headers_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.get_project_intelligence_config._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.GetIntelligenceFindingRequest() + request.name = "name_value" -def test_get_project_intelligence_config_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFinding() + ) + await client.get_intelligence_finding(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_intelligence_finding_flattened(): client = StorageControlClient( 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 = storage_control.IntelligenceConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/intelligenceConfig" - } - - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_intelligence_finding( 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 = storage_control.IntelligenceConfig.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_project_intelligence_config(**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/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) + 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_project_intelligence_config_rest_flattened_error(transport: str = "rest"): +def test_get_intelligence_finding_flattened_error(): client = StorageControlClient( 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_project_intelligence_config( - storage_control.GetProjectIntelligenceConfigRequest(), + client.get_intelligence_finding( + storage_control.GetIntelligenceFindingRequest(), name="name_value", ) -def test_update_project_intelligence_config_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 = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_get_intelligence_finding_flattened_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFinding() - # Ensure method has been cached - assert ( - client._transport.update_project_intelligence_config - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFinding() ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_intelligence_finding( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.update_project_intelligence_config - ] = mock_rpc - - request = {} - client.update_project_intelligence_config(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # 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 - client.update_project_intelligence_config(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_intelligence_finding_flattened_error_async(): + client = StorageControlAsyncClient( + 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_intelligence_finding( + storage_control.GetIntelligenceFindingRequest(), + name="name_value", + ) -def test_update_project_intelligence_config_rest_required_fields( - request_type=storage_control.UpdateProjectIntelligenceConfigRequest, -): - transport_class = transports.StorageControlRestTransport - 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) +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingsRequest(), + {}, + ], +) +def test_list_intelligence_findings(request_type, transport: str = "grpc"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_project_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present + # Everything is optional 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 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_project_intelligence_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingsResponse( + next_page_token="next_page_token_value", ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 = storage_control.IntelligenceConfig.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_intelligence_findings(request) - response = client.update_project_intelligence_config(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_update_project_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.ListIntelligenceFindingsRequest() + assert args[0] == request - unset_fields = ( - transport.update_project_intelligence_config._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "intelligenceConfig", - "updateMask", - ) - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntelligenceFindingsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_project_intelligence_config_rest_flattened(): +def test_list_intelligence_findings_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # 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 = storage_control.IntelligenceConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "intelligence_config": { - "name": "projects/sample1/locations/sample2/intelligenceConfig" - } - } - - # get truthy value for each flattened field - mock_args = dict( - intelligence_config=storage_control.IntelligenceConfig(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 = storage_control.IntelligenceConfig.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_project_intelligence_config(**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/{intelligence_config.name=projects/*/locations/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) - - -def test_update_project_intelligence_config_rest_flattened_error( - transport: str = "rest", -): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # 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 = storage_control.ListIntelligenceFindingsRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_project_intelligence_config( - storage_control.UpdateProjectIntelligenceConfigRequest(), - intelligence_config=storage_control.IntelligenceConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.list_intelligence_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingsRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + assert args[0] == request_msg -def test_get_folder_intelligence_config_rest_use_cached_wrapped_rpc(): +def test_list_intelligence_findings_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11071,7 +10954,7 @@ def test_get_folder_intelligence_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_folder_intelligence_config + client._transport.list_intelligence_findings in client._transport._wrapped_methods ) @@ -11081,384 +10964,539 @@ def test_get_folder_intelligence_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_folder_intelligence_config + client._transport.list_intelligence_findings ] = mock_rpc - request = {} - client.get_folder_intelligence_config(request) + client.list_intelligence_findings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_folder_intelligence_config(request) + client.list_intelligence_findings(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_folder_intelligence_config_rest_required_fields( - request_type=storage_control.GetFolderIntelligenceConfigRequest, +@pytest.mark.asyncio +async def test_list_intelligence_findings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.StorageControlRestTransport + # Clients should use _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 = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_intelligence_findings + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_folder_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # 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_intelligence_findings + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_intelligence_findings(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_folder_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.list_intelligence_findings(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingsRequest(), + {}, + ], +) +async def test_list_intelligence_findings_async( + request_type, transport: str = "grpc_asyncio" +): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 + # Everything is optional 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 - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_intelligence_findings(request) - # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = storage_control.ListIntelligenceFindingsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntelligenceFindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" - response = client.get_folder_intelligence_config(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +def test_list_intelligence_findings_field_headers(): + client = StorageControlClient( + 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 = storage_control.ListIntelligenceFindingsRequest() -def test_get_folder_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + request.parent = "parent_value" - unset_fields = transport.get_folder_intelligence_config._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + call.return_value = storage_control.ListIntelligenceFindingsResponse() + client.list_intelligence_findings(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_get_folder_intelligence_config_rest_flattened(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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_intelligence_findings_field_headers_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = storage_control.IntelligenceConfig() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.ListIntelligenceFindingsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "folders/sample1/locations/sample2/intelligenceConfig" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingsResponse() ) - mock_args.update(sample_request) + await client.list_intelligence_findings(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 = storage_control.IntelligenceConfig.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"} + # 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"] - client.get_folder_intelligence_config(**mock_args) + +def test_list_intelligence_findings_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_intelligence_findings( + parent="parent_value", + ) # 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=folders/*/locations/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) + 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_get_folder_intelligence_config_rest_flattened_error(transport: str = "rest"): +def test_list_intelligence_findings_flattened_error(): client = StorageControlClient( 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_folder_intelligence_config( - storage_control.GetFolderIntelligenceConfigRequest(), - name="name_value", + client.list_intelligence_findings( + storage_control.ListIntelligenceFindingsRequest(), + parent="parent_value", ) -def test_update_folder_intelligence_config_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 = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_intelligence_findings_flattened_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingsResponse() - # Ensure method has been cached - assert ( - client._transport.update_folder_intelligence_config - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingsResponse() ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_intelligence_findings( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.update_folder_intelligence_config - ] = mock_rpc - - request = {} - client.update_folder_intelligence_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_folder_intelligence_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # 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 -def test_update_folder_intelligence_config_rest_required_fields( - request_type=storage_control.UpdateFolderIntelligenceConfigRequest, -): - transport_class = transports.StorageControlRestTransport - 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) +@pytest.mark.asyncio +async def test_list_intelligence_findings_flattened_error_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_folder_intelligence_config._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_folder_intelligence_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_intelligence_findings( + storage_control.ListIntelligenceFindingsRequest(), + parent="parent_value", ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone +def test_list_intelligence_findings_pager(transport_name: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 = storage_control.IntelligenceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + ), + RuntimeError, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_intelligence_findings( + request={}, retry=retry, timeout=timeout + ) - response = client.update_folder_intelligence_config(request) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storage_control.IntelligenceFinding) for i in results) -def test_update_folder_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_intelligence_findings_pages(transport_name: str = "grpc"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - unset_fields = ( - transport.update_folder_intelligence_config._get_unset_required_fields({}) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_intelligence_findings(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_intelligence_findings_async_pager(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + ), + RuntimeError, ) - & set( - ( - "intelligenceConfig", - "updateMask", - ) + async_pager = await client.list_intelligence_findings( + 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, storage_control.IntelligenceFinding) for i in responses ) + + +@pytest.mark.asyncio +async def test_list_intelligence_findings_async_pages(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_intelligence_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + -def test_update_folder_intelligence_config_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + storage_control.SummarizeIntelligenceFindingsRequest(), + {}, + ], +) +def test_summarize_intelligence_findings(request_type, transport: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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 = storage_control.IntelligenceConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "intelligence_config": { - "name": "folders/sample1/locations/sample2/intelligenceConfig" - } - } + # Everything is optional 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 - # get truthy value for each flattened field - mock_args = dict( - intelligence_config=storage_control.IntelligenceConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.SummarizeIntelligenceFindingsResponse( + next_page_token="next_page_token_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 = storage_control.IntelligenceConfig.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.summarize_intelligence_findings(request) - client.update_folder_intelligence_config(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.SummarizeIntelligenceFindingsRequest() + assert args[0] == request - # 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/{intelligence_config.name=folders/*/locations/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SummarizeIntelligenceFindingsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_folder_intelligence_config_rest_flattened_error( - transport: str = "rest", -): +def test_summarize_intelligence_findings_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_folder_intelligence_config( - storage_control.UpdateFolderIntelligenceConfigRequest(), - intelligence_config=storage_control.IntelligenceConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # 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 = storage_control.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + filter="filter_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.summarize_intelligence_findings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.summarize_intelligence_findings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.SummarizeIntelligenceFindingsRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", ) + assert args[0] == request_msg -def test_get_organization_intelligence_config_rest_use_cached_wrapped_rpc(): +def test_summarize_intelligence_findings_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11467,7 +11505,7 @@ def test_get_organization_intelligence_config_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_organization_intelligence_config + client._transport.summarize_intelligence_findings in client._transport._wrapped_methods ) @@ -11477,4097 +11515,8656 @@ def test_get_organization_intelligence_config_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_organization_intelligence_config + client._transport.summarize_intelligence_findings ] = mock_rpc - request = {} - client.get_organization_intelligence_config(request) + client.summarize_intelligence_findings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_organization_intelligence_config(request) + client.summarize_intelligence_findings(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_organization_intelligence_config_rest_required_fields( - request_type=storage_control.GetOrganizationIntelligenceConfigRequest, +@pytest.mark.asyncio +async def test_summarize_intelligence_findings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.StorageControlRestTransport + # Clients should use _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 = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.summarize_intelligence_findings + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_organization_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.summarize_intelligence_findings + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.summarize_intelligence_findings(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_organization_intelligence_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.summarize_intelligence_findings(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + storage_control.SummarizeIntelligenceFindingsRequest(), + {}, + ], +) +async def test_summarize_intelligence_findings_async( + request_type, transport: str = "grpc_asyncio" +): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 + # Everything is optional 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 - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.SummarizeIntelligenceFindingsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.summarize_intelligence_findings(request) - # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = storage_control.SummarizeIntelligenceFindingsRequest() + assert args[0] == request - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SummarizeIntelligenceFindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" - response = client.get_organization_intelligence_config(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +def test_summarize_intelligence_findings_field_headers(): + client = StorageControlClient( + 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 = storage_control.SummarizeIntelligenceFindingsRequest() -def test_get_organization_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + request.parent = "parent_value" - unset_fields = ( - transport.get_organization_intelligence_config._get_unset_required_fields({}) - ) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + call.return_value = storage_control.SummarizeIntelligenceFindingsResponse() + client.summarize_intelligence_findings(request) + + # Establish that the 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"] -def test_get_organization_intelligence_config_rest_flattened(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_summarize_intelligence_findings_field_headers_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = storage_control.IntelligenceConfig() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.SummarizeIntelligenceFindingsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.SummarizeIntelligenceFindingsResponse() ) - mock_args.update(sample_request) + await client.summarize_intelligence_findings(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 = storage_control.IntelligenceConfig.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"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_organization_intelligence_config(**mock_args) + # 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_summarize_intelligence_findings_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.SummarizeIntelligenceFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.summarize_intelligence_findings( + parent="parent_value", + ) # 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=organizations/*/locations/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) + 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_get_organization_intelligence_config_rest_flattened_error( - transport: str = "rest", -): +def test_summarize_intelligence_findings_flattened_error(): client = StorageControlClient( 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_organization_intelligence_config( - storage_control.GetOrganizationIntelligenceConfigRequest(), - name="name_value", + client.summarize_intelligence_findings( + storage_control.SummarizeIntelligenceFindingsRequest(), + parent="parent_value", ) -def test_update_organization_intelligence_config_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 = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_summarize_intelligence_findings_flattened_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.SummarizeIntelligenceFindingsResponse() - # Ensure method has been cached - assert ( - client._transport.update_organization_intelligence_config - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.SummarizeIntelligenceFindingsResponse() ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.summarize_intelligence_findings( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.update_organization_intelligence_config - ] = mock_rpc - - request = {} - client.update_organization_intelligence_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.update_organization_intelligence_config(request) + # 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 - # 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_summarize_intelligence_findings_flattened_error_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_update_organization_intelligence_config_rest_required_fields( - request_type=storage_control.UpdateOrganizationIntelligenceConfigRequest, -): - transport_class = transports.StorageControlRestTransport - - 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) - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.summarize_intelligence_findings( + storage_control.SummarizeIntelligenceFindingsRequest(), + parent="parent_value", + ) - # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_organization_intelligence_config._get_unset_required_fields( - jsonified_request +def test_summarize_intelligence_findings_pager(transport_name: str = "grpc"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + next_page_token="abc", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[], + next_page_token="def", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + ], + next_page_token="ghi", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + ), + RuntimeError, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_organization_intelligence_config._get_unset_required_fields( - jsonified_request - ) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.summarize_intelligence_findings( + request={}, retry=retry, timeout=timeout ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storage_control.FindingSummary) for i in results) + +def test_summarize_intelligence_findings_pages(transport_name: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = storage_control.IntelligenceConfig() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + next_page_token="abc", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[], + next_page_token="def", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + ], + next_page_token="ghi", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + ), + RuntimeError, + ) + pages = list(client.summarize_intelligence_findings(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.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"} +@pytest.mark.asyncio +async def test_summarize_intelligence_findings_async_pager(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.update_organization_intelligence_config(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + next_page_token="abc", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[], + next_page_token="def", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + ], + next_page_token="ghi", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + ), + RuntimeError, + ) + async_pager = await client.summarize_intelligence_findings( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + assert len(responses) == 6 + assert all(isinstance(i, storage_control.FindingSummary) for i in responses) -def test_update_organization_intelligence_config_rest_unset_required_fields(): - transport = transports.StorageControlRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_summarize_intelligence_findings_async_pages(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = ( - transport.update_organization_intelligence_config._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "intelligenceConfig", - "updateMask", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + next_page_token="abc", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[], + next_page_token="def", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + ], + next_page_token="ghi", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + ), + RuntimeError, ) - ) + pages = [] + async for page_ in ( + await client.summarize_intelligence_findings(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_update_organization_intelligence_config_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetIntelligenceFindingRevisionRequest(), + {}, + ], +) +def test_get_intelligence_finding_revision(request_type, transport: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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 = storage_control.IntelligenceConfig() - - # get arguments that satisfy an http rule for this method - sample_request = { - "intelligence_config": { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" - } - } + # Everything is optional 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 - # get truthy value for each flattened field - mock_args = dict( - intelligence_config=storage_control.IntelligenceConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFindingRevision( + 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 = storage_control.IntelligenceConfig.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_intelligence_finding_revision(request) - client.update_organization_intelligence_config(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.GetIntelligenceFindingRevisionRequest() + assert args[0] == request - # 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/{intelligence_config.name=organizations/*/locations/*/intelligenceConfig}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceFindingRevision) + assert response.name == "name_value" -def test_update_organization_intelligence_config_rest_flattened_error( - transport: str = "rest", -): +def test_get_intelligence_finding_revision_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_organization_intelligence_config( - storage_control.UpdateOrganizationIntelligenceConfigRequest(), - intelligence_config=storage_control.IntelligenceConfig(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # 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 = storage_control.GetIntelligenceFindingRevisionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_intelligence_finding_revision(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRevisionRequest( + name="name_value", ) + assert args[0] == request_msg -def test_get_iam_policy_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = iam_policy_pb2.GetIamPolicyRequest() - with pytest.raises(RuntimeError): - client.get_iam_policy(request) +def test_get_intelligence_finding_revision_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_set_iam_policy_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = iam_policy_pb2.SetIamPolicyRequest() - with pytest.raises(RuntimeError): - client.set_iam_policy(request) + # Ensure method has been cached + assert ( + client._transport.get_intelligence_finding_revision + 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_intelligence_finding_revision + ] = mock_rpc + request = {} + client.get_intelligence_finding_revision(request) -def test_test_iam_permissions_rest_no_http_options(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = iam_policy_pb2.TestIamPermissionsRequest() - with pytest.raises(RuntimeError): - client.test_iam_permissions(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_intelligence_finding_revision(request) -def test_create_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_folder({}) - assert "Method CreateFolder is not available over REST transport" in str( - not_implemented_error.value - ) + # 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_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_folder({}) - assert "Method DeleteFolder is not available over REST transport" in str( - not_implemented_error.value - ) +@pytest.mark.asyncio +async def test_get_intelligence_finding_revision_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 = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_get_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_folder({}) - assert "Method GetFolder is not available over REST transport" in str( - not_implemented_error.value - ) + # Ensure method has been cached + assert ( + client._client._transport.get_intelligence_finding_revision + 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_intelligence_finding_revision + ] = mock_rpc -def test_list_folders_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_folders({}) - assert "Method ListFolders is not available over REST transport" in str( - not_implemented_error.value - ) + request = {} + await client.get_intelligence_finding_revision(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_rename_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.rename_folder({}) - assert "Method RenameFolder is not available over REST transport" in str( - not_implemented_error.value - ) + await client.get_intelligence_finding_revision(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_folder_recursive_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_folder_recursive({}) - assert "Method DeleteFolderRecursive is not available over REST transport" in str( - not_implemented_error.value +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetIntelligenceFindingRevisionRequest(), + {}, + ], +) +async def test_get_intelligence_finding_revision_async( + request_type, transport: str = "grpc_asyncio" +): + client = StorageControlAsyncClient( + 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 -def test_get_storage_layout_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_storage_layout({}) - assert "Method GetStorageLayout is not available over REST transport" in str( - not_implemented_error.value - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFindingRevision( + name="name_value", + ) + ) + response = await client.get_intelligence_finding_revision(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = storage_control.GetIntelligenceFindingRevisionRequest() + assert args[0] == request -def test_create_managed_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_managed_folder({}) - assert "Method CreateManagedFolder is not available over REST transport" in str( - not_implemented_error.value - ) + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceFindingRevision) + assert response.name == "name_value" -def test_delete_managed_folder_rest_error(): +def test_get_intelligence_finding_revision_field_headers(): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_managed_folder({}) - assert "Method DeleteManagedFolder is not available over REST transport" in str( - not_implemented_error.value + 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 = storage_control.GetIntelligenceFindingRevisionRequest() -def test_get_managed_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_managed_folder({}) - assert "Method GetManagedFolder is not available over REST transport" in str( - not_implemented_error.value - ) + request.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceFindingRevision() + client.get_intelligence_finding_revision(request) -def test_list_managed_folders_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_managed_folders({}) - assert "Method ListManagedFolders is not available over REST transport" in str( - not_implemented_error.value - ) - + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_create_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_anywhere_cache({}) - assert "Method CreateAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + # 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_update_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.update_anywhere_cache({}) - assert "Method UpdateAnywhereCache is not available over REST transport" in str( - not_implemented_error.value +@pytest.mark.asyncio +async def test_get_intelligence_finding_revision_field_headers_async(): + client = StorageControlAsyncClient( + 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 = storage_control.GetIntelligenceFindingRevisionRequest() -def test_disable_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.disable_anywhere_cache({}) - assert "Method DisableAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) - + request.name = "name_value" -def test_pause_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.pause_anywhere_cache({}) - assert "Method PauseAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFindingRevision() + ) + await client.get_intelligence_finding_revision(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_resume_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.resume_anywhere_cache({}) - assert "Method ResumeAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + # 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_anywhere_cache_rest_error(): +def test_get_intelligence_finding_revision_flattened(): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_anywhere_cache({}) - assert "Method GetAnywhereCache is not available over REST transport" in str( - not_implemented_error.value + credentials=ga_credentials.AnonymousCredentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFindingRevision() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_intelligence_finding_revision( + name="name_value", + ) -def test_list_anywhere_caches_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_anywhere_caches({}) - assert "Method ListAnywhereCaches is not available over REST transport" in str( - not_implemented_error.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_iam_policy_rest_error(): +def test_get_intelligence_finding_revision_flattened_error(): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_iam_policy({}) - assert "Method GetIamPolicy is not available over REST transport" in str( - not_implemented_error.value + credentials=ga_credentials.AnonymousCredentials(), ) - -def test_set_iam_policy_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.set_iam_policy({}) - assert "Method SetIamPolicy is not available over REST transport" in str( - not_implemented_error.value - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_intelligence_finding_revision( + storage_control.GetIntelligenceFindingRevisionRequest(), + name="name_value", + ) -def test_test_iam_permissions_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # Since a `google.api.http` annotation is required for using a rest transport - # method, this should error. - with pytest.raises(NotImplementedError) as not_implemented_error: - client.test_iam_permissions({}) - assert "Method TestIamPermissions is not available over REST transport" in str( - not_implemented_error.value +@pytest.mark.asyncio +async def test_get_intelligence_finding_revision_flattened_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.IntelligenceFindingRevision() -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.StorageControlGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFindingRevision() ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.StorageControlGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = StorageControlClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_intelligence_finding_revision( + name="name_value", ) - # It is an error to provide an api_key and a transport instance. - transport = transports.StorageControlGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = StorageControlClient( - client_options=options, - transport=transport, - ) + # 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 - # 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 = StorageControlClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.StorageControlGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_get_intelligence_finding_revision_flattened_error_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = StorageControlClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + await client.get_intelligence_finding_revision( + storage_control.GetIntelligenceFindingRevisionRequest(), + name="name_value", ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.StorageControlGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingRevisionsRequest(), + {}, + ], +) +def test_list_intelligence_finding_revisions(request_type, transport: str = "grpc"): + client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = StorageControlClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.StorageControlGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Everything is optional 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 - transport = transports.StorageControlGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.StorageControlGrpcTransport, - transports.StorageControlGrpcAsyncIOTransport, - transports.StorageControlRestTransport, - ], -) -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 = StorageControlClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_finding_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingRevisionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_intelligence_finding_revisions(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.ListIntelligenceFindingRevisionsRequest() + assert args[0] == request -def test_initialize_client_w_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntelligenceFindingRevisionsPager) + assert response.next_page_token == "next_page_token_value" -# 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_folder_empty_call_grpc(): +def test_list_intelligence_finding_revisions_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 = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - call.return_value = storage_control.Folder() - client.create_folder(request=None) + # 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 = storage_control.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + page_token="page_token_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_finding_revisions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_intelligence_finding_revisions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = storage_control.CreateFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id + request_msg = storage_control.ListIntelligenceFindingRevisionsRequest( + parent="parent_value", + page_token="page_token_value", + ) assert args[0] == request_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_folder_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_list_intelligence_finding_revisions_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - call.return_value = None - client.delete_folder(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.list_intelligence_finding_revisions + 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_intelligence_finding_revisions + ] = mock_rpc + request = {} + client.list_intelligence_finding_revisions(request) -# 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_folder_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - call.return_value = storage_control.Folder() - client.get_folder(request=None) + client.list_intelligence_finding_revisions(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# 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_folders_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_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 = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - call.return_value = storage_control.ListFoldersResponse() - client.list_folders(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListFoldersRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._client._transport.list_intelligence_finding_revisions + 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_intelligence_finding_revisions + ] = mock_rpc -# 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_rename_folder_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + await client.list_intelligence_finding_revisions(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.rename_folder), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.rename_folder(request=None) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.RenameFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + await client.list_intelligence_finding_revisions(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# 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_folder_recursive_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingRevisionsRequest(), + {}, + ], +) +async def test_list_intelligence_finding_revisions_async( + request_type, transport: str = "grpc_asyncio" +): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional 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_folder_recursive), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_folder_recursive(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingRevisionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_intelligence_finding_revisions(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRecursiveRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + request = storage_control.ListIntelligenceFindingRevisionsRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntelligenceFindingRevisionsAsyncPager) + assert response.next_page_token == "next_page_token_value" -# 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_storage_layout_empty_call_grpc(): + +def test_list_intelligence_finding_revisions_field_headers(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_storage_layout), "__call__" - ) as call: - call.return_value = storage_control.StorageLayout() - client.get_storage_layout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetStorageLayoutRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.ListIntelligenceFindingRevisionsRequest() -# 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_managed_folder_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request.parent = "parent_value" - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_managed_folder), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = storage_control.ManagedFolder() - client.create_managed_folder(request=None) + call.return_value = storage_control.ListIntelligenceFindingRevisionsResponse() + client.list_intelligence_finding_revisions(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = storage_control.CreateManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + 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"] -# 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_managed_folder_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_field_headers_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = storage_control.ListIntelligenceFindingRevisionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_managed_folder), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = None - client.delete_managed_folder(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingRevisionsResponse() + ) + await client.list_intelligence_finding_revisions(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + 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"] -# 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_managed_folder_empty_call_grpc(): + +def test_list_intelligence_finding_revisions_flattened(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_managed_folder), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = storage_control.ManagedFolder() - client.get_managed_folder(request=None) + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingRevisionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_intelligence_finding_revisions( + parent="parent_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# 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_managed_folders_empty_call_grpc(): +def test_list_intelligence_finding_revisions_flattened_error(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_managed_folders), "__call__" - ) as call: - call.return_value = storage_control.ListManagedFoldersResponse() - client.list_managed_folders(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListManagedFoldersRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_intelligence_finding_revisions( + storage_control.ListIntelligenceFindingRevisionsRequest(), + parent="parent_value", + ) -# 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_anywhere_cache_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_flattened_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_anywhere_cache), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_anywhere_cache(request=None) + # Designate an appropriate return value for the call. + call.return_value = storage_control.ListIntelligenceFindingRevisionsResponse() - # Establish that the underlying stub method was called. - call.assert_called() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingRevisionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_intelligence_finding_revisions( + 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] - request_msg = storage_control.CreateAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -# 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_anywhere_cache_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_flattened_error_async(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_anywhere_cache), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_anywhere_cache(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_intelligence_finding_revisions( + storage_control.ListIntelligenceFindingRevisionsRequest(), + parent="parent_value", + ) -# 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_disable_anywhere_cache_empty_call_grpc(): +def test_list_intelligence_finding_revisions_pager(transport_name: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.disable_anywhere_cache), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = storage_control.AnywhereCache() - client.disable_anywhere_cache(request=None) + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + ), + RuntimeError, + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DisableAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_intelligence_finding_revisions( + 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, storage_control.IntelligenceFindingRevision) for i in results + ) -# 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_pause_anywhere_cache_empty_call_grpc(): + +def test_list_intelligence_finding_revisions_pages(transport_name: str = "grpc"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.pause_anywhere_cache), "__call__" + type(client.transport.list_intelligence_finding_revisions), "__call__" ) as call: - call.return_value = storage_control.AnywhereCache() - client.pause_anywhere_cache(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.PauseAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + ), + RuntimeError, + ) + pages = list(client.list_intelligence_finding_revisions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_resume_anywhere_cache_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_async_pager(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.resume_anywhere_cache), "__call__" + type(client.transport.list_intelligence_finding_revisions), + "__call__", + new_callable=mock.AsyncMock, ) as call: - call.return_value = storage_control.AnywhereCache() - client.resume_anywhere_cache(request=None) + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_intelligence_finding_revisions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ResumeAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + assert len(responses) == 6 + assert all( + isinstance(i, storage_control.IntelligenceFindingRevision) + for i in responses + ) -# 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_anywhere_cache_empty_call_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_intelligence_finding_revisions_async_pages(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_anywhere_cache), "__call__" + type(client.transport.list_intelligence_finding_revisions), + "__call__", + new_callable=mock.AsyncMock, ) as call: - call.return_value = storage_control.AnywhereCache() - client.get_anywhere_cache(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Set the response to a series of pages. + call.side_effect = ( + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_intelligence_finding_revisions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_anywhere_caches_empty_call_grpc(): +def test_create_folder_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.CreateFolderRequest() + with pytest.raises(RuntimeError): + client.create_folder(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_anywhere_caches), "__call__" - ) as call: - call.return_value = storage_control.ListAnywhereCachesResponse() - client.list_anywhere_caches(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListAnywhereCachesRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg +def test_delete_folder_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.DeleteFolderRequest() + with pytest.raises(RuntimeError): + client.delete_folder(request) -# 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_project_intelligence_config_empty_call_grpc(): +def test_get_folder_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.GetFolderRequest() + with pytest.raises(RuntimeError): + client.get_folder(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_project_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.get_project_intelligence_config(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetProjectIntelligenceConfigRequest() - assert args[0] == request_msg +def test_list_folders_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.ListFoldersRequest() + with pytest.raises(RuntimeError): + client.list_folders(request) -# 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_project_intelligence_config_empty_call_grpc(): +def test_rename_folder_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.RenameFolderRequest() + with pytest.raises(RuntimeError): + client.rename_folder(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_project_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.update_project_intelligence_config(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateProjectIntelligenceConfigRequest() - assert args[0] == request_msg +def test_delete_folder_recursive_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.DeleteFolderRecursiveRequest() + with pytest.raises(RuntimeError): + client.delete_folder_recursive(request) -# 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_folder_intelligence_config_empty_call_grpc(): +def test_get_storage_layout_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.GetStorageLayoutRequest() + with pytest.raises(RuntimeError): + client.get_storage_layout(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_folder_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.get_folder_intelligence_config(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetFolderIntelligenceConfigRequest() - assert args[0] == request_msg +def test_create_managed_folder_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.CreateManagedFolderRequest() + with pytest.raises(RuntimeError): + client.create_managed_folder(request) -# 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_folder_intelligence_config_empty_call_grpc(): +def test_delete_managed_folder_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.DeleteManagedFolderRequest() + with pytest.raises(RuntimeError): + client.delete_managed_folder(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_folder_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.update_folder_intelligence_config(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateFolderIntelligenceConfigRequest() - assert args[0] == request_msg +def test_get_managed_folder_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.GetManagedFolderRequest() + with pytest.raises(RuntimeError): + client.get_managed_folder(request) -# 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_organization_intelligence_config_empty_call_grpc(): +def test_list_managed_folders_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.get_organization_intelligence_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetOrganizationIntelligenceConfigRequest() - assert args[0] == request_msg + request = storage_control.ListManagedFoldersRequest() + with pytest.raises(RuntimeError): + client.list_managed_folders(request) -# 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_organization_intelligence_config_empty_call_grpc(): +def test_create_anywhere_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_intelligence_config), "__call__" - ) as call: - call.return_value = storage_control.IntelligenceConfig() - client.update_organization_intelligence_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateOrganizationIntelligenceConfigRequest() - assert args[0] == request_msg + request = storage_control.CreateAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.create_anywhere_cache(request) -# 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_iam_policy_empty_call_grpc(): +def test_update_anywhere_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest() - assert args[0] == request_msg + request = storage_control.UpdateAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.update_anywhere_cache(request) -# 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_set_iam_policy_empty_call_grpc(): +def test_disable_anywhere_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest() - assert args[0] == request_msg + request = storage_control.DisableAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.disable_anywhere_cache(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_test_iam_permissions_empty_call_grpc(): +def test_pause_anywhere_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest() - assert args[0] == request_msg + request = storage_control.PauseAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.pause_anywhere_cache(request) -def test_create_folder_routing_parameters_request_1_grpc(): +def test_resume_anywhere_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.ResumeAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.resume_anywhere_cache(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - call.return_value = storage_control.Folder() - client.create_folder(request={"parent": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateFolderRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_get_anywhere_cache_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.GetAnywhereCacheRequest() + with pytest.raises(RuntimeError): + client.get_anywhere_cache(request) -def test_delete_folder_routing_parameters_request_1_grpc(): +def test_list_anywhere_caches_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = storage_control.ListAnywhereCachesRequest() + with pytest.raises(RuntimeError): + client.list_anywhere_caches(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - call.return_value = None - client.delete_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} +def test_get_project_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.get_project_intelligence_config + 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_project_intelligence_config + ] = mock_rpc -def test_get_folder_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + client.get_project_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - call.return_value = storage_control.Folder() - client.get_folder(request={"name": "projects/sample1/buckets/sample2/sample3"}) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.get_project_intelligence_config(request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # 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_folders_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_project_intelligence_config_rest_required_fields( + request_type=storage_control.GetProjectIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - call.return_value = storage_control.ListFoldersResponse() - client.list_folders(request={"parent": "sample1"}) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListFoldersRequest(**{"parent": "sample1"}) - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_project_intelligence_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_project_intelligence_config._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" -def test_rename_folder_routing_parameters_request_1_grpc(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.rename_folder), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.rename_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.RenameFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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"} -def test_delete_folder_recursive_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.get_project_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder_recursive), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_folder_recursive( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRecursiveRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_get_project_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.get_project_intelligence_config._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_storage_layout_routing_parameters_request_1_grpc(): + +def test_get_project_intelligence_config_rest_flattened(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_storage_layout), "__call__" - ) as call: - call.return_value = storage_control.StorageLayout() - client.get_storage_layout( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # 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 = storage_control.IntelligenceConfig() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetStorageLayoutRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/intelligenceConfig" + } - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # 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 = storage_control.IntelligenceConfig.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"} -def test_create_managed_folder_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_managed_folder), "__call__" - ) as call: - call.return_value = storage_control.ManagedFolder() - client.create_managed_folder(request={"parent": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateManagedFolderRequest( - **{"parent": "sample1"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.get_project_intelligence_config(**mock_args) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # 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/*/intelligenceConfig}" + % client.transport._host, + args[1], ) -def test_delete_managed_folder_routing_parameters_request_1_grpc(): +def test_get_project_intelligence_config_rest_flattened_error(transport: str = "rest"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_managed_folder), "__call__" - ) as call: - call.return_value = None - client.delete_managed_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_project_intelligence_config( + storage_control.GetProjectIntelligenceConfigRequest(), + name="name_value", ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteManagedFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] +def test_update_project_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_get_managed_folder_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_managed_folder), "__call__" - ) as call: - call.return_value = storage_control.ManagedFolder() - client.get_managed_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} + # Ensure method has been cached + assert ( + client._transport.update_project_intelligence_config + in client._transport._wrapped_methods ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetManagedFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + # 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. ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client._transport._wrapped_methods[ + client._transport.update_project_intelligence_config + ] = mock_rpc - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + request = {} + client.update_project_intelligence_config(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_list_managed_folders_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.update_project_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_managed_folders), "__call__" - ) as call: - call.return_value = storage_control.ListManagedFoldersResponse() - client.list_managed_folders(request={"parent": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListManagedFoldersRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_update_project_intelligence_config_rest_required_fields( + request_type=storage_control.UpdateProjectIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport -def test_create_anywhere_cache_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_anywhere_cache), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_anywhere_cache(request={"parent": "sample1"}) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateAnywhereCacheRequest( - **{"parent": "sample1"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_project_intelligence_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_project_intelligence_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", ) + ) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone -def test_update_anywhere_cache_routing_parameters_request_1_grpc(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_anywhere_cache), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_anywhere_cache( - request={ - "anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"} + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.UpdateAnywhereCacheRequest( - **{"anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"}} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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"} -def test_disable_anywhere_cache_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.update_project_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_anywhere_cache), "__call__" - ) as call: - call.return_value = storage_control.AnywhereCache() - client.disable_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DisableAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] +def test_update_project_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_project_intelligence_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "intelligenceConfig", + "updateMask", + ) ) + ) -def test_pause_anywhere_cache_routing_parameters_request_1_grpc(): +def test_update_project_intelligence_config_rest_flattened(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.pause_anywhere_cache), "__call__" - ) as call: - call.return_value = storage_control.AnywhereCache() - client.pause_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # 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 = storage_control.IntelligenceConfig() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.PauseAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + # get arguments that satisfy an http rule for this method + sample_request = { + "intelligence_config": { + "name": "projects/sample1/locations/sample2/intelligenceConfig" + } + } + + # get truthy value for each flattened field + mock_args = dict( + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + mock_args.update(sample_request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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_project_intelligence_config(**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/{intelligence_config.name=projects/*/locations/*/intelligenceConfig}" + % client.transport._host, + args[1], ) -def test_resume_anywhere_cache_routing_parameters_request_1_grpc(): +def test_update_project_intelligence_config_rest_flattened_error( + transport: str = "rest", +): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.resume_anywhere_cache), "__call__" - ) as call: - call.return_value = storage_control.AnywhereCache() - client.resume_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_project_intelligence_config( + storage_control.UpdateProjectIntelligenceConfigRequest(), + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ResumeAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + +def test_get_folder_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.get_folder_intelligence_config + 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_folder_intelligence_config + ] = mock_rpc -def test_get_anywhere_cache_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + client.get_folder_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_anywhere_cache), "__call__" - ) as call: - call.return_value = storage_control.AnywhereCache() - client.get_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.get_folder_intelligence_config(request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # 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_anywhere_caches_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_folder_intelligence_config_rest_required_fields( + request_type=storage_control.GetFolderIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_anywhere_caches), "__call__" - ) as call: - call.return_value = storage_control.ListAnywhereCachesResponse() - client.list_anywhere_caches(request={"parent": "sample1"}) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListAnywhereCachesRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_folder_intelligence_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_folder_intelligence_config._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" -def test_get_iam_policy_routing_parameters_request_1_grpc(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(request={"resource": "sample1"}) + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest(**{"resource": "sample1"}) - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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"} -def test_get_iam_policy_routing_parameters_request_2_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response = client.get_folder_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy( - request={"resource": "projects/sample1/buckets/sample2/sample3"} - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest( - **{"resource": "projects/sample1/buckets/sample2/sample3"} - ) - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_get_folder_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_folder_intelligence_config._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_set_iam_policy_routing_parameters_request_1_grpc(): +def test_get_folder_intelligence_config_rest_flattened(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(request={"resource": "sample1"}) + # 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 = storage_control.IntelligenceConfig() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest(**{"resource": "sample1"}) - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "folders/sample1/locations/sample2/intelligenceConfig" + } - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # 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 = storage_control.IntelligenceConfig.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_folder_intelligence_config(**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=folders/*/locations/*/intelligenceConfig}" + % client.transport._host, + args[1], ) -def test_set_iam_policy_routing_parameters_request_2_grpc(): +def test_get_folder_intelligence_config_rest_flattened_error(transport: str = "rest"): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy( - request={"resource": "projects/sample1/buckets/sample2/sample3"} + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_folder_intelligence_config( + storage_control.GetFolderIntelligenceConfigRequest(), + name="name_value", ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest( - **{"resource": "projects/sample1/buckets/sample2/sample3"} + +def test_update_folder_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.update_folder_intelligence_config + 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_folder_intelligence_config + ] = mock_rpc -def test_test_iam_permissions_routing_parameters_request_1_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + client.update_folder_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(request={"resource": "sample1"}) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "sample1"} - ) - assert args[0] == request_msg + client.update_folder_intelligence_config(request) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_test_iam_permissions_routing_parameters_request_2_grpc(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_update_folder_intelligence_config_rest_required_fields( + request_type=storage_control.UpdateFolderIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions( - request={"resource": "projects/sample1/buckets/sample2/objects/sample3"} - ) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "projects/sample1/buckets/sample2/objects/sample3"} - ) - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_folder_intelligence_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_folder_intelligence_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", ) + ) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone -def test_test_iam_permissions_routing_parameters_request_3_grpc(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions( - request={ - "resource": "projects/sample1/buckets/sample2/managedFolders/sample3" + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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, } - ) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "projects/sample1/buckets/sample2/managedFolders/sample3"} - ) - assert args[0] == request_msg + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_transport_kind_grpc_asyncio(): - transport = StorageControlAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + response_value._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_folder_intelligence_config(request) -def test_initialize_client_w_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_folder_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.Folder( - name="name_value", - metageneration=1491, + unset_fields = ( + transport.update_folder_intelligence_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", ) ) - await client.create_folder(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.CreateFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + & set( + ( + "intelligenceConfig", + "updateMask", + ) + ) + ) -# 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_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_folder_intelligence_config_rest_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_folder(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # 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 = storage_control.IntelligenceConfig() + # get arguments that satisfy an http rule for this method + sample_request = { + "intelligence_config": { + "name": "folders/sample1/locations/sample2/intelligenceConfig" + } + } -# 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_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.Folder( - name="name_value", - metageneration=1491, - ) + # get truthy value for each flattened field + mock_args = dict( + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.get_folder(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + 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 = storage_control.IntelligenceConfig.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"} -# 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_folders_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.update_folder_intelligence_config(**mock_args) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListFoldersResponse( - next_page_token="next_page_token_value", - ) + # 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/{intelligence_config.name=folders/*/locations/*/intelligenceConfig}" + % client.transport._host, + args[1], ) - await client.list_folders(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListFoldersRequest() - assert args[0] == request_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_rename_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_folder_intelligence_config_rest_flattened_error( + transport: str = "rest", +): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.rename_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_folder_intelligence_config( + storage_control.UpdateFolderIntelligenceConfigRequest(), + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.rename_folder(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.RenameFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_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_folder_recursive_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder_recursive), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") +def test_get_organization_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.delete_folder_recursive(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRecursiveRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_storage_layout_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert ( + client._transport.get_organization_intelligence_config + in client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_storage_layout), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.StorageLayout( - name="name_value", - location="location_value", - location_type="location_type_value", - ) + # 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. ) - await client.get_storage_layout(request=None) + client._transport._wrapped_methods[ + client._transport.get_organization_intelligence_config + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetStorageLayoutRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + request = {} + client.get_organization_intelligence_config(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_managed_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.get_organization_intelligence_config(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ManagedFolder( - name="name_value", - metageneration=1491, - ) - ) - await client.create_managed_folder(request=None) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.CreateManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg +def test_get_organization_intelligence_config_rest_required_fields( + request_type=storage_control.GetOrganizationIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport -# 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_managed_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_managed_folder(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DeleteManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_organization_intelligence_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_managed_folder_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ManagedFolder( - name="name_value", - metageneration=1491, - ) - ) - await client.get_managed_folder(request=None) + jsonified_request["name"] = "name_value" - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetManagedFolderRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_organization_intelligence_config._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" -# 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_managed_folders_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_managed_folders), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListManagedFoldersResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_managed_folders(request=None) + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListManagedFoldersRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -# 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_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_anywhere_cache), "__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_anywhere_cache(request=None) + response = client.get_organization_intelligence_config(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.CreateAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_organization_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_anywhere_cache), "__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.update_anywhere_cache(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = ( + transport.get_organization_intelligence_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) -# 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_disable_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_organization_intelligence_config_rest_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) - ) - await client.disable_anywhere_cache(request=None) + # 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 = storage_control.IntelligenceConfig() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.DisableAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/intelligenceConfig" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) -# 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_pause_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.pause_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) + client.get_organization_intelligence_config(**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=organizations/*/locations/*/intelligenceConfig}" + % client.transport._host, + args[1], ) - await client.pause_anywhere_cache(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.PauseAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg +def test_get_organization_intelligence_config_rest_flattened_error( + transport: str = "rest", +): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -# 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_resume_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.resume_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_organization_intelligence_config( + storage_control.GetOrganizationIntelligenceConfigRequest(), + name="name_value", ) - await client.resume_anywhere_cache(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ResumeAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg +def test_update_organization_intelligence_config_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_anywhere_cache_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) + # Ensure method has been cached + assert ( + client._transport.update_organization_intelligence_config + in client._transport._wrapped_methods ) - await client.get_anywhere_cache(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetAnywhereCacheRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # 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_organization_intelligence_config + ] = mock_rpc + request = {} + client.update_organization_intelligence_config(request) -# 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_anywhere_caches_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_anywhere_caches), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListAnywhereCachesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_anywhere_caches(request=None) + client.update_organization_intelligence_config(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.ListAnywhereCachesRequest() - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# 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_project_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_organization_intelligence_config_rest_required_fields( + request_type=storage_control.UpdateOrganizationIntelligenceConfigRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_project_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, - ) - ) - await client.get_project_intelligence_config(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetProjectIntelligenceConfigRequest() - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_organization_intelligence_config._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_project_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_organization_intelligence_config._get_unset_required_fields( + jsonified_request ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_project_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, - ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", ) - await client.update_project_intelligence_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateProjectIntelligenceConfigRequest() - assert args[0] == request_msg + ) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone -# 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_folder_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_folder_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, - ) - ) - await client.get_folder_intelligence_config(request=None) + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceConfig() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetFolderIntelligenceConfigRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -# 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_folder_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_folder_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, - ) - ) - await client.update_folder_intelligence_config(request=None) + response = client.update_organization_intelligence_config(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateFolderIntelligenceConfigRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_organization_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_organization_intelligence_config_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + unset_fields = ( + transport.update_organization_intelligence_config._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", ) ) - await client.get_organization_intelligence_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.GetOrganizationIntelligenceConfigRequest() - assert args[0] == request_msg + & set( + ( + "intelligenceConfig", + "updateMask", + ) + ) + ) -# 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_organization_intelligence_config_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_organization_intelligence_config_rest_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_intelligence_config), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, - ) - ) - await client.update_organization_intelligence_config(request=None) + # 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 = storage_control.IntelligenceConfig() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = storage_control.UpdateOrganizationIntelligenceConfigRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "intelligence_config": { + "name": "organizations/sample1/locations/sample2/intelligenceConfig" + } + } + # get truthy value for each flattened field + mock_args = dict( + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) -# 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_iam_policy_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.get_iam_policy(request=None) + client.update_organization_intelligence_config(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest() - assert args[0] == request_msg + # 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/{intelligence_config.name=organizations/*/locations/*/intelligenceConfig}" + % client.transport._host, + args[1], + ) -# 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_set_iam_policy_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_organization_intelligence_config_rest_flattened_error( + transport: str = "rest", +): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_organization_intelligence_config( + storage_control.UpdateOrganizationIntelligenceConfigRequest(), + intelligence_config=storage_control.IntelligenceConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.set_iam_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest() - assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_test_iam_permissions_empty_call_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_iam_policy_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = iam_policy_pb2.GetIamPolicyRequest() + with pytest.raises(RuntimeError): + client.get_iam_policy(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - await client.test_iam_permissions(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest() - assert args[0] == request_msg +def test_set_iam_policy_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = iam_policy_pb2.SetIamPolicyRequest() + with pytest.raises(RuntimeError): + client.set_iam_policy(request) -@pytest.mark.asyncio -async def test_create_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_test_iam_permissions_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = iam_policy_pb2.TestIamPermissionsRequest() + with pytest.raises(RuntimeError): + client.test_iam_permissions(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.Folder( - name="name_value", - metageneration=1491, - ) + +def test_get_intelligence_finding_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.create_folder(request={"parent": "sample1"}) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateFolderRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - expected_headers = {"bucket": "sample1"} + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.get_intelligence_finding + 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_intelligence_finding + ] = mock_rpc -@pytest.mark.asyncio -async def test_delete_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = {} + client.get_intelligence_finding(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.get_intelligence_finding(request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # 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_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_intelligence_finding_rest_required_fields( + request_type=storage_control.GetIntelligenceFindingRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_folder), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.Folder( - name="name_value", - metageneration=1491, - ) - ) - await client.get_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_intelligence_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" -@pytest.mark.asyncio -async def test_list_folders_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_intelligence_finding._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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_folders), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListFoldersResponse( - next_page_token="next_page_token_value", - ) - ) - await client.list_folders(request={"parent": "sample1"}) + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceFinding() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListFoldersRequest(**{"parent": "sample1"}) - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Convert return value to protobuf type + return_value = storage_control.IntelligenceFinding.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"} -@pytest.mark.asyncio -async def test_rename_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response = client.get_intelligence_finding(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.rename_folder), "__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.rename_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.RenameFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_get_intelligence_finding_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.get_intelligence_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -@pytest.mark.asyncio -async def test_delete_folder_recursive_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_get_intelligence_finding_rest_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_folder_recursive), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.delete_folder_recursive( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # 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 = storage_control.IntelligenceFinding() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteFolderRecursiveRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/intelligenceFindings/sample3" + } - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # 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 = storage_control.IntelligenceFinding.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"} -@pytest.mark.asyncio -async def test_get_storage_layout_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.get_intelligence_finding(**mock_args) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_storage_layout), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.StorageLayout( - name="name_value", - location="location_value", - location_type="location_type_value", - ) + # 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/*/intelligenceFindings/*}" + % client.transport._host, + args[1], ) - await client.get_storage_layout( - request={"name": "projects/sample1/buckets/sample2/sample3"} + + +def test_get_intelligence_finding_rest_flattened_error(transport: str = "rest"): + client = StorageControlClient( + 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_intelligence_finding( + storage_control.GetIntelligenceFindingRequest(), + name="name_value", ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetStorageLayoutRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + +def test_list_intelligence_findings_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.list_intelligence_findings + 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_intelligence_findings + ] = mock_rpc -@pytest.mark.asyncio -async def test_create_managed_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = {} + client.list_intelligence_findings(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ManagedFolder( - name="name_value", - metageneration=1491, - ) - ) - await client.create_managed_folder(request={"parent": "sample1"}) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateManagedFolderRequest( - **{"parent": "sample1"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.list_intelligence_findings(request) - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # 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_managed_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_intelligence_findings_rest_required_fields( + request_type=storage_control.ListIntelligenceFindingsRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_managed_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DeleteManagedFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_intelligence_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_intelligence_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", ) + ) + 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" -@pytest.mark.asyncio -async def test_get_managed_folder_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_managed_folder), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ManagedFolder( - name="name_value", - metageneration=1491, + # Designate an appropriate value for the returned response. + return_value = storage_control.ListIntelligenceFindingsResponse() + # 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 = storage_control.ListIntelligenceFindingsResponse.pb( + return_value ) - ) - await client.get_managed_folder( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + json_return_value = json_format.MessageToJson(return_value) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetManagedFolderRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + response = client.list_intelligence_findings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -@pytest.mark.asyncio -async def test_list_managed_folders_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_intelligence_findings_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_managed_folders), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListManagedFoldersResponse( - next_page_token="next_page_token_value", + unset_fields = transport.list_intelligence_findings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", ) ) - await client.list_managed_folders(request={"parent": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListManagedFoldersRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + & set(("parent",)) + ) -@pytest.mark.asyncio -async def test_create_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_intelligence_findings_rest_flattened(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_anywhere_cache), "__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_anywhere_cache(request={"parent": "sample1"}) + # 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 = storage_control.ListIntelligenceFindingsResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.CreateAnywhereCacheRequest( - **{"parent": "sample1"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # 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 = storage_control.ListIntelligenceFindingsResponse.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"} -@pytest.mark.asyncio -async def test_update_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.list_intelligence_findings(**mock_args) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_anywhere_cache), "__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.update_anywhere_cache( - request={ - "anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"} - } + # 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/*}/intelligenceFindings" + % client.transport._host, + args[1], ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.UpdateAnywhereCacheRequest( - **{"anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"}} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] +def test_list_intelligence_findings_rest_flattened_error(transport: str = "rest"): + client = StorageControlClient( + 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_intelligence_findings( + storage_control.ListIntelligenceFindingsRequest(), + parent="parent_value", ) -@pytest.mark.asyncio -async def test_disable_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_intelligence_findings_rest_pager(transport: str = "rest"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) - ) - await client.disable_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} + # 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 = ( + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingsResponse( + intelligence_findings=[ + storage_control.IntelligenceFinding(), + storage_control.IntelligenceFinding(), + ], + ), ) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.DisableAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + # Wrap the values into proper Response objs + response = tuple( + storage_control.ListIntelligenceFindingsResponse.to_json(x) + for x in response ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + 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 - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + sample_request = {"parent": "projects/sample1/locations/sample2"} + pager = client.list_intelligence_findings(request=sample_request) -@pytest.mark.asyncio -async def test_pause_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storage_control.IntelligenceFinding) for i in results) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.pause_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) - ) - await client.pause_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + pages = list(client.list_intelligence_findings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.PauseAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} + +def test_summarize_intelligence_findings_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.summarize_intelligence_findings + 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.summarize_intelligence_findings + ] = mock_rpc -@pytest.mark.asyncio -async def test_resume_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = {} + client.summarize_intelligence_findings(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.resume_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) - ) - await client.resume_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ResumeAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + client.summarize_intelligence_findings(request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # 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_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_summarize_intelligence_findings_rest_required_fields( + request_type=storage_control.SummarizeIntelligenceFindingsRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_anywhere_cache), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.AnywhereCache( - name="name_value", - zone="zone_value", - admission_policy="admission_policy_value", - state="state_value", - pending_update=True, - ) - ) - await client.get_anywhere_cache( - request={"name": "projects/sample1/buckets/sample2/sample3"} - ) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.GetAnywhereCacheRequest( - **{"name": "projects/sample1/buckets/sample2/sample3"} - ) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).summarize_intelligence_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).summarize_intelligence_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "resource_scope", ) + ) + 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" -@pytest.mark.asyncio -async def test_list_anywhere_caches_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_anywhere_caches), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - storage_control.ListAnywhereCachesResponse( - next_page_token="next_page_token_value", + # Designate an appropriate value for the returned response. + return_value = storage_control.SummarizeIntelligenceFindingsResponse() + # 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 = storage_control.SummarizeIntelligenceFindingsResponse.pb( + return_value ) - ) - await client.list_anywhere_caches(request={"parent": "sample1"}) + json_return_value = json_format.MessageToJson(return_value) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = storage_control.ListAnywhereCachesRequest(**{"parent": "sample1"}) - # Ensure that the uuid4 field is set according to AIP 4235 - assert _UUID4_RE.fullmatch(args[0].request_id) - request_msg.request_id = args[0].request_id - assert args[0] == request_msg + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + response = client.summarize_intelligence_findings(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -@pytest.mark.asyncio -async def test_get_iam_policy_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_summarize_intelligence_findings_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", + unset_fields = transport.summarize_intelligence_findings._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "resourceScope", ) ) - await client.get_iam_policy(request={"resource": "sample1"}) + & set(("parent",)) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest(**{"resource": "sample1"}) - assert args[0] == request_msg - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) +def test_summarize_intelligence_findings_rest_flattened(): + client = StorageControlClient( + 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 = storage_control.SummarizeIntelligenceFindingsResponse() -@pytest.mark.asyncio -async def test_get_iam_policy_routing_parameters_request_2_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.get_iam_policy( - request={"resource": "projects/sample1/buckets/sample2/sample3"} + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.GetIamPolicyRequest( - **{"resource": "projects/sample1/buckets/sample2/sample3"} + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = storage_control.SummarizeIntelligenceFindingsResponse.pb( + return_value ) - assert args[0] == request_msg + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client.summarize_intelligence_findings(**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/*}/intelligenceFindings:summarize" + % client.transport._host, + args[1], ) -@pytest.mark.asyncio -async def test_set_iam_policy_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_summarize_intelligence_findings_rest_flattened_error(transport: str = "rest"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.set_iam_policy(request={"resource": "sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest(**{"resource": "sample1"}) - assert args[0] == request_msg - - expected_headers = {"bucket": "sample1"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.summarize_intelligence_findings( + storage_control.SummarizeIntelligenceFindingsRequest(), + parent="parent_value", ) -@pytest.mark.asyncio -async def test_set_iam_policy_routing_parameters_request_2_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_summarize_intelligence_findings_rest_pager(transport: str = "rest"): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy( - version=774, - etag=b"etag_blob", - ) - ) - await client.set_iam_policy( - request={"resource": "projects/sample1/buckets/sample2/sample3"} + # 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 = ( + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + next_page_token="abc", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[], + next_page_token="def", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + ], + next_page_token="ghi", + ), + storage_control.SummarizeIntelligenceFindingsResponse( + finding_summaries=[ + storage_control.FindingSummary(), + storage_control.FindingSummary(), + ], + ), ) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.SetIamPolicyRequest( - **{"resource": "projects/sample1/buckets/sample2/sample3"} + # Wrap the values into proper Response objs + response = tuple( + storage_control.SummarizeIntelligenceFindingsResponse.to_json(x) + for x in response ) - assert args[0] == request_msg + 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 - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + sample_request = {"parent": "projects/sample1/locations/sample2"} + pager = client.summarize_intelligence_findings(request=sample_request) -@pytest.mark.asyncio -async def test_test_iam_permissions_routing_parameters_request_1_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, storage_control.FindingSummary) for i in results) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) + pages = list( + client.summarize_intelligence_findings(request=sample_request).pages ) - await client.test_iam_permissions(request={"resource": "sample1"}) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "sample1"} + +def test_get_intelligence_finding_revision_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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert args[0] == request_msg - expected_headers = {"bucket": "sample1"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + client._transport.get_intelligence_finding_revision + 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_intelligence_finding_revision + ] = mock_rpc -@pytest.mark.asyncio -async def test_test_iam_permissions_routing_parameters_request_2_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + request = {} + client.get_intelligence_finding_revision(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - await client.test_iam_permissions( - request={"resource": "projects/sample1/buckets/sample2/objects/sample3"} - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "projects/sample1/buckets/sample2/objects/sample3"} - ) - assert args[0] == request_msg + client.get_intelligence_finding_revision(request) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -@pytest.mark.asyncio -async def test_test_iam_permissions_routing_parameters_request_3_grpc_asyncio(): - client = StorageControlAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_intelligence_finding_revision_rest_required_fields( + request_type=storage_control.GetIntelligenceFindingRevisionRequest, +): + transport_class = transports.StorageControlRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - ) - await client.test_iam_permissions( - request={ - "resource": "projects/sample1/buckets/sample2/managedFolders/sample3" - } - ) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest( - **{"resource": "projects/sample1/buckets/sample2/managedFolders/sample3"} - ) - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_intelligence_finding_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - expected_headers = {"bucket": "projects/sample1/buckets/sample2"} - assert ( - gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] - ) + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" -def test_transport_kind_rest(): - transport = StorageControlClient.get_transport_class("rest")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + ).get_intelligence_finding_revision._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" -def test_create_folder_rest_error(): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_folder({}) - assert "Method CreateFolder is not available over REST transport" in str( - not_implemented_error.value + # Designate an appropriate value for the returned response. + return_value = storage_control.IntelligenceFindingRevision() + # 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 = storage_control.IntelligenceFindingRevision.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_intelligence_finding_revision(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_intelligence_finding_revision_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_intelligence_finding_revision._get_unset_required_fields({}) ) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_folder_rest_error(): +def test_get_intelligence_finding_revision_rest_flattened(): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_folder({}) - assert "Method DeleteFolder is not available over REST transport" in str( - not_implemented_error.value - ) + # 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 = storage_control.IntelligenceFindingRevision() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/intelligenceFindings/sample3/revisions/sample4" + } -def test_get_folder_rest_error(): + # 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 = storage_control.IntelligenceFindingRevision.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_intelligence_finding_revision(**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/*/intelligenceFindings/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_intelligence_finding_revision_rest_flattened_error( + transport: str = "rest", +): client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_folder({}) - assert "Method GetFolder is not available over REST transport" in str( - not_implemented_error.value + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_intelligence_finding_revision( + storage_control.GetIntelligenceFindingRevisionRequest(), + name="name_value", + ) + + +def test_list_intelligence_finding_revisions_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 = StorageControlClient( + 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_intelligence_finding_revisions + 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_intelligence_finding_revisions + ] = mock_rpc + + request = {} + client.list_intelligence_finding_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_intelligence_finding_revisions(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_intelligence_finding_revisions_rest_required_fields( + request_type=storage_control.ListIntelligenceFindingRevisionsRequest, +): + transport_class = transports.StorageControlRestTransport + + 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_intelligence_finding_revisions._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_intelligence_finding_revisions._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 = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = storage_control.ListIntelligenceFindingRevisionsResponse() + # 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 = storage_control.ListIntelligenceFindingRevisionsResponse.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_intelligence_finding_revisions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_intelligence_finding_revisions_rest_unset_required_fields(): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_intelligence_finding_revisions._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_intelligence_finding_revisions_rest_flattened(): + client = StorageControlClient( + 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 = storage_control.ListIntelligenceFindingRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/intelligenceFindings/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 = storage_control.ListIntelligenceFindingRevisionsResponse.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_intelligence_finding_revisions(**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/*/intelligenceFindings/*}/revisions" + % client.transport._host, + args[1], + ) + + +def test_list_intelligence_finding_revisions_rest_flattened_error( + transport: str = "rest", +): + client = StorageControlClient( + 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_intelligence_finding_revisions( + storage_control.ListIntelligenceFindingRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_intelligence_finding_revisions_rest_pager(transport: str = "rest"): + client = StorageControlClient( + 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 = ( + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="abc", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[], + next_page_token="def", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + ], + next_page_token="ghi", + ), + storage_control.ListIntelligenceFindingRevisionsResponse( + intelligence_finding_revisions=[ + storage_control.IntelligenceFindingRevision(), + storage_control.IntelligenceFindingRevision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + storage_control.ListIntelligenceFindingRevisionsResponse.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/intelligenceFindings/sample3" + } + + pager = client.list_intelligence_finding_revisions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, storage_control.IntelligenceFindingRevision) for i in results + ) + + pages = list( + client.list_intelligence_finding_revisions(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_folder({}) + assert "Method CreateFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_folder({}) + assert "Method DeleteFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_folder({}) + assert "Method GetFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_folders_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_folders({}) + assert "Method ListFolders is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_rename_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.rename_folder({}) + assert "Method RenameFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_folder_recursive_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_folder_recursive({}) + assert "Method DeleteFolderRecursive is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_storage_layout_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_storage_layout({}) + assert "Method GetStorageLayout is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_create_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_managed_folder({}) + assert "Method CreateManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_managed_folder({}) + assert "Method DeleteManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_managed_folder({}) + assert "Method GetManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_managed_folders_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_managed_folders({}) + assert "Method ListManagedFolders is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_create_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_anywhere_cache({}) + assert "Method CreateAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_update_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.update_anywhere_cache({}) + assert "Method UpdateAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_disable_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.disable_anywhere_cache({}) + assert "Method DisableAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_pause_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.pause_anywhere_cache({}) + assert "Method PauseAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_resume_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.resume_anywhere_cache({}) + assert "Method ResumeAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_anywhere_cache({}) + assert "Method GetAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_anywhere_caches_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_anywhere_caches({}) + assert "Method ListAnywhereCaches is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_iam_policy_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_iam_policy({}) + assert "Method GetIamPolicy is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_set_iam_policy_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.set_iam_policy({}) + assert "Method SetIamPolicy is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_test_iam_permissions_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.test_iam_permissions({}) + assert "Method TestIamPermissions is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageControlClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = StorageControlClient( + 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 = StorageControlClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = StorageControlClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = StorageControlClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.StorageControlGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.StorageControlGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.StorageControlGrpcTransport, + transports.StorageControlGrpcAsyncIOTransport, + transports.StorageControlRestTransport, + ], +) +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 = StorageControlClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = StorageControlClient( + 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_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + call.return_value = storage_control.Folder() + client.create_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + call.return_value = None + client.delete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + call.return_value = storage_control.Folder() + client.get_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folders_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + call.return_value = storage_control.ListFoldersResponse() + client.list_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListFoldersRequest() + assert args[0] == request_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_rename_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rename_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.rename_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.RenameFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_recursive_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder_recursive), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_folder_recursive(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRecursiveRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_storage_layout_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_storage_layout), "__call__" + ) as call: + call.return_value = storage_control.StorageLayout() + client.get_storage_layout(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetStorageLayoutRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_managed_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_managed_folder), "__call__" + ) as call: + call.return_value = storage_control.ManagedFolder() + client.create_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_managed_folder), "__call__" + ) as call: + call.return_value = None + client.delete_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folder_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_managed_folder), "__call__" + ) as call: + call.return_value = storage_control.ManagedFolder() + client.get_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folders_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_managed_folders), "__call__" + ) as call: + call.return_value = storage_control.ListManagedFoldersResponse() + client.list_managed_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListManagedFoldersRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_anywhere_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_anywhere_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_disable_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.disable_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_pause_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.pause_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.pause_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.PauseAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_resume_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.resume_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.resume_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ResumeAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_cache_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.get_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_caches_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_anywhere_caches), "__call__" + ) as call: + call.return_value = storage_control.ListAnywhereCachesResponse() + client.list_anywhere_caches(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListAnywhereCachesRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_project_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_project_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.get_project_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetProjectIntelligenceConfigRequest() + assert args[0] == request_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_project_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_project_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.update_project_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateProjectIntelligenceConfigRequest() + assert args[0] == request_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_folder_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_folder_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.get_folder_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetFolderIntelligenceConfigRequest() + assert args[0] == request_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_folder_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_folder_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.update_folder_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateFolderIntelligenceConfigRequest() + assert args[0] == request_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_organization_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.get_organization_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetOrganizationIntelligenceConfigRequest() + assert args[0] == request_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_organization_intelligence_config_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_intelligence_config), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceConfig() + client.update_organization_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateOrganizationIntelligenceConfigRequest() + assert args[0] == request_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_iam_policy_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_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_set_iam_policy_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_iam_permissions_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_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_intelligence_finding_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceFinding() + client.get_intelligence_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRequest() + assert args[0] == request_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_intelligence_findings_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + call.return_value = storage_control.ListIntelligenceFindingsResponse() + client.list_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingsRequest() + assert args[0] == request_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_summarize_intelligence_findings_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + call.return_value = storage_control.SummarizeIntelligenceFindingsResponse() + client.summarize_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.SummarizeIntelligenceFindingsRequest() + assert args[0] == request_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_intelligence_finding_revision_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + call.return_value = storage_control.IntelligenceFindingRevision() + client.get_intelligence_finding_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRevisionRequest() + assert args[0] == request_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_intelligence_finding_revisions_empty_call_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_finding_revisions), "__call__" + ) as call: + call.return_value = storage_control.ListIntelligenceFindingRevisionsResponse() + client.list_intelligence_finding_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingRevisionsRequest() + assert args[0] == request_msg + + +def test_create_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + call.return_value = storage_control.Folder() + client.create_folder(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateFolderRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + call.return_value = None + client.delete_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + call.return_value = storage_control.Folder() + client.get_folder(request={"name": "projects/sample1/buckets/sample2/sample3"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_folders_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + call.return_value = storage_control.ListFoldersResponse() + client.list_folders(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListFoldersRequest(**{"parent": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_rename_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rename_folder), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.rename_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.RenameFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_folder_recursive_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder_recursive), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_folder_recursive( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRecursiveRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_storage_layout_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_storage_layout), "__call__" + ) as call: + call.return_value = storage_control.StorageLayout() + client.get_storage_layout( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetStorageLayoutRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_create_managed_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_managed_folder), "__call__" + ) as call: + call.return_value = storage_control.ManagedFolder() + client.create_managed_folder(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateManagedFolderRequest( + **{"parent": "sample1"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_delete_managed_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_managed_folder), "__call__" + ) as call: + call.return_value = None + client.delete_managed_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteManagedFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_managed_folder_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_managed_folder), "__call__" + ) as call: + call.return_value = storage_control.ManagedFolder() + client.get_managed_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetManagedFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_managed_folders_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_managed_folders), "__call__" + ) as call: + call.return_value = storage_control.ListManagedFoldersResponse() + client.list_managed_folders(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListManagedFoldersRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_create_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_anywhere_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_anywhere_cache(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateAnywhereCacheRequest( + **{"parent": "sample1"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_update_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_anywhere_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_anywhere_cache( + request={ + "anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"} + } + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.UpdateAnywhereCacheRequest( + **{"anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"}} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_disable_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.disable_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DisableAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_pause_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.pause_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.pause_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.PauseAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_resume_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.resume_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.resume_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ResumeAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_anywhere_cache_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_anywhere_cache), "__call__" + ) as call: + call.return_value = storage_control.AnywhereCache() + client.get_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_list_anywhere_caches_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_anywhere_caches), "__call__" + ) as call: + call.return_value = storage_control.ListAnywhereCachesResponse() + client.list_anywhere_caches(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListAnywhereCachesRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_iam_policy_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest(**{"resource": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_get_iam_policy_routing_parameters_request_2_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy( + request={"resource": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest( + **{"resource": "projects/sample1/buckets/sample2/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_set_iam_policy_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest(**{"resource": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_set_iam_policy_routing_parameters_request_2_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy( + request={"resource": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest( + **{"resource": "projects/sample1/buckets/sample2/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_test_iam_permissions_routing_parameters_request_1_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "sample1"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_test_iam_permissions_routing_parameters_request_2_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions( + request={"resource": "projects/sample1/buckets/sample2/objects/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "projects/sample1/buckets/sample2/objects/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_test_iam_permissions_routing_parameters_request_3_grpc(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions( + request={ + "resource": "projects/sample1/buckets/sample2/managedFolders/sample3" + } + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "projects/sample1/buckets/sample2/managedFolders/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_grpc_asyncio(): + transport = StorageControlAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = StorageControlAsyncClient( + 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_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.Folder( + name="name_value", + metageneration=1491, + ) + ) + await client.create_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.Folder( + name="name_value", + metageneration=1491, + ) + ) + await client.get_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folders_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListFoldersRequest() + assert args[0] == request_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_rename_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rename_folder), "__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.rename_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.RenameFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_folder_recursive_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder_recursive), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_folder_recursive(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRecursiveRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_storage_layout_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_storage_layout), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.StorageLayout( + name="name_value", + location="location_value", + location_type="location_type_value", + ) + ) + await client.get_storage_layout(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetStorageLayoutRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_managed_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ManagedFolder( + name="name_value", + metageneration=1491, + ) + ) + await client.create_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DeleteManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folder_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ManagedFolder( + name="name_value", + metageneration=1491, + ) + ) + await client.get_managed_folder(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetManagedFolderRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_managed_folders_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_managed_folders), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListManagedFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_managed_folders(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListManagedFoldersRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_anywhere_cache), "__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_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.CreateAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_anywhere_cache), "__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.update_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_disable_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.disable_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_pause_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.pause_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.pause_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.PauseAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_resume_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.resume_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.resume_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ResumeAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_cache_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.get_anywhere_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetAnywhereCacheRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_anywhere_caches_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_anywhere_caches), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListAnywhereCachesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_anywhere_caches(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListAnywhereCachesRequest() + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_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_project_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_project_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.get_project_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetProjectIntelligenceConfigRequest() + assert args[0] == request_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_project_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_project_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.update_project_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateProjectIntelligenceConfigRequest() + assert args[0] == request_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_folder_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_folder_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.get_folder_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetFolderIntelligenceConfigRequest() + assert args[0] == request_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_folder_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_folder_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.update_folder_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateFolderIntelligenceConfigRequest() + assert args[0] == request_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_organization_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.get_organization_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetOrganizationIntelligenceConfigRequest() + assert args[0] == request_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_organization_intelligence_config_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_intelligence_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + ) + await client.update_organization_intelligence_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.UpdateOrganizationIntelligenceConfigRequest() + assert args[0] == request_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_iam_policy_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request_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_set_iam_policy_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request_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_intelligence_finding_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFinding( + name="name_value", + description="description_value", + type_=storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE, + category=storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT, + severity=storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL, + target_resource="target_resource_value", + associated_resources=["associated_resources_value"], + ) + ) + await client.get_intelligence_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRequest() + assert args[0] == request_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_intelligence_findings_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingsRequest() + assert args[0] == request_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_summarize_intelligence_findings_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.SummarizeIntelligenceFindingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.summarize_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.SummarizeIntelligenceFindingsRequest() + assert args[0] == request_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_intelligence_finding_revision_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.IntelligenceFindingRevision( + name="name_value", + ) + ) + await client.get_intelligence_finding_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRevisionRequest() + assert args[0] == request_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_intelligence_finding_revisions_empty_call_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_finding_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListIntelligenceFindingRevisionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_intelligence_finding_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingRevisionsRequest() + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.Folder( + name="name_value", + metageneration=1491, + ) + ) + await client.create_folder(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateFolderRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_folder), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.Folder( + name="name_value", + metageneration=1491, + ) + ) + await client.get_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_folders_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_folders), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_folders(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListFoldersRequest(**{"parent": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_rename_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rename_folder), "__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.rename_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.RenameFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_folder_recursive_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_folder_recursive), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_folder_recursive( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteFolderRecursiveRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_storage_layout_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_storage_layout), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.StorageLayout( + name="name_value", + location="location_value", + location_type="location_type_value", + ) + ) + await client.get_storage_layout( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetStorageLayoutRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_create_managed_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ManagedFolder( + name="name_value", + metageneration=1491, + ) + ) + await client.create_managed_folder(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateManagedFolderRequest( + **{"parent": "sample1"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_delete_managed_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_managed_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DeleteManagedFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_managed_folder_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_managed_folder), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ManagedFolder( + name="name_value", + metageneration=1491, + ) + ) + await client.get_managed_folder( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetManagedFolderRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_managed_folders_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_managed_folders), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListManagedFoldersResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_managed_folders(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListManagedFoldersRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_create_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_anywhere_cache), "__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_anywhere_cache(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.CreateAnywhereCacheRequest( + **{"parent": "sample1"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_update_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_anywhere_cache), "__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.update_anywhere_cache( + request={ + "anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"} + } + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.UpdateAnywhereCacheRequest( + **{"anywhere_cache": {"name": "projects/sample1/buckets/sample2/sample3"}} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_disable_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.disable_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.DisableAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_pause_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.pause_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.pause_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.PauseAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_resume_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.resume_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.resume_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ResumeAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_anywhere_cache_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_anywhere_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.AnywhereCache( + name="name_value", + zone="zone_value", + admission_policy="admission_policy_value", + state="state_value", + pending_update=True, + ) + ) + await client.get_anywhere_cache( + request={"name": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.GetAnywhereCacheRequest( + **{"name": "projects/sample1/buckets/sample2/sample3"} + ) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_list_anywhere_caches_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_anywhere_caches), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + storage_control.ListAnywhereCachesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_anywhere_caches(request={"parent": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = storage_control.ListAnywhereCachesRequest(**{"parent": "sample1"}) + # Ensure that the uuid4 field is set according to AIP 4235 + assert _UUID4_RE.fullmatch(args[0].request_id) + request_msg.request_id = args[0].request_id + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest(**{"resource": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_routing_parameters_request_2_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.get_iam_policy( + request={"resource": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.GetIamPolicyRequest( + **{"resource": "projects/sample1/buckets/sample2/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest(**{"resource": "sample1"}) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_routing_parameters_request_2_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + await client.set_iam_policy( + request={"resource": "projects/sample1/buckets/sample2/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.SetIamPolicyRequest( + **{"resource": "projects/sample1/buckets/sample2/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_routing_parameters_request_1_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions(request={"resource": "sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "sample1"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "sample1"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_routing_parameters_request_2_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions( + request={"resource": "projects/sample1/buckets/sample2/objects/sample3"} + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "projects/sample1/buckets/sample2/objects/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_routing_parameters_request_3_grpc_asyncio(): + client = StorageControlAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + await client.test_iam_permissions( + request={ + "resource": "projects/sample1/buckets/sample2/managedFolders/sample3" + } + ) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest( + **{"resource": "projects/sample1/buckets/sample2/managedFolders/sample3"} + ) + assert args[0] == request_msg + + expected_headers = {"bucket": "projects/sample1/buckets/sample2"} + assert ( + gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw["metadata"] + ) + + +def test_transport_kind_rest(): + transport = StorageControlClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_folder({}) + assert "Method CreateFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_folder({}) + assert "Method DeleteFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_folder({}) + assert "Method GetFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_folders_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_folders({}) + assert "Method ListFolders is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_rename_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.rename_folder({}) + assert "Method RenameFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_folder_recursive_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_folder_recursive({}) + assert "Method DeleteFolderRecursive is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_storage_layout_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_storage_layout({}) + assert "Method GetStorageLayout is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_create_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_managed_folder({}) + assert "Method CreateManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_delete_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.delete_managed_folder({}) + assert "Method DeleteManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_managed_folder_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_managed_folder({}) + assert "Method GetManagedFolder is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_managed_folders_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_managed_folders({}) + assert "Method ListManagedFolders is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_create_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.create_anywhere_cache({}) + assert "Method CreateAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_update_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.update_anywhere_cache({}) + assert "Method UpdateAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_disable_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.disable_anywhere_cache({}) + assert "Method DisableAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_pause_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.pause_anywhere_cache({}) + assert "Method PauseAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_resume_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.resume_anywhere_cache({}) + assert "Method ResumeAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_anywhere_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_anywhere_cache({}) + assert "Method GetAnywhereCache is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_list_anywhere_caches_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.list_anywhere_caches({}) + assert "Method ListAnywhereCaches is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_project_intelligence_config_rest_bad_request( + request_type=storage_control.GetProjectIntelligenceConfigRequest, +): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/intelligenceConfig"} + 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_project_intelligence_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetProjectIntelligenceConfigRequest, + dict, + ], +) +def test_get_project_intelligence_config_rest_call_success(request_type): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/intelligenceConfig"} + 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 = storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + + # 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 = storage_control.IntelligenceConfig.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_project_intelligence_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceConfig) + assert response.name == "name_value" + assert ( + response.edition_config + == storage_control.IntelligenceConfig.EditionConfig.INHERIT + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_intelligence_config_rest_interceptors(null_interceptor): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.StorageControlRestInterceptor(), + ) + client = StorageControlClient(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.StorageControlRestInterceptor, + "post_get_project_intelligence_config", + ) as post, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_get_project_intelligence_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.StorageControlRestInterceptor, + "pre_get_project_intelligence_config", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = storage_control.GetProjectIntelligenceConfigRequest.pb( + storage_control.GetProjectIntelligenceConfigRequest() + ) + 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 = storage_control.IntelligenceConfig.to_json( + storage_control.IntelligenceConfig() + ) + req.return_value.content = return_value + + request = storage_control.GetProjectIntelligenceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storage_control.IntelligenceConfig() + post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata + + client.get_project_intelligence_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_project_intelligence_config_rest_bad_request( + request_type=storage_control.UpdateProjectIntelligenceConfigRequest, +): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "intelligence_config": { + "name": "projects/sample1/locations/sample2/intelligenceConfig" + } + } + 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_project_intelligence_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + storage_control.UpdateProjectIntelligenceConfigRequest, + dict, + ], +) +def test_update_project_intelligence_config_rest_call_success(request_type): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "intelligence_config": { + "name": "projects/sample1/locations/sample2/intelligenceConfig" + } + } + request_init["intelligence_config"] = { + "name": "projects/sample1/locations/sample2/intelligenceConfig", + "edition_config": 1, + "update_time": {"seconds": 751, "nanos": 543}, + "filter": { + "included_cloud_storage_locations": { + "locations": ["locations_value1", "locations_value2"] + }, + "excluded_cloud_storage_locations": {}, + "included_cloud_storage_buckets": { + "bucket_id_regexes": [ + "bucket_id_regexes_value1", + "bucket_id_regexes_value2", + ] + }, + "excluded_cloud_storage_buckets": {}, + }, + "effective_intelligence_config": { + "effective_edition": 1, + "intelligence_config": "intelligence_config_value", + }, + "trial_config": {"expire_time": {}}, + } + # 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 = storage_control.UpdateProjectIntelligenceConfigRequest.meta.fields[ + "intelligence_config" + ] + + 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["intelligence_config"].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["intelligence_config"][field])): + del request_init["intelligence_config"][field][i][subfield] + else: + del request_init["intelligence_config"][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 = storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) + + # 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 = storage_control.IntelligenceConfig.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_project_intelligence_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceConfig) + assert response.name == "name_value" + assert ( + response.edition_config + == storage_control.IntelligenceConfig.EditionConfig.INHERIT + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_project_intelligence_config_rest_interceptors(null_interceptor): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.StorageControlRestInterceptor(), ) + client = StorageControlClient(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.StorageControlRestInterceptor, + "post_update_project_intelligence_config", + ) as post, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_update_project_intelligence_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.StorageControlRestInterceptor, + "pre_update_project_intelligence_config", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = storage_control.UpdateProjectIntelligenceConfigRequest.pb( + storage_control.UpdateProjectIntelligenceConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -def test_list_folders_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_folders({}) - assert "Method ListFolders is not available over REST transport" in str( - not_implemented_error.value - ) + 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 = storage_control.IntelligenceConfig.to_json( + storage_control.IntelligenceConfig() + ) + req.return_value.content = return_value + request = storage_control.UpdateProjectIntelligenceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storage_control.IntelligenceConfig() + post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata -def test_rename_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.update_project_intelligence_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.rename_folder({}) - assert "Method RenameFolder is not available over REST transport" in str( - not_implemented_error.value - ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_delete_folder_recursive_rest_error(): +def test_get_folder_intelligence_config_rest_bad_request( + request_type=storage_control.GetFolderIntelligenceConfigRequest, +): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1/locations/sample2/intelligenceConfig"} + request = request_type(**request_init) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_folder_recursive({}) - assert "Method DeleteFolderRecursive is not available over REST transport" in str( - not_implemented_error.value - ) + # 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_folder_intelligence_config(request) -def test_get_storage_layout_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + storage_control.GetFolderIntelligenceConfigRequest, + dict, + ], +) +def test_get_folder_intelligence_config_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_storage_layout({}) - assert "Method GetStorageLayout is not available over REST transport" in str( - not_implemented_error.value - ) + # send a request that will satisfy transcoding + request_init = {"name": "folders/sample1/locations/sample2/intelligenceConfig"} + 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 = storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) -def test_create_managed_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_managed_folder({}) - assert "Method CreateManagedFolder is not available over REST transport" in str( - not_implemented_error.value + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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_folder_intelligence_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceConfig) + assert response.name == "name_value" + assert ( + response.edition_config + == storage_control.IntelligenceConfig.EditionConfig.INHERIT ) -def test_delete_managed_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_folder_intelligence_config_rest_interceptors(null_interceptor): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.StorageControlRestInterceptor(), ) + client = StorageControlClient(transport=transport) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.delete_managed_folder({}) - assert "Method DeleteManagedFolder is not available over REST transport" in str( - not_implemented_error.value - ) + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_get_folder_intelligence_config", + ) as post, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_get_folder_intelligence_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.StorageControlRestInterceptor, + "pre_get_folder_intelligence_config", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = storage_control.GetFolderIntelligenceConfigRequest.pb( + storage_control.GetFolderIntelligenceConfigRequest() + ) + 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 = storage_control.IntelligenceConfig.to_json( + storage_control.IntelligenceConfig() + ) + req.return_value.content = return_value -def test_get_managed_folder_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + request = storage_control.GetFolderIntelligenceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storage_control.IntelligenceConfig() + post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_managed_folder({}) - assert "Method GetManagedFolder is not available over REST transport" in str( - not_implemented_error.value - ) + client.get_folder_intelligence_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_managed_folders_rest_error(): +def test_update_folder_intelligence_config_rest_bad_request( + request_type=storage_control.UpdateFolderIntelligenceConfigRequest, +): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "intelligence_config": { + "name": "folders/sample1/locations/sample2/intelligenceConfig" + } + } + request = request_type(**request_init) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_managed_folders({}) - assert "Method ListManagedFolders is not available over REST transport" in str( - not_implemented_error.value - ) + # 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_folder_intelligence_config(request) -def test_create_anywhere_cache_rest_error(): +@pytest.mark.parametrize( + "request_type", + [ + storage_control.UpdateFolderIntelligenceConfigRequest, + dict, + ], +) +def test_update_folder_intelligence_config_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.create_anywhere_cache({}) - assert "Method CreateAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + # send a request that will satisfy transcoding + request_init = { + "intelligence_config": { + "name": "folders/sample1/locations/sample2/intelligenceConfig" + } + } + request_init["intelligence_config"] = { + "name": "folders/sample1/locations/sample2/intelligenceConfig", + "edition_config": 1, + "update_time": {"seconds": 751, "nanos": 543}, + "filter": { + "included_cloud_storage_locations": { + "locations": ["locations_value1", "locations_value2"] + }, + "excluded_cloud_storage_locations": {}, + "included_cloud_storage_buckets": { + "bucket_id_regexes": [ + "bucket_id_regexes_value1", + "bucket_id_regexes_value2", + ] + }, + "excluded_cloud_storage_buckets": {}, + }, + "effective_intelligence_config": { + "effective_edition": 1, + "intelligence_config": "intelligence_config_value", + }, + "trial_config": {"expire_time": {}}, + } + # 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 = storage_control.UpdateFolderIntelligenceConfigRequest.meta.fields[ + "intelligence_config" + ] -def test_update_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + 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 = [] - with pytest.raises(NotImplementedError) as not_implemented_error: - client.update_anywhere_cache({}) - assert "Method UpdateAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + 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 -def test_disable_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - with pytest.raises(NotImplementedError) as not_implemented_error: - client.disable_anywhere_cache({}) - assert "Method DisableAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + 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["intelligence_config"].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 -def test_pause_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + 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, + } + ) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.pause_anywhere_cache({}) - assert "Method PauseAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + # 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["intelligence_config"][field])): + del request_init["intelligence_config"][field][i][subfield] + else: + del request_init["intelligence_config"][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 = storage_control.IntelligenceConfig( + name="name_value", + edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + ) -def test_resume_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - with pytest.raises(NotImplementedError) as not_implemented_error: - client.resume_anywhere_cache({}) - assert "Method ResumeAnywhereCache is not available over REST transport" in str( - not_implemented_error.value + # Convert return value to protobuf type + return_value = storage_control.IntelligenceConfig.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_folder_intelligence_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, storage_control.IntelligenceConfig) + assert response.name == "name_value" + assert ( + response.edition_config + == storage_control.IntelligenceConfig.EditionConfig.INHERIT ) -def test_get_anywhere_cache_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_folder_intelligence_config_rest_interceptors(null_interceptor): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.StorageControlRestInterceptor(), ) + client = StorageControlClient(transport=transport) - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_anywhere_cache({}) - assert "Method GetAnywhereCache is not available over REST transport" in str( - not_implemented_error.value - ) + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_update_folder_intelligence_config", + ) as post, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_update_folder_intelligence_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.StorageControlRestInterceptor, + "pre_update_folder_intelligence_config", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = storage_control.UpdateFolderIntelligenceConfigRequest.pb( + storage_control.UpdateFolderIntelligenceConfigRequest() + ) + 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 = storage_control.IntelligenceConfig.to_json( + storage_control.IntelligenceConfig() + ) + req.return_value.content = return_value -def test_list_anywhere_caches_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + request = storage_control.UpdateFolderIntelligenceConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storage_control.IntelligenceConfig() + post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata - with pytest.raises(NotImplementedError) as not_implemented_error: - client.list_anywhere_caches({}) - assert "Method ListAnywhereCaches is not available over REST transport" in str( - not_implemented_error.value - ) + client.update_folder_intelligence_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_project_intelligence_config_rest_bad_request( - request_type=storage_control.GetProjectIntelligenceConfigRequest, +def test_get_organization_intelligence_config_rest_bad_request( + request_type=storage_control.GetOrganizationIntelligenceConfigRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/intelligenceConfig"} + request_init = { + "name": "organizations/sample1/locations/sample2/intelligenceConfig" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15583,23 +20180,25 @@ def test_get_project_intelligence_config_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_project_intelligence_config(request) + client.get_organization_intelligence_config(request) @pytest.mark.parametrize( "request_type", [ - storage_control.GetProjectIntelligenceConfigRequest, + storage_control.GetOrganizationIntelligenceConfigRequest, dict, ], ) -def test_get_project_intelligence_config_rest_call_success(request_type): +def test_get_organization_intelligence_config_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/intelligenceConfig"} + request_init = { + "name": "organizations/sample1/locations/sample2/intelligenceConfig" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -15620,7 +20219,7 @@ def test_get_project_intelligence_config_rest_call_success(request_type): response_value.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_project_intelligence_config(request) + response = client.get_organization_intelligence_config(request) # Establish that the response is the type that we expect. assert isinstance(response, storage_control.IntelligenceConfig) @@ -15632,7 +20231,7 @@ def test_get_project_intelligence_config_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_project_intelligence_config_rest_interceptors(null_interceptor): +def test_get_organization_intelligence_config_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15646,22 +20245,22 @@ def test_get_project_intelligence_config_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.StorageControlRestInterceptor, - "post_get_project_intelligence_config", + "post_get_organization_intelligence_config", ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_get_project_intelligence_config_with_metadata", + "post_get_organization_intelligence_config_with_metadata", ) as post_with_metadata, mock.patch.object( transports.StorageControlRestInterceptor, - "pre_get_project_intelligence_config", + "pre_get_organization_intelligence_config", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.GetProjectIntelligenceConfigRequest.pb( - storage_control.GetProjectIntelligenceConfigRequest() + pb_message = storage_control.GetOrganizationIntelligenceConfigRequest.pb( + storage_control.GetOrganizationIntelligenceConfigRequest() ) transcode.return_value = { "method": "post", @@ -15678,7 +20277,7 @@ def test_get_project_intelligence_config_rest_interceptors(null_interceptor): ) req.return_value.content = return_value - request = storage_control.GetProjectIntelligenceConfigRequest() + request = storage_control.GetOrganizationIntelligenceConfigRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15687,7 +20286,7 @@ def test_get_project_intelligence_config_rest_interceptors(null_interceptor): post.return_value = storage_control.IntelligenceConfig() post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata - client.get_project_intelligence_config( + client.get_organization_intelligence_config( request, metadata=[ ("key", "val"), @@ -15700,8 +20299,8 @@ def test_get_project_intelligence_config_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_project_intelligence_config_rest_bad_request( - request_type=storage_control.UpdateProjectIntelligenceConfigRequest, +def test_update_organization_intelligence_config_rest_bad_request( + request_type=storage_control.UpdateOrganizationIntelligenceConfigRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -15709,7 +20308,7 @@ def test_update_project_intelligence_config_rest_bad_request( # send a request that will satisfy transcoding request_init = { "intelligence_config": { - "name": "projects/sample1/locations/sample2/intelligenceConfig" + "name": "organizations/sample1/locations/sample2/intelligenceConfig" } } request = request_type(**request_init) @@ -15727,17 +20326,17 @@ def test_update_project_intelligence_config_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_project_intelligence_config(request) + client.update_organization_intelligence_config(request) @pytest.mark.parametrize( "request_type", [ - storage_control.UpdateProjectIntelligenceConfigRequest, + storage_control.UpdateOrganizationIntelligenceConfigRequest, dict, ], ) -def test_update_project_intelligence_config_rest_call_success(request_type): +def test_update_organization_intelligence_config_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15745,11 +20344,11 @@ def test_update_project_intelligence_config_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = { "intelligence_config": { - "name": "projects/sample1/locations/sample2/intelligenceConfig" + "name": "organizations/sample1/locations/sample2/intelligenceConfig" } } request_init["intelligence_config"] = { - "name": "projects/sample1/locations/sample2/intelligenceConfig", + "name": "organizations/sample1/locations/sample2/intelligenceConfig", "edition_config": 1, "update_time": {"seconds": 751, "nanos": 543}, "filter": { @@ -15776,9 +20375,11 @@ def test_update_project_intelligence_config_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = storage_control.UpdateProjectIntelligenceConfigRequest.meta.fields[ - "intelligence_config" - ] + test_field = ( + storage_control.UpdateOrganizationIntelligenceConfigRequest.meta.fields[ + "intelligence_config" + ] + ) def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -15860,7 +20461,7 @@ def get_message_fields(field): response_value.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_project_intelligence_config(request) + response = client.update_organization_intelligence_config(request) # Establish that the response is the type that we expect. assert isinstance(response, storage_control.IntelligenceConfig) @@ -15872,7 +20473,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_project_intelligence_config_rest_interceptors(null_interceptor): +def test_update_organization_intelligence_config_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15886,22 +20487,22 @@ def test_update_project_intelligence_config_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_project_intelligence_config", + "post_update_organization_intelligence_config", ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_project_intelligence_config_with_metadata", + "post_update_organization_intelligence_config_with_metadata", ) as post_with_metadata, mock.patch.object( transports.StorageControlRestInterceptor, - "pre_update_project_intelligence_config", + "pre_update_organization_intelligence_config", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.UpdateProjectIntelligenceConfigRequest.pb( - storage_control.UpdateProjectIntelligenceConfigRequest() + pb_message = storage_control.UpdateOrganizationIntelligenceConfigRequest.pb( + storage_control.UpdateOrganizationIntelligenceConfigRequest() ) transcode.return_value = { "method": "post", @@ -15918,7 +20519,7 @@ def test_update_project_intelligence_config_rest_interceptors(null_interceptor): ) req.return_value.content = return_value - request = storage_control.UpdateProjectIntelligenceConfigRequest() + request = storage_control.UpdateOrganizationIntelligenceConfigRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15927,7 +20528,7 @@ def test_update_project_intelligence_config_rest_interceptors(null_interceptor): post.return_value = storage_control.IntelligenceConfig() post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata - client.update_project_intelligence_config( + client.update_organization_intelligence_config( request, metadata=[ ("key", "val"), @@ -15940,14 +20541,52 @@ def test_update_project_intelligence_config_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_folder_intelligence_config_rest_bad_request( - request_type=storage_control.GetFolderIntelligenceConfigRequest, +def test_get_iam_policy_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.get_iam_policy({}) + assert "Method GetIamPolicy is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_set_iam_policy_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.set_iam_policy({}) + assert "Method SetIamPolicy is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_test_iam_permissions_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.test_iam_permissions({}) + assert "Method TestIamPermissions is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_intelligence_finding_rest_bad_request( + request_type=storage_control.GetIntelligenceFindingRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1/locations/sample2/intelligenceConfig"} + request_init = { + "name": "projects/sample1/locations/sample2/intelligenceFindings/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15963,31 +20602,38 @@ def test_get_folder_intelligence_config_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_folder_intelligence_config(request) + client.get_intelligence_finding(request) @pytest.mark.parametrize( "request_type", [ - storage_control.GetFolderIntelligenceConfigRequest, + storage_control.GetIntelligenceFindingRequest, dict, ], ) -def test_get_folder_intelligence_config_rest_call_success(request_type): +def test_get_intelligence_finding_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "folders/sample1/locations/sample2/intelligenceConfig"} + request_init = { + "name": "projects/sample1/locations/sample2/intelligenceFindings/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 = storage_control.IntelligenceConfig( + return_value = storage_control.IntelligenceFinding( name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + description="description_value", + type_=storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE, + category=storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT, + severity=storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL, + target_resource="target_resource_value", + associated_resources=["associated_resources_value"], ) # Wrap the value into a proper Response obj @@ -15995,24 +20641,34 @@ def test_get_folder_intelligence_config_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) + return_value = storage_control.IntelligenceFinding.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_folder_intelligence_config(request) + response = client.get_intelligence_finding(request) # Establish that the response is the type that we expect. - assert isinstance(response, storage_control.IntelligenceConfig) + assert isinstance(response, storage_control.IntelligenceFinding) assert response.name == "name_value" + assert response.description == "description_value" assert ( - response.edition_config - == storage_control.IntelligenceConfig.EditionConfig.INHERIT + response.type_ + == storage_control.FindingType.FINDING_TYPE_COLDLINE_AND_ARCHIVAL_STORAGE_OPERATIONS_SPIKE + ) + assert ( + response.category + == storage_control.FindingCategory.FINDING_CATEGORY_DATA_MANAGEMENT + ) + assert ( + response.severity == storage_control.FindingSeverity.FINDING_SEVERITY_CRITICAL ) + assert response.target_resource == "target_resource_value" + assert response.associated_resources == ["associated_resources_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_folder_intelligence_config_rest_interceptors(null_interceptor): +def test_get_intelligence_finding_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16025,23 +20681,21 @@ def test_get_folder_intelligence_config_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.StorageControlRestInterceptor, - "post_get_folder_intelligence_config", + transports.StorageControlRestInterceptor, "post_get_intelligence_finding" ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_get_folder_intelligence_config_with_metadata", + "post_get_intelligence_finding_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.StorageControlRestInterceptor, - "pre_get_folder_intelligence_config", + transports.StorageControlRestInterceptor, "pre_get_intelligence_finding" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.GetFolderIntelligenceConfigRequest.pb( - storage_control.GetFolderIntelligenceConfigRequest() + pb_message = storage_control.GetIntelligenceFindingRequest.pb( + storage_control.GetIntelligenceFindingRequest() ) transcode.return_value = { "method": "post", @@ -16053,21 +20707,24 @@ def test_get_folder_intelligence_config_rest_interceptors(null_interceptor): 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 = storage_control.IntelligenceConfig.to_json( - storage_control.IntelligenceConfig() + return_value = storage_control.IntelligenceFinding.to_json( + storage_control.IntelligenceFinding() ) req.return_value.content = return_value - request = storage_control.GetFolderIntelligenceConfigRequest() + request = storage_control.GetIntelligenceFindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = storage_control.IntelligenceConfig() - post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata + post.return_value = storage_control.IntelligenceFinding() + post_with_metadata.return_value = ( + storage_control.IntelligenceFinding(), + metadata, + ) - client.get_folder_intelligence_config( + client.get_intelligence_finding( request, metadata=[ ("key", "val"), @@ -16080,18 +20737,150 @@ def test_get_folder_intelligence_config_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_folder_intelligence_config_rest_bad_request( - request_type=storage_control.UpdateFolderIntelligenceConfigRequest, +def test_list_intelligence_findings_rest_bad_request( + request_type=storage_control.ListIntelligenceFindingsRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "intelligence_config": { - "name": "folders/sample1/locations/sample2/intelligenceConfig" + 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_intelligence_findings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingsRequest, + dict, + ], +) +def test_list_intelligence_findings_rest_call_success(request_type): + client = StorageControlClient( + 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 = storage_control.ListIntelligenceFindingsResponse( + 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 = storage_control.ListIntelligenceFindingsResponse.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_intelligence_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIntelligenceFindingsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_intelligence_findings_rest_interceptors(null_interceptor): + transport = transports.StorageControlRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.StorageControlRestInterceptor(), + ) + client = StorageControlClient(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.StorageControlRestInterceptor, "post_list_intelligence_findings" + ) as post, + mock.patch.object( + transports.StorageControlRestInterceptor, + "post_list_intelligence_findings_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.StorageControlRestInterceptor, "pre_list_intelligence_findings" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = storage_control.ListIntelligenceFindingsRequest.pb( + storage_control.ListIntelligenceFindingsRequest() + ) + 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 = storage_control.ListIntelligenceFindingsResponse.to_json( + storage_control.ListIntelligenceFindingsResponse() + ) + req.return_value.content = return_value + + request = storage_control.ListIntelligenceFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = storage_control.ListIntelligenceFindingsResponse() + post_with_metadata.return_value = ( + storage_control.ListIntelligenceFindingsResponse(), + metadata, + ) + + client.list_intelligence_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_summarize_intelligence_findings_rest_bad_request( + request_type=storage_control.SummarizeIntelligenceFindingsRequest, +): + client = StorageControlClient( + 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. @@ -16107,127 +20896,30 @@ def test_update_folder_intelligence_config_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_folder_intelligence_config(request) + client.summarize_intelligence_findings(request) @pytest.mark.parametrize( "request_type", [ - storage_control.UpdateFolderIntelligenceConfigRequest, + storage_control.SummarizeIntelligenceFindingsRequest, dict, ], ) -def test_update_folder_intelligence_config_rest_call_success(request_type): +def test_summarize_intelligence_findings_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "intelligence_config": { - "name": "folders/sample1/locations/sample2/intelligenceConfig" - } - } - request_init["intelligence_config"] = { - "name": "folders/sample1/locations/sample2/intelligenceConfig", - "edition_config": 1, - "update_time": {"seconds": 751, "nanos": 543}, - "filter": { - "included_cloud_storage_locations": { - "locations": ["locations_value1", "locations_value2"] - }, - "excluded_cloud_storage_locations": {}, - "included_cloud_storage_buckets": { - "bucket_id_regexes": [ - "bucket_id_regexes_value1", - "bucket_id_regexes_value2", - ] - }, - "excluded_cloud_storage_buckets": {}, - }, - "effective_intelligence_config": { - "effective_edition": 1, - "intelligence_config": "intelligence_config_value", - }, - "trial_config": {"expire_time": {}}, - } - # 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 = storage_control.UpdateFolderIntelligenceConfigRequest.meta.fields[ - "intelligence_config" - ] - - 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["intelligence_config"].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["intelligence_config"][field])): - del request_init["intelligence_config"][field][i][subfield] - else: - del request_init["intelligence_config"][field][subfield] + 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 = storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + return_value = storage_control.SummarizeIntelligenceFindingsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -16235,24 +20927,22 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) + return_value = storage_control.SummarizeIntelligenceFindingsResponse.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_folder_intelligence_config(request) + response = client.summarize_intelligence_findings(request) # Establish that the response is the type that we expect. - assert isinstance(response, storage_control.IntelligenceConfig) - assert response.name == "name_value" - assert ( - response.edition_config - == storage_control.IntelligenceConfig.EditionConfig.INHERIT - ) + assert isinstance(response, pagers.SummarizeIntelligenceFindingsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_folder_intelligence_config_rest_interceptors(null_interceptor): +def test_summarize_intelligence_findings_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16266,22 +20956,22 @@ def test_update_folder_intelligence_config_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_folder_intelligence_config", + "post_summarize_intelligence_findings", ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_folder_intelligence_config_with_metadata", + "post_summarize_intelligence_findings_with_metadata", ) as post_with_metadata, mock.patch.object( transports.StorageControlRestInterceptor, - "pre_update_folder_intelligence_config", + "pre_summarize_intelligence_findings", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.UpdateFolderIntelligenceConfigRequest.pb( - storage_control.UpdateFolderIntelligenceConfigRequest() + pb_message = storage_control.SummarizeIntelligenceFindingsRequest.pb( + storage_control.SummarizeIntelligenceFindingsRequest() ) transcode.return_value = { "method": "post", @@ -16293,21 +20983,24 @@ def test_update_folder_intelligence_config_rest_interceptors(null_interceptor): 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 = storage_control.IntelligenceConfig.to_json( - storage_control.IntelligenceConfig() + return_value = storage_control.SummarizeIntelligenceFindingsResponse.to_json( + storage_control.SummarizeIntelligenceFindingsResponse() ) req.return_value.content = return_value - request = storage_control.UpdateFolderIntelligenceConfigRequest() + request = storage_control.SummarizeIntelligenceFindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = storage_control.IntelligenceConfig() - post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata + post.return_value = storage_control.SummarizeIntelligenceFindingsResponse() + post_with_metadata.return_value = ( + storage_control.SummarizeIntelligenceFindingsResponse(), + metadata, + ) - client.update_folder_intelligence_config( + client.summarize_intelligence_findings( request, metadata=[ ("key", "val"), @@ -16320,15 +21013,15 @@ def test_update_folder_intelligence_config_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_organization_intelligence_config_rest_bad_request( - request_type=storage_control.GetOrganizationIntelligenceConfigRequest, +def test_get_intelligence_finding_revision_rest_bad_request( + request_type=storage_control.GetIntelligenceFindingRevisionRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" + "name": "projects/sample1/locations/sample2/intelligenceFindings/sample3/revisions/sample4" } request = request_type(**request_init) @@ -16345,33 +21038,32 @@ def test_get_organization_intelligence_config_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_organization_intelligence_config(request) + client.get_intelligence_finding_revision(request) @pytest.mark.parametrize( "request_type", [ - storage_control.GetOrganizationIntelligenceConfigRequest, + storage_control.GetIntelligenceFindingRevisionRequest, dict, ], ) -def test_get_organization_intelligence_config_rest_call_success(request_type): +def test_get_intelligence_finding_revision_rest_call_success(request_type): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" + "name": "projects/sample1/locations/sample2/intelligenceFindings/sample3/revisions/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 = storage_control.IntelligenceConfig( + return_value = storage_control.IntelligenceFindingRevision( name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, ) # Wrap the value into a proper Response obj @@ -16379,24 +21071,20 @@ def test_get_organization_intelligence_config_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) + return_value = storage_control.IntelligenceFindingRevision.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_organization_intelligence_config(request) + response = client.get_intelligence_finding_revision(request) # Establish that the response is the type that we expect. - assert isinstance(response, storage_control.IntelligenceConfig) + assert isinstance(response, storage_control.IntelligenceFindingRevision) assert response.name == "name_value" - assert ( - response.edition_config - == storage_control.IntelligenceConfig.EditionConfig.INHERIT - ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_organization_intelligence_config_rest_interceptors(null_interceptor): +def test_get_intelligence_finding_revision_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16410,22 +21098,22 @@ def test_get_organization_intelligence_config_rest_interceptors(null_interceptor mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.StorageControlRestInterceptor, - "post_get_organization_intelligence_config", + "post_get_intelligence_finding_revision", ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_get_organization_intelligence_config_with_metadata", + "post_get_intelligence_finding_revision_with_metadata", ) as post_with_metadata, mock.patch.object( transports.StorageControlRestInterceptor, - "pre_get_organization_intelligence_config", + "pre_get_intelligence_finding_revision", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.GetOrganizationIntelligenceConfigRequest.pb( - storage_control.GetOrganizationIntelligenceConfigRequest() + pb_message = storage_control.GetIntelligenceFindingRevisionRequest.pb( + storage_control.GetIntelligenceFindingRevisionRequest() ) transcode.return_value = { "method": "post", @@ -16437,21 +21125,24 @@ def test_get_organization_intelligence_config_rest_interceptors(null_interceptor 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 = storage_control.IntelligenceConfig.to_json( - storage_control.IntelligenceConfig() + return_value = storage_control.IntelligenceFindingRevision.to_json( + storage_control.IntelligenceFindingRevision() ) req.return_value.content = return_value - request = storage_control.GetOrganizationIntelligenceConfigRequest() + request = storage_control.GetIntelligenceFindingRevisionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = storage_control.IntelligenceConfig() - post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata + post.return_value = storage_control.IntelligenceFindingRevision() + post_with_metadata.return_value = ( + storage_control.IntelligenceFindingRevision(), + metadata, + ) - client.get_organization_intelligence_config( + client.get_intelligence_finding_revision( request, metadata=[ ("key", "val"), @@ -16464,17 +21155,15 @@ def test_get_organization_intelligence_config_rest_interceptors(null_interceptor post_with_metadata.assert_called_once() -def test_update_organization_intelligence_config_rest_bad_request( - request_type=storage_control.UpdateOrganizationIntelligenceConfigRequest, +def test_list_intelligence_finding_revisions_rest_bad_request( + request_type=storage_control.ListIntelligenceFindingRevisionsRequest, ): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "intelligence_config": { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" - } + "parent": "projects/sample1/locations/sample2/intelligenceFindings/sample3" } request = request_type(**request_init) @@ -16487,133 +21176,36 @@ def test_update_organization_intelligence_config_rest_bad_request( 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_organization_intelligence_config(request) - - -@pytest.mark.parametrize( - "request_type", - [ - storage_control.UpdateOrganizationIntelligenceConfigRequest, - dict, - ], -) -def test_update_organization_intelligence_config_rest_call_success(request_type): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "intelligence_config": { - "name": "organizations/sample1/locations/sample2/intelligenceConfig" - } - } - request_init["intelligence_config"] = { - "name": "organizations/sample1/locations/sample2/intelligenceConfig", - "edition_config": 1, - "update_time": {"seconds": 751, "nanos": 543}, - "filter": { - "included_cloud_storage_locations": { - "locations": ["locations_value1", "locations_value2"] - }, - "excluded_cloud_storage_locations": {}, - "included_cloud_storage_buckets": { - "bucket_id_regexes": [ - "bucket_id_regexes_value1", - "bucket_id_regexes_value2", - ] - }, - "excluded_cloud_storage_buckets": {}, - }, - "effective_intelligence_config": { - "effective_edition": 1, - "intelligence_config": "intelligence_config_value", - }, - "trial_config": {"expire_time": {}}, - } - # 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 = ( - storage_control.UpdateOrganizationIntelligenceConfigRequest.meta.fields[ - "intelligence_config" - ] - ) - - 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["intelligence_config"].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 + 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_intelligence_finding_revisions(request) - 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["intelligence_config"][field])): - del request_init["intelligence_config"][field][i][subfield] - else: - del request_init["intelligence_config"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + storage_control.ListIntelligenceFindingRevisionsRequest, + dict, + ], +) +def test_list_intelligence_finding_revisions_rest_call_success(request_type): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/intelligenceFindings/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 = storage_control.IntelligenceConfig( - name="name_value", - edition_config=storage_control.IntelligenceConfig.EditionConfig.INHERIT, + return_value = storage_control.ListIntelligenceFindingRevisionsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -16621,24 +21213,22 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = storage_control.IntelligenceConfig.pb(return_value) + return_value = storage_control.ListIntelligenceFindingRevisionsResponse.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_organization_intelligence_config(request) + response = client.list_intelligence_finding_revisions(request) # Establish that the response is the type that we expect. - assert isinstance(response, storage_control.IntelligenceConfig) - assert response.name == "name_value" - assert ( - response.edition_config - == storage_control.IntelligenceConfig.EditionConfig.INHERIT - ) + assert isinstance(response, pagers.ListIntelligenceFindingRevisionsPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_organization_intelligence_config_rest_interceptors(null_interceptor): +def test_list_intelligence_finding_revisions_rest_interceptors(null_interceptor): transport = transports.StorageControlRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16652,22 +21242,22 @@ def test_update_organization_intelligence_config_rest_interceptors(null_intercep mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_organization_intelligence_config", + "post_list_intelligence_finding_revisions", ) as post, mock.patch.object( transports.StorageControlRestInterceptor, - "post_update_organization_intelligence_config_with_metadata", + "post_list_intelligence_finding_revisions_with_metadata", ) as post_with_metadata, mock.patch.object( transports.StorageControlRestInterceptor, - "pre_update_organization_intelligence_config", + "pre_list_intelligence_finding_revisions", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = storage_control.UpdateOrganizationIntelligenceConfigRequest.pb( - storage_control.UpdateOrganizationIntelligenceConfigRequest() + pb_message = storage_control.ListIntelligenceFindingRevisionsRequest.pb( + storage_control.ListIntelligenceFindingRevisionsRequest() ) transcode.return_value = { "method": "post", @@ -16679,21 +21269,24 @@ def test_update_organization_intelligence_config_rest_interceptors(null_intercep 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 = storage_control.IntelligenceConfig.to_json( - storage_control.IntelligenceConfig() + return_value = storage_control.ListIntelligenceFindingRevisionsResponse.to_json( + storage_control.ListIntelligenceFindingRevisionsResponse() ) req.return_value.content = return_value - request = storage_control.UpdateOrganizationIntelligenceConfigRequest() + request = storage_control.ListIntelligenceFindingRevisionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = storage_control.IntelligenceConfig() - post_with_metadata.return_value = storage_control.IntelligenceConfig(), metadata + post.return_value = storage_control.ListIntelligenceFindingRevisionsResponse() + post_with_metadata.return_value = ( + storage_control.ListIntelligenceFindingRevisionsResponse(), + metadata, + ) - client.update_organization_intelligence_config( + client.list_intelligence_finding_revisions( request, metadata=[ ("key", "val"), @@ -16706,42 +21299,6 @@ def test_update_organization_intelligence_config_rest_interceptors(null_intercep post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.get_iam_policy({}) - assert "Method GetIamPolicy is not available over REST transport" in str( - not_implemented_error.value - ) - - -def test_set_iam_policy_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.set_iam_policy({}) - assert "Method SetIamPolicy is not available over REST transport" in str( - not_implemented_error.value - ) - - -def test_test_iam_permissions_rest_error(): - client = StorageControlClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - with pytest.raises(NotImplementedError) as not_implemented_error: - client.test_iam_permissions({}) - assert "Method TestIamPermissions is not available over REST transport" in str( - not_implemented_error.value - ) - - def test_initialize_client_w_rest(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -17353,6 +21910,111 @@ def test_test_iam_permissions_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_get_intelligence_finding_empty_call_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding), "__call__" + ) as call: + client.get_intelligence_finding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRequest() + assert args[0] == request_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_intelligence_findings_empty_call_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_findings), "__call__" + ) as call: + client.list_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingsRequest() + assert args[0] == request_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_summarize_intelligence_findings_empty_call_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.summarize_intelligence_findings), "__call__" + ) as call: + client.summarize_intelligence_findings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.SummarizeIntelligenceFindingsRequest() + assert args[0] == request_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_intelligence_finding_revision_empty_call_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_intelligence_finding_revision), "__call__" + ) as call: + client.get_intelligence_finding_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.GetIntelligenceFindingRevisionRequest() + assert args[0] == request_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_intelligence_finding_revisions_empty_call_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_intelligence_finding_revisions), "__call__" + ) as call: + client.list_intelligence_finding_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.ListIntelligenceFindingRevisionsRequest() + assert args[0] == request_msg + + def test_create_folder_routing_parameters_request_1_rest(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18135,6 +22797,11 @@ def test_storage_control_base_transport(): "get_iam_policy", "set_iam_policy", "test_iam_permissions", + "get_intelligence_finding", + "list_intelligence_findings", + "summarize_intelligence_findings", + "get_intelligence_finding_revision", + "list_intelligence_finding_revisions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -18510,6 +23177,21 @@ def test_storage_control_client_transport_session_collision(transport_name): session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 + session1 = client1.transport.get_intelligence_finding._session + session2 = client2.transport.get_intelligence_finding._session + assert session1 != session2 + session1 = client1.transport.list_intelligence_findings._session + session2 = client2.transport.list_intelligence_findings._session + assert session1 != session2 + session1 = client1.transport.summarize_intelligence_findings._session + session2 = client2.transport.summarize_intelligence_findings._session + assert session1 != session2 + session1 = client1.transport.get_intelligence_finding_revision._session + session2 = client2.transport.get_intelligence_finding_revision._session + assert session1 != session2 + session1 = client1.transport.list_intelligence_finding_revisions._session + session2 = client2.transport.list_intelligence_finding_revisions._session + assert session1 != session2 def test_storage_control_grpc_transport_channel(): @@ -18701,10 +23383,33 @@ def test_parse_anywhere_cache_path(): assert expected == actual -def test_folder_path(): +def test_bucket_path(): project = "cuttlefish" bucket = "mussel" - folder = "winkle" + expected = "projects/{project}/buckets/{bucket}".format( + project=project, + bucket=bucket, + ) + actual = StorageControlClient.bucket_path(project, bucket) + assert expected == actual + + +def test_parse_bucket_path(): + expected = { + "project": "winkle", + "bucket": "nautilus", + } + path = StorageControlClient.bucket_path(**expected) + + # Check that the path construction is reversible. + actual = StorageControlClient.parse_bucket_path(path) + assert expected == actual + + +def test_folder_path(): + project = "scallop" + bucket = "abalone" + folder = "squid" expected = "projects/{project}/buckets/{bucket}/folders/{folder}".format( project=project, bucket=bucket, @@ -18716,9 +23421,9 @@ def test_folder_path(): def test_parse_folder_path(): expected = { - "project": "nautilus", - "bucket": "scallop", - "folder": "abalone", + "project": "clam", + "bucket": "whelk", + "folder": "octopus", } path = StorageControlClient.folder_path(**expected) @@ -18728,8 +23433,8 @@ def test_parse_folder_path(): def test_intelligence_config_path(): - folder = "squid" - location = "clam" + folder = "oyster" + location = "nudibranch" expected = "folders/{folder}/locations/{location}/intelligenceConfig".format( folder=folder, location=location, @@ -18740,8 +23445,8 @@ def test_intelligence_config_path(): def test_parse_intelligence_config_path(): expected = { - "folder": "whelk", - "location": "octopus", + "folder": "cuttlefish", + "location": "mussel", } path = StorageControlClient.intelligence_config_path(**expected) @@ -18750,10 +23455,69 @@ def test_parse_intelligence_config_path(): assert expected == actual +def test_intelligence_finding_path(): + project = "winkle" + location = "nautilus" + intelligence_finding = "scallop" + expected = "projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}".format( + project=project, + location=location, + intelligence_finding=intelligence_finding, + ) + actual = StorageControlClient.intelligence_finding_path( + project, location, intelligence_finding + ) + assert expected == actual + + +def test_parse_intelligence_finding_path(): + expected = { + "project": "abalone", + "location": "squid", + "intelligence_finding": "clam", + } + path = StorageControlClient.intelligence_finding_path(**expected) + + # Check that the path construction is reversible. + actual = StorageControlClient.parse_intelligence_finding_path(path) + assert expected == actual + + +def test_intelligence_finding_revision_path(): + project = "whelk" + location = "octopus" + intelligence_finding = "oyster" + revision = "nudibranch" + expected = "projects/{project}/locations/{location}/intelligenceFindings/{intelligence_finding}/revisions/{revision}".format( + project=project, + location=location, + intelligence_finding=intelligence_finding, + revision=revision, + ) + actual = StorageControlClient.intelligence_finding_revision_path( + project, location, intelligence_finding, revision + ) + assert expected == actual + + +def test_parse_intelligence_finding_revision_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "intelligence_finding": "winkle", + "revision": "nautilus", + } + path = StorageControlClient.intelligence_finding_revision_path(**expected) + + # Check that the path construction is reversible. + actual = StorageControlClient.parse_intelligence_finding_revision_path(path) + assert expected == actual + + def test_managed_folder_path(): - project = "oyster" - bucket = "nudibranch" - managed_folder = "cuttlefish" + project = "scallop" + bucket = "abalone" + managed_folder = "squid" expected = ( "projects/{project}/buckets/{bucket}/managedFolders/{managed_folder}".format( project=project, @@ -18767,9 +23531,9 @@ def test_managed_folder_path(): def test_parse_managed_folder_path(): expected = { - "project": "mussel", - "bucket": "winkle", - "managed_folder": "nautilus", + "project": "clam", + "bucket": "whelk", + "managed_folder": "octopus", } path = StorageControlClient.managed_folder_path(**expected) @@ -18779,8 +23543,8 @@ def test_parse_managed_folder_path(): def test_storage_layout_path(): - project = "scallop" - bucket = "abalone" + project = "oyster" + bucket = "nudibranch" expected = "projects/{project}/buckets/{bucket}/storageLayout".format( project=project, bucket=bucket, @@ -18791,8 +23555,8 @@ def test_storage_layout_path(): def test_parse_storage_layout_path(): expected = { - "project": "squid", - "bucket": "clam", + "project": "cuttlefish", + "bucket": "mussel", } path = StorageControlClient.storage_layout_path(**expected) @@ -18802,7 +23566,7 @@ def test_parse_storage_layout_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -18812,7 +23576,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = StorageControlClient.common_billing_account_path(**expected) @@ -18822,7 +23586,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -18832,7 +23596,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = StorageControlClient.common_folder_path(**expected) @@ -18842,7 +23606,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -18852,7 +23616,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = StorageControlClient.common_organization_path(**expected) @@ -18862,7 +23626,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -18872,7 +23636,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = StorageControlClient.common_project_path(**expected) @@ -18882,8 +23646,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, @@ -18894,8 +23658,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = StorageControlClient.common_location_path(**expected) diff --git a/packages/google-maps-places/google/maps/places/__init__.py b/packages/google-maps-places/google/maps/places/__init__.py index 82bc066f2088..9a843c49d5a1 100644 --- a/packages/google-maps-places/google/maps/places/__init__.py +++ b/packages/google-maps-places/google/maps/places/__init__.py @@ -48,6 +48,13 @@ from google.maps.places_v1.types.route_modifiers import RouteModifiers from google.maps.places_v1.types.routing_preference import RoutingPreference from google.maps.places_v1.types.routing_summary import RoutingSummary +from google.maps.places_v1.types.transit import ( + TransitAgency, + TransitIcon, + TransitLine, + TransitStation, + TransitStop, +) from google.maps.places_v1.types.travel_mode import TravelMode __all__ = ( @@ -81,5 +88,10 @@ "RouteModifiers", "RoutingPreference", "RoutingSummary", + "TransitAgency", + "TransitIcon", + "TransitLine", + "TransitStation", + "TransitStop", "TravelMode", ) diff --git a/packages/google-maps-places/google/maps/places_v1/__init__.py b/packages/google-maps-places/google/maps/places_v1/__init__.py index 1facf24aabb3..21cb42522c09 100644 --- a/packages/google-maps-places/google/maps/places_v1/__init__.py +++ b/packages/google-maps-places/google/maps/places_v1/__init__.py @@ -52,6 +52,13 @@ from .types.route_modifiers import RouteModifiers from .types.routing_preference import RoutingPreference from .types.routing_summary import RoutingSummary +from .types.transit import ( + TransitAgency, + TransitIcon, + TransitLine, + TransitStation, + TransitStop, +) from .types.travel_mode import TravelMode if hasattr(api_core, "check_python_version") and hasattr( @@ -168,5 +175,10 @@ def _get_version(dependency_name): "SearchNearbyResponse", "SearchTextRequest", "SearchTextResponse", + "TransitAgency", + "TransitIcon", + "TransitLine", + "TransitStation", + "TransitStop", "TravelMode", ) diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py b/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py index e3f8993aa94c..c89921a476d4 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/async_client.py @@ -62,6 +62,7 @@ price_range, review, routing_summary, + transit, ) from .client import PlacesClient diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/client.py b/packages/google-maps-places/google/maps/places_v1/services/places/client.py index 43ef7baa6640..bd8a7506c356 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/client.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/client.py @@ -79,6 +79,7 @@ price_range, review, routing_summary, + transit, ) from .transports.base import DEFAULT_CLIENT_INFO, PlacesTransport diff --git a/packages/google-maps-places/google/maps/places_v1/types/__init__.py b/packages/google-maps-places/google/maps/places_v1/types/__init__.py index ccacf047ae79..75f884b247df 100644 --- a/packages/google-maps-places/google/maps/places_v1/types/__init__.py +++ b/packages/google-maps-places/google/maps/places_v1/types/__init__.py @@ -75,6 +75,13 @@ from .routing_summary import ( RoutingSummary, ) +from .transit import ( + TransitAgency, + TransitIcon, + TransitLine, + TransitStation, + TransitStop, +) from .travel_mode import ( TravelMode, ) @@ -108,5 +115,10 @@ "RouteModifiers", "RoutingPreference", "RoutingSummary", + "TransitAgency", + "TransitIcon", + "TransitLine", + "TransitStation", + "TransitStop", "TravelMode", ) diff --git a/packages/google-maps-places/google/maps/places_v1/types/place.py b/packages/google-maps-places/google/maps/places_v1/types/place.py index c99111e407ac..a762d932b7a4 100644 --- a/packages/google-maps-places/google/maps/places_v1/types/place.py +++ b/packages/google-maps-places/google/maps/places_v1/types/place.py @@ -27,7 +27,13 @@ from google.geo.type.types import viewport as ggt_viewport from google.maps.places_v1.types import address_descriptor as gmp_address_descriptor -from google.maps.places_v1.types import content_block, ev_charging, photo, review +from google.maps.places_v1.types import ( + content_block, + ev_charging, + photo, + review, + transit, +) from google.maps.places_v1.types import fuel_options as gmp_fuel_options from google.maps.places_v1.types import price_range as gmp_price_range @@ -424,6 +430,9 @@ class Place(proto.Message): multiple times, this field will represent the first moved Place. This field will not be populated if this Place has not moved. + transit_station (google.maps.places_v1.types.TransitStation): + The transit station information for the + place. """ class BusinessStatus(proto.Enum): @@ -1654,6 +1663,11 @@ class Link(proto.Message): proto.STRING, number=94, ) + transit_station: transit.TransitStation = proto.Field( + proto.MESSAGE, + number=98, + message=transit.TransitStation, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-places/google/maps/places_v1/types/transit.py b/packages/google-maps-places/google/maps/places_v1/types/transit.py new file mode 100644 index 000000000000..2b22952a7681 --- /dev/null +++ b/packages/google-maps-places/google/maps/places_v1/types/transit.py @@ -0,0 +1,367 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.type.latlng_pb2 as latlng_pb2 # type: ignore +import google.type.localized_text_pb2 as localized_text_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.maps.places.v1", + manifest={ + "TransitStation", + "TransitAgency", + "TransitLine", + "TransitStop", + "TransitIcon", + }, +) + + +class TransitStation(proto.Message): + r"""Represents transit-specific information for a place. + + Attributes: + display_name (google.type.localized_text_pb2.LocalizedText): + The name of the station in the local + language. + agencies (MutableSequence[google.maps.places_v1.types.TransitAgency]): + The transit agencies that serve this station. + stops (MutableSequence[google.maps.places_v1.types.TransitStop]): + Transit stops at this station. + """ + + display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + agencies: MutableSequence["TransitAgency"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="TransitAgency", + ) + stops: MutableSequence["TransitStop"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="TransitStop", + ) + + +class TransitAgency(proto.Message): + r"""Represents a transit agency. + + Attributes: + display_name (google.type.localized_text_pb2.LocalizedText): + Agency name (e.g. "VTA") in the requested + language. + url (str): + The URL of the agency's homepage. + fare_url (str): + The URL of the agency's fare details page. + icon (google.maps.places_v1.types.TransitIcon): + Icon identifier for localized branded icon of a transit + system (e.g. London Underground) which should be used + instead of TransitLine.vehicle_icon in the UI. + lines (MutableSequence[google.maps.places_v1.types.TransitLine]): + The transit lines that are served by this + agency. + """ + + display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + fare_url: str = proto.Field( + proto.STRING, + number=3, + ) + icon: "TransitIcon" = proto.Field( + proto.MESSAGE, + number=4, + message="TransitIcon", + ) + lines: MutableSequence["TransitLine"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="TransitLine", + ) + + +class TransitLine(proto.Message): + r"""Represents a single transit line. + + Attributes: + id (str): + The id of the transit line that can be used + to uniquely identify the line among other + transit lines in the same transit station. This + identifier is not guaranteed to be stable across + different responses. + vehicle_type (google.maps.places_v1.types.TransitLine.VehicleType): + The type of vehicle using this line. + display_name (google.type.localized_text_pb2.LocalizedText): + The long name for this transit line (e.g. + "Sunnydale local"). + short_display_name (google.type.localized_text_pb2.LocalizedText): + The short name for this transit line (e.g. + "S2"). + text_color (str): + The text color of labels for this transit + line in #RRGGBB hex format, e.g. #909CE1. + background_color (str): + The background color of the labels for this + transit line in #RRGGBB hex format, e.g. + #909CE1. This color can also be used for drawing + shapes for this transit line. + url (str): + The URL of a webpage with details about this + line. + icon (google.maps.places_v1.types.TransitIcon): + Icon identifier for this particular line + (e.g. subway lines in New York). + vehicle_icon (google.maps.places_v1.types.TransitIcon): + Icon identifier for this particular vehicle + type. + """ + + class VehicleType(proto.Enum): + r"""The type of vehicle for a transit line. + + Values: + VEHICLE_TYPE_UNSPECIFIED (0): + Default value when vehicle type is not + specified. + RAIL (1): + Rail. + METRO_RAIL (2): + Metro rail. + SUBWAY (3): + Subway. + TRAM (4): + Tram. + MONORAIL (5): + Monorail. + HEAVY_RAIL (6): + Heavy rail. + COMMUTER_TRAIN (7): + Commuter train. + HIGH_SPEED_TRAIN (8): + High speed train. + LONG_DISTANCE_TRAIN (9): + Long distance train. + BUS (10): + Bus. + INTERCITY_BUS (11): + Intercity bus. + TROLLEYBUS (12): + Trolleybus. + SHARE_TAXI (13): + Share taxi. + COACH (14): + Coach. + FERRY (15): + Ferry. + CABLE_CAR (16): + Cable car. + GONDOLA_LIFT (17): + Gondola lift. + FUNICULAR (18): + Funicular. + SPECIAL (19): + Special. + HORSE_CARRIAGE (20): + Horse carriage. + AIRPLANE (21): + Airplane. + """ + + VEHICLE_TYPE_UNSPECIFIED = 0 + RAIL = 1 + METRO_RAIL = 2 + SUBWAY = 3 + TRAM = 4 + MONORAIL = 5 + HEAVY_RAIL = 6 + COMMUTER_TRAIN = 7 + HIGH_SPEED_TRAIN = 8 + LONG_DISTANCE_TRAIN = 9 + BUS = 10 + INTERCITY_BUS = 11 + TROLLEYBUS = 12 + SHARE_TAXI = 13 + COACH = 14 + FERRY = 15 + CABLE_CAR = 16 + GONDOLA_LIFT = 17 + FUNICULAR = 18 + SPECIAL = 19 + HORSE_CARRIAGE = 20 + AIRPLANE = 21 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + vehicle_type: VehicleType = proto.Field( + proto.ENUM, + number=2, + enum=VehicleType, + ) + display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + short_display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + text_color: str = proto.Field( + proto.STRING, + number=5, + ) + background_color: str = proto.Field( + proto.STRING, + number=6, + ) + url: str = proto.Field( + proto.STRING, + number=7, + ) + icon: "TransitIcon" = proto.Field( + proto.MESSAGE, + number=8, + message="TransitIcon", + ) + vehicle_icon: "TransitIcon" = proto.Field( + proto.MESSAGE, + number=9, + message="TransitIcon", + ) + + +class TransitStop(proto.Message): + r"""Represents a transit stop within a station. This is a specific + location where passengers board and alight transit vehicles, such as + a platform or bus bay. This is distinct from a ``Departure``, which + is an event of a vehicle leaving a stop at a specific time. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + The id of the transit stop that can be used + to uniquely identify the stop among other + transit stops in the same transit station. This + identifier is not guaranteed to be stable across + different responses. + display_name (google.type.localized_text_pb2.LocalizedText): + The name of the stop. + platform_code (google.type.localized_text_pb2.LocalizedText): + The platform code represented by this stop. + It can be formatted in any way. (eg: "2", + "Platform 2", "2-4", or "1x"). + signage_text (google.type.localized_text_pb2.LocalizedText): + The verbatim text written on the signboard for this + platform, e.g. "Towards Central" or "East side & Brooklyn". + When ``platform_code`` is absent, this field is potentially + the only identifier for the platform; however, both + ``platform_code`` and ``signage_text`` may be set + simultaneously. + stop_code (google.type.localized_text_pb2.LocalizedText): + Human readable identifier of the stop, used + by transit agencies to distinguish stops with + the same name. + location (google.type.latlng_pb2.LatLng): + The stop's location. + wheelchair_accessible_entrance (bool): + Wheelchair accessibility of this stop. This + field indicates whether there is an accessible + path from outside the station to the stop. It + does not indicate whether it is possible to + board a vehicle from the stop. + + This field is a member of `oneof`_ ``_wheelchair_accessible_entrance``. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + platform_code: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + signage_text: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + stop_code: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=5, + message=localized_text_pb2.LocalizedText, + ) + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=6, + message=latlng_pb2.LatLng, + ) + wheelchair_accessible_entrance: bool = proto.Field( + proto.BOOL, + number=7, + optional=True, + ) + + +class TransitIcon(proto.Message): + r"""Icon for a transit line, vehicle, or agency. + + Attributes: + url (str): + The URL of the icon. + name_included (bool): + Whether the name is contained in the icon and + there is no need to display it next to the icon. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + name_included: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py index 2e22dcbd14ab..1cce8810e989 100644 --- a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py +++ b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py @@ -78,6 +78,7 @@ route_modifiers, routing_preference, routing_summary, + transit, travel_mode, )