diff --git a/.release-please-individual-manifest.json b/.release-please-individual-manifest.json index 999d31cc830d..325f141eedc2 100644 --- a/.release-please-individual-manifest.json +++ b/.release-please-individual-manifest.json @@ -1,6 +1,7 @@ { - "packages/google-cloud-workloadidentity": "0.1.0", "packages/google-cloud-ftp": "0.1.0", + "packages/google-cloud-workloadidentity": "0.1.0", "packages/google-crc32c": "1.8.0", + "packages/google-maps-mapmanagement": "0.1.0", "preview-packages/google-cloud-compute": "1.51.0-preview.1" -} +} \ No newline at end of file diff --git a/librarian.yaml b/librarian.yaml index 7566bfa79e63..e97cb5f5cf01 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.39.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 8856eed71a9cb2b9829d2617ee57fe2d8871a691 - sha256: 54104af35306b605a97f7d1b98b9b96f4a507cd18322b44d81f62eca17969b3a + commit: 50aad1b835b0b1fd3acec6af91d9c9735787fe11 + sha256: e58f3198fb96392a89b2850cca67882456f8d231ea4849f16cfb5551a012789d tools: pip: - name: black @@ -2356,6 +2356,7 @@ libraries: - name: google-maps-mapmanagement version: 0.1.0 apis: + - path: google/maps/mapmanagement/v2 - path: google/maps/mapmanagement/v2beta copyright_year: "2026" python: diff --git a/packages/google-ads-admanager/docs/admanager_v1/native_style_service.rst b/packages/google-ads-admanager/docs/admanager_v1/native_style_service.rst new file mode 100644 index 000000000000..32cb7b5b1f3e --- /dev/null +++ b/packages/google-ads-admanager/docs/admanager_v1/native_style_service.rst @@ -0,0 +1,10 @@ +NativeStyleService +------------------------------------ + +.. automodule:: google.ads.admanager_v1.services.native_style_service + :members: + :inherited-members: + +.. automodule:: google.ads.admanager_v1.services.native_style_service.pagers + :members: + :inherited-members: diff --git a/packages/google-ads-admanager/docs/admanager_v1/services_.rst b/packages/google-ads-admanager/docs/admanager_v1/services_.rst index 36a1b800cad8..0003640041cd 100644 --- a/packages/google-ads-admanager/docs/admanager_v1/services_.rst +++ b/packages/google-ads-admanager/docs/admanager_v1/services_.rst @@ -43,6 +43,7 @@ Services for Google Ads Admanager v1 API mobile_carrier_service mobile_device_service mobile_device_submodel_service + native_style_service network_service operating_system_service operating_system_version_service diff --git a/packages/google-ads-admanager/google/ads/admanager/__init__.py b/packages/google-ads-admanager/google/ads/admanager/__init__.py index 3eec214d3b08..46b21f4b9bac 100644 --- a/packages/google-ads-admanager/google/ads/admanager/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager/__init__.py @@ -122,6 +122,9 @@ from google.ads.admanager_v1.services.mobile_device_submodel_service.client import ( MobileDeviceSubmodelServiceClient, ) +from google.ads.admanager_v1.services.native_style_service.client import ( + NativeStyleServiceClient, +) from google.ads.admanager_v1.services.network_service.client import NetworkServiceClient from google.ads.admanager_v1.services.operating_system_service.client import ( OperatingSystemServiceClient, @@ -288,8 +291,24 @@ UpdateApplicationRequest, ) from google.ads.admanager_v1.types.applied_label import AppliedLabel +from google.ads.admanager_v1.types.audience_segment_enums import ( + AudienceSegmentApprovalStatusEnum, + AudienceSegmentLicenseTypeEnum, + AudienceSegmentStatusEnum, + AudienceSegmentTypeEnum, +) from google.ads.admanager_v1.types.audience_segment_messages import AudienceSegment from google.ads.admanager_v1.types.audience_segment_service import ( + BatchActivateAudienceSegmentsRequest, + BatchActivateAudienceSegmentsResponse, + BatchApproveAudienceSegmentsRequest, + BatchApproveAudienceSegmentsResponse, + BatchDeactivateAudienceSegmentsRequest, + BatchDeactivateAudienceSegmentsResponse, + BatchPopulateAudienceSegmentsRequest, + BatchPopulateAudienceSegmentsResponse, + BatchRejectAudienceSegmentsRequest, + BatchRejectAudienceSegmentsResponse, GetAudienceSegmentRequest, ListAudienceSegmentsRequest, ListAudienceSegmentsResponse, @@ -350,12 +369,21 @@ from google.ads.admanager_v1.types.child_publisher_service import ( BatchCreateChildPublishersRequest, BatchCreateChildPublishersResponse, + BatchRejectChildPublishersRequest, + BatchRejectChildPublishersResponse, + BatchRenegotiateChildPublisherAgreementsRequest, + BatchRenegotiateChildPublisherAgreementsResponse, + BatchResendChildPublisherInvitationEmailsRequest, + BatchResendChildPublisherInvitationEmailsResponse, BatchUpdateChildPublishersRequest, BatchUpdateChildPublishersResponse, + BatchWithdrawChildPublishersRequest, + BatchWithdrawChildPublishersResponse, CreateChildPublisherRequest, GetChildPublisherRequest, ListChildPublishersRequest, ListChildPublishersResponse, + RenegotiateChildPublisherAgreementRequest, UpdateChildPublisherRequest, ) from google.ads.admanager_v1.types.cms_metadata_key_enums import ( @@ -819,11 +847,36 @@ ListMobileDeviceSubmodelsRequest, ListMobileDeviceSubmodelsResponse, ) -from google.ads.admanager_v1.types.network_messages import Network +from google.ads.admanager_v1.types.native_style_enums import NativeStyleStatusEnum +from google.ads.admanager_v1.types.native_style_messages import NativeStyle +from google.ads.admanager_v1.types.native_style_service import ( + BatchActivateNativeStylesRequest, + BatchActivateNativeStylesResponse, + BatchArchiveNativeStylesRequest, + BatchArchiveNativeStylesResponse, + BatchCreateNativeStylesRequest, + BatchCreateNativeStylesResponse, + BatchDeactivateNativeStylesRequest, + BatchDeactivateNativeStylesResponse, + BatchUpdateNativeStylesRequest, + BatchUpdateNativeStylesResponse, + CreateNativeStyleRequest, + GetNativeStyleRequest, + ListNativeStylesRequest, + ListNativeStylesResponse, + UpdateNativeStyleRequest, +) +from google.ads.admanager_v1.types.network_messages import ( + DefaultThirdPartyDataDeclaration, + Network, +) from google.ads.admanager_v1.types.network_service import ( + GetDefaultThirdPartyDataDeclarationRequest, GetNetworkRequest, ListNetworksRequest, ListNetworksResponse, + ProvisionTestNetworkRequest, + UpdateNetworkRequest, ) from google.ads.admanager_v1.types.nielsen_ctv_pacing_enum import NielsenCtvPacingEnum from google.ads.admanager_v1.types.non_guaranteed_deal_priority import ( @@ -1192,6 +1245,7 @@ "MobileCarrierServiceClient", "MobileDeviceServiceClient", "MobileDeviceSubmodelServiceClient", + "NativeStyleServiceClient", "NetworkServiceClient", "OperatingSystemServiceClient", "OperatingSystemVersionServiceClient", @@ -1307,7 +1361,21 @@ "ListApplicationsResponse", "UpdateApplicationRequest", "AppliedLabel", + "AudienceSegmentApprovalStatusEnum", + "AudienceSegmentLicenseTypeEnum", + "AudienceSegmentStatusEnum", + "AudienceSegmentTypeEnum", "AudienceSegment", + "BatchActivateAudienceSegmentsRequest", + "BatchActivateAudienceSegmentsResponse", + "BatchApproveAudienceSegmentsRequest", + "BatchApproveAudienceSegmentsResponse", + "BatchDeactivateAudienceSegmentsRequest", + "BatchDeactivateAudienceSegmentsResponse", + "BatchPopulateAudienceSegmentsRequest", + "BatchPopulateAudienceSegmentsResponse", + "BatchRejectAudienceSegmentsRequest", + "BatchRejectAudienceSegmentsResponse", "GetAudienceSegmentRequest", "ListAudienceSegmentsRequest", "ListAudienceSegmentsResponse", @@ -1350,12 +1418,21 @@ "ChildPublisher", "BatchCreateChildPublishersRequest", "BatchCreateChildPublishersResponse", + "BatchRejectChildPublishersRequest", + "BatchRejectChildPublishersResponse", + "BatchRenegotiateChildPublisherAgreementsRequest", + "BatchRenegotiateChildPublisherAgreementsResponse", + "BatchResendChildPublisherInvitationEmailsRequest", + "BatchResendChildPublisherInvitationEmailsResponse", "BatchUpdateChildPublishersRequest", "BatchUpdateChildPublishersResponse", + "BatchWithdrawChildPublishersRequest", + "BatchWithdrawChildPublishersResponse", "CreateChildPublisherRequest", "GetChildPublisherRequest", "ListChildPublishersRequest", "ListChildPublishersResponse", + "RenegotiateChildPublisherAgreementRequest", "UpdateChildPublisherRequest", "CmsMetadataKeyStatusEnum", "CmsMetadataKey", @@ -1691,10 +1768,31 @@ "GetMobileDeviceSubmodelRequest", "ListMobileDeviceSubmodelsRequest", "ListMobileDeviceSubmodelsResponse", + "NativeStyleStatusEnum", + "NativeStyle", + "BatchActivateNativeStylesRequest", + "BatchActivateNativeStylesResponse", + "BatchArchiveNativeStylesRequest", + "BatchArchiveNativeStylesResponse", + "BatchCreateNativeStylesRequest", + "BatchCreateNativeStylesResponse", + "BatchDeactivateNativeStylesRequest", + "BatchDeactivateNativeStylesResponse", + "BatchUpdateNativeStylesRequest", + "BatchUpdateNativeStylesResponse", + "CreateNativeStyleRequest", + "GetNativeStyleRequest", + "ListNativeStylesRequest", + "ListNativeStylesResponse", + "UpdateNativeStyleRequest", + "DefaultThirdPartyDataDeclaration", "Network", + "GetDefaultThirdPartyDataDeclarationRequest", "GetNetworkRequest", "ListNetworksRequest", "ListNetworksResponse", + "ProvisionTestNetworkRequest", + "UpdateNetworkRequest", "NielsenCtvPacingEnum", "NonGuaranteedDealPriority", "OperatingSystem", diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py index bb31e4d9ac80..694ffc7e0c25 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/__init__.py @@ -70,6 +70,7 @@ "google.ads.admanager_v1.services.mobile_carrier_service", "google.ads.admanager_v1.services.mobile_device_service", "google.ads.admanager_v1.services.mobile_device_submodel_service", + "google.ads.admanager_v1.services.native_style_service", "google.ads.admanager_v1.services.network_service", "google.ads.admanager_v1.services.operating_system_service", "google.ads.admanager_v1.services.operating_system_version_service", @@ -113,6 +114,7 @@ "google.ads.admanager_v1.types.application_messages", "google.ads.admanager_v1.types.application_service", "google.ads.admanager_v1.types.applied_label", + "google.ads.admanager_v1.types.audience_segment_enums", "google.ads.admanager_v1.types.audience_segment_messages", "google.ads.admanager_v1.types.audience_segment_service", "google.ads.admanager_v1.types.bandwidth_group_messages", @@ -234,6 +236,9 @@ "google.ads.admanager_v1.types.mobile_device_service", "google.ads.admanager_v1.types.mobile_device_submodel_messages", "google.ads.admanager_v1.types.mobile_device_submodel_service", + "google.ads.admanager_v1.types.native_style_enums", + "google.ads.admanager_v1.types.native_style_messages", + "google.ads.admanager_v1.types.native_style_service", "google.ads.admanager_v1.types.network_messages", "google.ads.admanager_v1.types.network_service", "google.ads.admanager_v1.types.nielsen_ctv_pacing_enum", @@ -353,6 +358,7 @@ from .services.mobile_carrier_service import MobileCarrierServiceClient from .services.mobile_device_service import MobileDeviceServiceClient from .services.mobile_device_submodel_service import MobileDeviceSubmodelServiceClient +from .services.native_style_service import NativeStyleServiceClient from .services.network_service import NetworkServiceClient from .services.operating_system_service import OperatingSystemServiceClient from .services.operating_system_version_service import ( @@ -485,8 +491,24 @@ UpdateApplicationRequest, ) from .types.applied_label import AppliedLabel +from .types.audience_segment_enums import ( + AudienceSegmentApprovalStatusEnum, + AudienceSegmentLicenseTypeEnum, + AudienceSegmentStatusEnum, + AudienceSegmentTypeEnum, +) from .types.audience_segment_messages import AudienceSegment from .types.audience_segment_service import ( + BatchActivateAudienceSegmentsRequest, + BatchActivateAudienceSegmentsResponse, + BatchApproveAudienceSegmentsRequest, + BatchApproveAudienceSegmentsResponse, + BatchDeactivateAudienceSegmentsRequest, + BatchDeactivateAudienceSegmentsResponse, + BatchPopulateAudienceSegmentsRequest, + BatchPopulateAudienceSegmentsResponse, + BatchRejectAudienceSegmentsRequest, + BatchRejectAudienceSegmentsResponse, GetAudienceSegmentRequest, ListAudienceSegmentsRequest, ListAudienceSegmentsResponse, @@ -543,12 +565,21 @@ from .types.child_publisher_service import ( BatchCreateChildPublishersRequest, BatchCreateChildPublishersResponse, + BatchRejectChildPublishersRequest, + BatchRejectChildPublishersResponse, + BatchRenegotiateChildPublisherAgreementsRequest, + BatchRenegotiateChildPublisherAgreementsResponse, + BatchResendChildPublisherInvitationEmailsRequest, + BatchResendChildPublisherInvitationEmailsResponse, BatchUpdateChildPublishersRequest, BatchUpdateChildPublishersResponse, + BatchWithdrawChildPublishersRequest, + BatchWithdrawChildPublishersResponse, CreateChildPublisherRequest, GetChildPublisherRequest, ListChildPublishersRequest, ListChildPublishersResponse, + RenegotiateChildPublisherAgreementRequest, UpdateChildPublisherRequest, ) from .types.cms_metadata_key_enums import CmsMetadataKeyStatusEnum @@ -967,11 +998,33 @@ ListMobileDeviceSubmodelsRequest, ListMobileDeviceSubmodelsResponse, ) -from .types.network_messages import Network +from .types.native_style_enums import NativeStyleStatusEnum +from .types.native_style_messages import NativeStyle +from .types.native_style_service import ( + BatchActivateNativeStylesRequest, + BatchActivateNativeStylesResponse, + BatchArchiveNativeStylesRequest, + BatchArchiveNativeStylesResponse, + BatchCreateNativeStylesRequest, + BatchCreateNativeStylesResponse, + BatchDeactivateNativeStylesRequest, + BatchDeactivateNativeStylesResponse, + BatchUpdateNativeStylesRequest, + BatchUpdateNativeStylesResponse, + CreateNativeStyleRequest, + GetNativeStyleRequest, + ListNativeStylesRequest, + ListNativeStylesResponse, + UpdateNativeStyleRequest, +) +from .types.network_messages import DefaultThirdPartyDataDeclaration, Network from .types.network_service import ( + GetDefaultThirdPartyDataDeclarationRequest, GetNetworkRequest, ListNetworksRequest, ListNetworksResponse, + ProvisionTestNetworkRequest, + UpdateNetworkRequest, ) from .types.nielsen_ctv_pacing_enum import NielsenCtvPacingEnum from .types.non_guaranteed_deal_priority import NonGuaranteedDealPriority @@ -1385,8 +1438,12 @@ def _get_version(dependency_name): "AppliedLabel", "ArchiveDaiEncodingProfileRequest", "AudienceSegment", + "AudienceSegmentApprovalStatusEnum", + "AudienceSegmentLicenseTypeEnum", "AudienceSegmentServiceClient", + "AudienceSegmentStatusEnum", "AudienceSegmentTargeting", + "AudienceSegmentTypeEnum", "AudioSettings", "AuxiliaryAdSettings", "BandwidthGroup", @@ -1396,6 +1453,8 @@ def _get_version(dependency_name): "BatchActivateAdRulesResponse", "BatchActivateAdUnitsRequest", "BatchActivateAdUnitsResponse", + "BatchActivateAudienceSegmentsRequest", + "BatchActivateAudienceSegmentsResponse", "BatchActivateCdnConfigsRequest", "BatchActivateCdnConfigsResponse", "BatchActivateCmsMetadataKeysRequest", @@ -1420,6 +1479,8 @@ def _get_version(dependency_name): "BatchActivateLabelsResponse", "BatchActivateLiveStreamsRequest", "BatchActivateLiveStreamsResponse", + "BatchActivateNativeStylesRequest", + "BatchActivateNativeStylesResponse", "BatchActivatePlacementsRequest", "BatchActivatePlacementsResponse", "BatchActivateTeamsRequest", @@ -1429,6 +1490,8 @@ def _get_version(dependency_name): "BatchAllowAdReviewCenterAdsResponse", "BatchApproveAndOverbookOrdersRequest", "BatchApproveAndOverbookOrdersResponse", + "BatchApproveAudienceSegmentsRequest", + "BatchApproveAudienceSegmentsResponse", "BatchApproveOrdersRequest", "BatchApproveOrdersResponse", "BatchApproveOrdersWithoutReservationRequest", @@ -1445,6 +1508,8 @@ def _get_version(dependency_name): "BatchArchiveDaiEncodingProfilesResponse", "BatchArchiveLiveStreamsRequest", "BatchArchiveLiveStreamsResponse", + "BatchArchiveNativeStylesRequest", + "BatchArchiveNativeStylesResponse", "BatchArchiveOrdersRequest", "BatchArchiveOrdersResponse", "BatchArchivePlacementsRequest", @@ -1487,6 +1552,8 @@ def _get_version(dependency_name): "BatchCreateLabelsResponse", "BatchCreateLiveStreamsRequest", "BatchCreateLiveStreamsResponse", + "BatchCreateNativeStylesRequest", + "BatchCreateNativeStylesResponse", "BatchCreateOrdersRequest", "BatchCreateOrdersResponse", "BatchCreatePlacementsRequest", @@ -1505,6 +1572,8 @@ def _get_version(dependency_name): "BatchDeactivateAdRulesResponse", "BatchDeactivateAdUnitsRequest", "BatchDeactivateAdUnitsResponse", + "BatchDeactivateAudienceSegmentsRequest", + "BatchDeactivateAudienceSegmentsResponse", "BatchDeactivateCmsMetadataKeysRequest", "BatchDeactivateCmsMetadataKeysResponse", "BatchDeactivateCmsMetadataValuesRequest", @@ -1523,6 +1592,8 @@ def _get_version(dependency_name): "BatchDeactivateDaiAuthenticationKeysResponse", "BatchDeactivateLabelsRequest", "BatchDeactivateLabelsResponse", + "BatchDeactivateNativeStylesRequest", + "BatchDeactivateNativeStylesResponse", "BatchDeactivatePlacementsRequest", "BatchDeactivatePlacementsResponse", "BatchDeactivateSitesRequest", @@ -1544,8 +1615,18 @@ def _get_version(dependency_name): "BatchPauseLiveStreamsResponse", "BatchPauseOrdersRequest", "BatchPauseOrdersResponse", + "BatchPopulateAudienceSegmentsRequest", + "BatchPopulateAudienceSegmentsResponse", "BatchRefreshMasterPlaylistsRequest", "BatchRefreshMasterPlaylistsResponse", + "BatchRejectAudienceSegmentsRequest", + "BatchRejectAudienceSegmentsResponse", + "BatchRejectChildPublishersRequest", + "BatchRejectChildPublishersResponse", + "BatchRenegotiateChildPublisherAgreementsRequest", + "BatchRenegotiateChildPublisherAgreementsResponse", + "BatchResendChildPublisherInvitationEmailsRequest", + "BatchResendChildPublisherInvitationEmailsResponse", "BatchResumeAndOverbookOrdersRequest", "BatchResumeAndOverbookOrdersResponse", "BatchResumeOrdersRequest", @@ -1602,6 +1683,8 @@ def _get_version(dependency_name): "BatchUpdateLabelsResponse", "BatchUpdateLiveStreamsRequest", "BatchUpdateLiveStreamsResponse", + "BatchUpdateNativeStylesRequest", + "BatchUpdateNativeStylesResponse", "BatchUpdateOrdersRequest", "BatchUpdateOrdersResponse", "BatchUpdatePartnersRequest", @@ -1618,6 +1701,8 @@ def _get_version(dependency_name): "BatchUpdateTeamsResponse", "BatchUpdateViewabilityProvidersRequest", "BatchUpdateViewabilityProvidersResponse", + "BatchWithdrawChildPublishersRequest", + "BatchWithdrawChildPublishersResponse", "BrandLiftPartnerEnum", "Browser", "BrowserLanguage", @@ -1685,6 +1770,7 @@ def _get_version(dependency_name): "CreateEntitySignalsMappingRequest", "CreateLabelRequest", "CreateLiveStreamRequest", + "CreateNativeStyleRequest", "CreateOrderRequest", "CreatePlacementRequest", "CreatePrivateAuctionDealRequest", @@ -1753,6 +1839,7 @@ def _get_version(dependency_name): "DeactivateTargetingPresetRequest", "DealBuyerPermissionTypeEnum", "DealPriorityTierEnum", + "DefaultThirdPartyDataDeclaration", "DelegationAccountStatusEnum", "DelegationApprovalStatusEnum", "DelegationInvitationStatusEnum", @@ -1812,6 +1899,7 @@ def _get_version(dependency_name): "GetCustomTargetingValueRequest", "GetDaiAuthenticationKeyRequest", "GetDaiEncodingProfileRequest", + "GetDefaultThirdPartyDataDeclarationRequest", "GetDeviceCapabilityRequest", "GetDeviceCategoryRequest", "GetDeviceManufacturerRequest", @@ -1824,6 +1912,7 @@ def _get_version(dependency_name): "GetMobileCarrierRequest", "GetMobileDeviceRequest", "GetMobileDeviceSubmodelRequest", + "GetNativeStyleRequest", "GetNetworkRequest", "GetOperatingSystemRequest", "GetOperatingSystemVersionRequest", @@ -1951,6 +2040,8 @@ def _get_version(dependency_name): "ListMobileDeviceSubmodelsResponse", "ListMobileDevicesRequest", "ListMobileDevicesResponse", + "ListNativeStylesRequest", + "ListNativeStylesResponse", "ListNetworksRequest", "ListNetworksResponse", "ListOperatingSystemVersionsRequest", @@ -2012,6 +2103,9 @@ def _get_version(dependency_name): "MobileDeviceServiceClient", "MobileDeviceSubmodel", "MobileDeviceSubmodelServiceClient", + "NativeStyle", + "NativeStyleServiceClient", + "NativeStyleStatusEnum", "Network", "NetworkServiceClient", "NielsenCtvPacingEnum", @@ -2039,8 +2133,10 @@ def _get_version(dependency_name): "PrivateMarketplaceDealStatusEnum", "ProgrammaticBuyer", "ProgrammaticBuyerServiceClient", + "ProvisionTestNetworkRequest", "ReachPartnerEnum", "RefreshRateTypeEnum", + "RenegotiateChildPublisherAgreementRequest", "Report", "ReportDataTable", "ReportDefinition", @@ -2120,6 +2216,8 @@ def _get_version(dependency_name): "UpdateEntitySignalsMappingRequest", "UpdateLabelRequest", "UpdateLiveStreamRequest", + "UpdateNativeStyleRequest", + "UpdateNetworkRequest", "UpdateOrderRequest", "UpdatePartnerRequest", "UpdatePlacementRequest", diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json index b3bbb614b56b..40700cba28e9 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json +++ b/packages/google-ads-admanager/google/ads/admanager_v1/gapic_metadata.json @@ -269,6 +269,31 @@ "rest": { "libraryClient": "AudienceSegmentServiceClient", "rpcs": { + "BatchActivateAudienceSegments": { + "methods": [ + "batch_activate_audience_segments" + ] + }, + "BatchApproveAudienceSegments": { + "methods": [ + "batch_approve_audience_segments" + ] + }, + "BatchDeactivateAudienceSegments": { + "methods": [ + "batch_deactivate_audience_segments" + ] + }, + "BatchPopulateAudienceSegments": { + "methods": [ + "batch_populate_audience_segments" + ] + }, + "BatchRejectAudienceSegments": { + "methods": [ + "batch_reject_audience_segments" + ] + }, "GetAudienceSegment": { "methods": [ "get_audience_segment" @@ -399,11 +424,31 @@ "batch_create_child_publishers" ] }, + "BatchRejectChildPublishers": { + "methods": [ + "batch_reject_child_publishers" + ] + }, + "BatchRenegotiateChildPublisherAgreements": { + "methods": [ + "batch_renegotiate_child_publisher_agreements" + ] + }, + "BatchResendChildPublisherInvitationEmails": { + "methods": [ + "batch_resend_child_publisher_invitation_emails" + ] + }, "BatchUpdateChildPublishers": { "methods": [ "batch_update_child_publishers" ] }, + "BatchWithdrawChildPublishers": { + "methods": [ + "batch_withdraw_child_publishers" + ] + }, "CreateChildPublisher": { "methods": [ "create_child_publisher" @@ -1310,11 +1355,60 @@ } } }, + "NativeStyleService": { + "clients": { + "rest": { + "libraryClient": "NativeStyleServiceClient", + "rpcs": { + "BatchActivateNativeStyles": { + "methods": [ + "batch_activate_native_styles" + ] + }, + "BatchArchiveNativeStyles": { + "methods": [ + "batch_archive_native_styles" + ] + }, + "BatchCreateNativeStyles": { + "methods": [ + "batch_create_native_styles" + ] + }, + "BatchDeactivateNativeStyles": { + "methods": [ + "batch_deactivate_native_styles" + ] + }, + "BatchUpdateNativeStyles": { + "methods": [ + "batch_update_native_styles" + ] + }, + "GetNativeStyle": { + "methods": [ + "get_native_style" + ] + }, + "ListNativeStyles": { + "methods": [ + "list_native_styles" + ] + } + } + } + } + }, "NetworkService": { "clients": { "rest": { "libraryClient": "NetworkServiceClient", "rpcs": { + "GetDefaultThirdPartyDataDeclaration": { + "methods": [ + "get_default_third_party_data_declaration" + ] + }, "GetNetwork": { "methods": [ "get_network" @@ -1324,6 +1418,16 @@ "methods": [ "list_networks" ] + }, + "ProvisionTestNetwork": { + "methods": [ + "provision_test_network" + ] + }, + "UpdateNetwork": { + "methods": [ + "update_network" + ] } } } diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/client.py index 696f260bdc24..11289f01480f 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/client.py @@ -65,6 +65,7 @@ from google.ads.admanager_v1.services.audience_segment_service import pagers from google.ads.admanager_v1.types import ( + audience_segment_enums, audience_segment_messages, audience_segment_service, ) @@ -227,6 +228,23 @@ def transport(self) -> AudienceSegmentServiceTransport: """ return self._transport + @staticmethod + def ad_unit_path( + network_code: str, + ad_unit: str, + ) -> str: + """Returns a fully-qualified ad_unit string.""" + return "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + + @staticmethod + def parse_ad_unit_path(path: str) -> Dict[str, str]: + """Parses a ad_unit path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adUnits/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def audience_segment_path( network_code: str, @@ -247,6 +265,68 @@ def parse_audience_segment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def cms_metadata_value_path( + network_code: str, + cms_metadata_value: str, + ) -> str: + """Returns a fully-qualified cms_metadata_value string.""" + return "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + + @staticmethod + def parse_cms_metadata_value_path(path: str) -> Dict[str, str]: + """Parses a cms_metadata_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cmsMetadataValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_key_path( + network_code: str, + custom_targeting_key: str, + ) -> str: + """Returns a fully-qualified custom_targeting_key string.""" + return ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + + @staticmethod + def parse_custom_targeting_key_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_key path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_value_path( + network_code: str, + custom_targeting_value: str, + ) -> str: + """Returns a fully-qualified custom_targeting_value string.""" + return "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + + @staticmethod + def parse_custom_targeting_value_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def network_path( network_code: str, @@ -262,6 +342,25 @@ def parse_network_path(path: str) -> Dict[str, str]: m = re.match(r"^networks/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def placement_path( + network_code: str, + placement: str, + ) -> str: + """Returns a fully-qualified placement string.""" + return "networks/{network_code}/placements/{placement}".format( + network_code=network_code, + placement=placement, + ) + + @staticmethod + def parse_placement_path(path: str) -> Dict[str, str]: + """Parses a placement path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/placements/(?P.+?)$", path + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -983,6 +1082,634 @@ def sample_list_audience_segments(): # Done; return the response. return response + def batch_activate_audience_segments( + self, + request: Optional[ + Union[audience_segment_service.BatchActivateAudienceSegmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchActivateAudienceSegmentsResponse: + r"""Activates ``AudienceSegment`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateAudienceSegmentsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_activate_audience_segments(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateAudienceSegmentsRequest, dict]): + The request object. Request message for ``BatchActivateAudienceSegments`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. + Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchActivateAudienceSegmentsResponse: + Response message for BatchActivateAudienceSegments + 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 = [parent, names] + 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, audience_segment_service.BatchActivateAudienceSegmentsRequest + ): + request = audience_segment_service.BatchActivateAudienceSegmentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_activate_audience_segments + ] + + # 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 batch_deactivate_audience_segments( + self, + request: Optional[ + Union[audience_segment_service.BatchDeactivateAudienceSegmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchDeactivateAudienceSegmentsResponse: + r"""Deactivates ``AudienceSegment`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_deactivate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateAudienceSegmentsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_deactivate_audience_segments(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeactivateAudienceSegmentsRequest, dict]): + The request object. Request message for ``BatchDeactivateAudienceSegments`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. + Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchDeactivateAudienceSegmentsResponse: + Response message for BatchDeactivateAudienceSegments + 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 = [parent, names] + 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, audience_segment_service.BatchDeactivateAudienceSegmentsRequest + ): + request = audience_segment_service.BatchDeactivateAudienceSegmentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_deactivate_audience_segments + ] + + # 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 batch_approve_audience_segments( + self, + request: Optional[ + Union[audience_segment_service.BatchApproveAudienceSegmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchApproveAudienceSegmentsResponse: + r"""Approves ``AudienceSegment`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_approve_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchApproveAudienceSegmentsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_approve_audience_segments(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchApproveAudienceSegmentsRequest, dict]): + The request object. Request message for ``BatchApproveAudienceSegments`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. + Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchApproveAudienceSegmentsResponse: + Response message for BatchApproveAudienceSegments + 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 = [parent, names] + 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, audience_segment_service.BatchApproveAudienceSegmentsRequest + ): + request = audience_segment_service.BatchApproveAudienceSegmentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_approve_audience_segments + ] + + # 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 batch_reject_audience_segments( + self, + request: Optional[ + Union[audience_segment_service.BatchRejectAudienceSegmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchRejectAudienceSegmentsResponse: + r"""Rejects ``AudienceSegment`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_reject_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchRejectAudienceSegmentsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_reject_audience_segments(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchRejectAudienceSegmentsRequest, dict]): + The request object. Request message for ``BatchRejectAudienceSegments`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. + Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchRejectAudienceSegmentsResponse: + Response message for BatchRejectAudienceSegments 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 = [parent, names] + 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, audience_segment_service.BatchRejectAudienceSegmentsRequest + ): + request = audience_segment_service.BatchRejectAudienceSegmentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_reject_audience_segments + ] + + # 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 batch_populate_audience_segments( + self, + request: Optional[ + Union[audience_segment_service.BatchPopulateAudienceSegmentsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchPopulateAudienceSegmentsResponse: + r"""Populates ``AudienceSegment`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_populate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchPopulateAudienceSegmentsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_populate_audience_segments(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchPopulateAudienceSegmentsRequest, dict]): + The request object. Request message for ``BatchPopulateAudienceSegments`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. + Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchPopulateAudienceSegmentsResponse: + Response message for BatchPopulateAudienceSegments + 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 = [parent, names] + 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, audience_segment_service.BatchPopulateAudienceSegmentsRequest + ): + request = audience_segment_service.BatchPopulateAudienceSegmentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_populate_audience_segments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AudienceSegmentServiceClient": return self diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/base.py index 7468a760ec05..9cc77395103b 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/base.py @@ -157,6 +157,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.batch_activate_audience_segments: gapic_v1.method.wrap_method( + self.batch_activate_audience_segments, + default_timeout=None, + client_info=client_info, + ), + self.batch_deactivate_audience_segments: gapic_v1.method.wrap_method( + self.batch_deactivate_audience_segments, + default_timeout=None, + client_info=client_info, + ), + self.batch_approve_audience_segments: gapic_v1.method.wrap_method( + self.batch_approve_audience_segments, + default_timeout=None, + client_info=client_info, + ), + self.batch_reject_audience_segments: gapic_v1.method.wrap_method( + self.batch_reject_audience_segments, + default_timeout=None, + client_info=client_info, + ), + self.batch_populate_audience_segments: gapic_v1.method.wrap_method( + self.batch_populate_audience_segments, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -202,6 +227,66 @@ def list_audience_segments( ]: raise NotImplementedError() + @property + def batch_activate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchActivateAudienceSegmentsRequest], + Union[ + audience_segment_service.BatchActivateAudienceSegmentsResponse, + Awaitable[audience_segment_service.BatchActivateAudienceSegmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_deactivate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchDeactivateAudienceSegmentsRequest], + Union[ + audience_segment_service.BatchDeactivateAudienceSegmentsResponse, + Awaitable[audience_segment_service.BatchDeactivateAudienceSegmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_approve_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchApproveAudienceSegmentsRequest], + Union[ + audience_segment_service.BatchApproveAudienceSegmentsResponse, + Awaitable[audience_segment_service.BatchApproveAudienceSegmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_reject_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchRejectAudienceSegmentsRequest], + Union[ + audience_segment_service.BatchRejectAudienceSegmentsResponse, + Awaitable[audience_segment_service.BatchRejectAudienceSegmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_populate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchPopulateAudienceSegmentsRequest], + Union[ + audience_segment_service.BatchPopulateAudienceSegmentsResponse, + Awaitable[audience_segment_service.BatchPopulateAudienceSegmentsResponse], + ], + ]: + raise NotImplementedError() + @property def get_operation( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest.py index 03ac326d0324..58869590249d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest.py @@ -75,6 +75,46 @@ class AudienceSegmentServiceRestInterceptor: .. code-block:: python class MyCustomAudienceSegmentServiceInterceptor(AudienceSegmentServiceRestInterceptor): + def pre_batch_activate_audience_segments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_audience_segments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_approve_audience_segments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_approve_audience_segments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_deactivate_audience_segments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_deactivate_audience_segments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_populate_audience_segments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_populate_audience_segments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_reject_audience_segments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_reject_audience_segments(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_audience_segment(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -97,6 +137,266 @@ def post_list_audience_segments(self, response): """ + def pre_batch_activate_audience_segments( + self, + request: audience_segment_service.BatchActivateAudienceSegmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchActivateAudienceSegmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_audience_segments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AudienceSegmentService server. + """ + return request, metadata + + def post_batch_activate_audience_segments( + self, response: audience_segment_service.BatchActivateAudienceSegmentsResponse + ) -> audience_segment_service.BatchActivateAudienceSegmentsResponse: + """Post-rpc interceptor for batch_activate_audience_segments + + DEPRECATED. Please use the `post_batch_activate_audience_segments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AudienceSegmentService server but before + it is returned to user code. This `post_batch_activate_audience_segments` interceptor runs + before the `post_batch_activate_audience_segments_with_metadata` interceptor. + """ + return response + + def post_batch_activate_audience_segments_with_metadata( + self, + response: audience_segment_service.BatchActivateAudienceSegmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchActivateAudienceSegmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_audience_segments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AudienceSegmentService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_audience_segments_with_metadata` + interceptor in new development instead of the `post_batch_activate_audience_segments` interceptor. + When both interceptors are used, this `post_batch_activate_audience_segments_with_metadata` interceptor runs after the + `post_batch_activate_audience_segments` interceptor. The (possibly modified) response returned by + `post_batch_activate_audience_segments` will be passed to + `post_batch_activate_audience_segments_with_metadata`. + """ + return response, metadata + + def pre_batch_approve_audience_segments( + self, + request: audience_segment_service.BatchApproveAudienceSegmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchApproveAudienceSegmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_approve_audience_segments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AudienceSegmentService server. + """ + return request, metadata + + def post_batch_approve_audience_segments( + self, response: audience_segment_service.BatchApproveAudienceSegmentsResponse + ) -> audience_segment_service.BatchApproveAudienceSegmentsResponse: + """Post-rpc interceptor for batch_approve_audience_segments + + DEPRECATED. Please use the `post_batch_approve_audience_segments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AudienceSegmentService server but before + it is returned to user code. This `post_batch_approve_audience_segments` interceptor runs + before the `post_batch_approve_audience_segments_with_metadata` interceptor. + """ + return response + + def post_batch_approve_audience_segments_with_metadata( + self, + response: audience_segment_service.BatchApproveAudienceSegmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchApproveAudienceSegmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_approve_audience_segments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AudienceSegmentService server but before it is returned to user code. + + We recommend only using this `post_batch_approve_audience_segments_with_metadata` + interceptor in new development instead of the `post_batch_approve_audience_segments` interceptor. + When both interceptors are used, this `post_batch_approve_audience_segments_with_metadata` interceptor runs after the + `post_batch_approve_audience_segments` interceptor. The (possibly modified) response returned by + `post_batch_approve_audience_segments` will be passed to + `post_batch_approve_audience_segments_with_metadata`. + """ + return response, metadata + + def pre_batch_deactivate_audience_segments( + self, + request: audience_segment_service.BatchDeactivateAudienceSegmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchDeactivateAudienceSegmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_deactivate_audience_segments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AudienceSegmentService server. + """ + return request, metadata + + def post_batch_deactivate_audience_segments( + self, response: audience_segment_service.BatchDeactivateAudienceSegmentsResponse + ) -> audience_segment_service.BatchDeactivateAudienceSegmentsResponse: + """Post-rpc interceptor for batch_deactivate_audience_segments + + DEPRECATED. Please use the `post_batch_deactivate_audience_segments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AudienceSegmentService server but before + it is returned to user code. This `post_batch_deactivate_audience_segments` interceptor runs + before the `post_batch_deactivate_audience_segments_with_metadata` interceptor. + """ + return response + + def post_batch_deactivate_audience_segments_with_metadata( + self, + response: audience_segment_service.BatchDeactivateAudienceSegmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchDeactivateAudienceSegmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_deactivate_audience_segments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AudienceSegmentService server but before it is returned to user code. + + We recommend only using this `post_batch_deactivate_audience_segments_with_metadata` + interceptor in new development instead of the `post_batch_deactivate_audience_segments` interceptor. + When both interceptors are used, this `post_batch_deactivate_audience_segments_with_metadata` interceptor runs after the + `post_batch_deactivate_audience_segments` interceptor. The (possibly modified) response returned by + `post_batch_deactivate_audience_segments` will be passed to + `post_batch_deactivate_audience_segments_with_metadata`. + """ + return response, metadata + + def pre_batch_populate_audience_segments( + self, + request: audience_segment_service.BatchPopulateAudienceSegmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchPopulateAudienceSegmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_populate_audience_segments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AudienceSegmentService server. + """ + return request, metadata + + def post_batch_populate_audience_segments( + self, response: audience_segment_service.BatchPopulateAudienceSegmentsResponse + ) -> audience_segment_service.BatchPopulateAudienceSegmentsResponse: + """Post-rpc interceptor for batch_populate_audience_segments + + DEPRECATED. Please use the `post_batch_populate_audience_segments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AudienceSegmentService server but before + it is returned to user code. This `post_batch_populate_audience_segments` interceptor runs + before the `post_batch_populate_audience_segments_with_metadata` interceptor. + """ + return response + + def post_batch_populate_audience_segments_with_metadata( + self, + response: audience_segment_service.BatchPopulateAudienceSegmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchPopulateAudienceSegmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_populate_audience_segments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AudienceSegmentService server but before it is returned to user code. + + We recommend only using this `post_batch_populate_audience_segments_with_metadata` + interceptor in new development instead of the `post_batch_populate_audience_segments` interceptor. + When both interceptors are used, this `post_batch_populate_audience_segments_with_metadata` interceptor runs after the + `post_batch_populate_audience_segments` interceptor. The (possibly modified) response returned by + `post_batch_populate_audience_segments` will be passed to + `post_batch_populate_audience_segments_with_metadata`. + """ + return response, metadata + + def pre_batch_reject_audience_segments( + self, + request: audience_segment_service.BatchRejectAudienceSegmentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchRejectAudienceSegmentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_reject_audience_segments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AudienceSegmentService server. + """ + return request, metadata + + def post_batch_reject_audience_segments( + self, response: audience_segment_service.BatchRejectAudienceSegmentsResponse + ) -> audience_segment_service.BatchRejectAudienceSegmentsResponse: + """Post-rpc interceptor for batch_reject_audience_segments + + DEPRECATED. Please use the `post_batch_reject_audience_segments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AudienceSegmentService server but before + it is returned to user code. This `post_batch_reject_audience_segments` interceptor runs + before the `post_batch_reject_audience_segments_with_metadata` interceptor. + """ + return response + + def post_batch_reject_audience_segments_with_metadata( + self, + response: audience_segment_service.BatchRejectAudienceSegmentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + audience_segment_service.BatchRejectAudienceSegmentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_reject_audience_segments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AudienceSegmentService server but before it is returned to user code. + + We recommend only using this `post_batch_reject_audience_segments_with_metadata` + interceptor in new development instead of the `post_batch_reject_audience_segments` interceptor. + When both interceptors are used, this `post_batch_reject_audience_segments_with_metadata` interceptor runs after the + `post_batch_reject_audience_segments` interceptor. The (possibly modified) response returned by + `post_batch_reject_audience_segments` will be passed to + `post_batch_reject_audience_segments_with_metadata`. + """ + return response, metadata + def pre_get_audience_segment( self, request: audience_segment_service.GetAudienceSegmentRequest, @@ -343,12 +643,14 @@ def __init__( self._interceptor = interceptor or AudienceSegmentServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetAudienceSegment( - _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment, + class _BatchActivateAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments, AudienceSegmentServiceRestStub, ): def __hash__(self): - return hash("AudienceSegmentServiceRestTransport.GetAudienceSegment") + return hash( + "AudienceSegmentServiceRestTransport.BatchActivateAudienceSegments" + ) @staticmethod def _get_response( @@ -369,46 +671,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: audience_segment_service.GetAudienceSegmentRequest, + request: audience_segment_service.BatchActivateAudienceSegmentsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> audience_segment_messages.AudienceSegment: - r"""Call the get audience segment method over HTTP. + ) -> audience_segment_service.BatchActivateAudienceSegmentsResponse: + r"""Call the batch activate audience + segments method over HTTP. + + Args: + request (~.audience_segment_service.BatchActivateAudienceSegmentsRequest): + The request object. Request message for ``BatchActivateAudienceSegments`` + 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: + ~.audience_segment_service.BatchActivateAudienceSegmentsResponse: + Response message for ``BatchActivateAudienceSegments`` + method. - Args: - request (~.audience_segment_service.GetAudienceSegmentRequest): - The request object. Request object for ``GetAudienceSegment`` 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: - ~.audience_segment_messages.AudienceSegment: - The ``AudienceSegment`` resource. """ - http_options = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._get_http_options() + http_options = _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments._get_http_options() - request, metadata = self._interceptor.pre_get_audience_segment( + request, metadata = self._interceptor.pre_batch_activate_audience_segments( request, metadata ) - transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._get_transcoded_request( + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments._get_transcoded_request( http_options, request ) + body = _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._get_query_params_json( + query_params = _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments._get_query_params_json( transcoded_request ) @@ -430,25 +741,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.ads.admanager_v1.AudienceSegmentServiceClient.GetAudienceSegment", + f"Sending request for google.ads.admanager_v1.AudienceSegmentServiceClient.BatchActivateAudienceSegments", extra={ "serviceName": "google.ads.admanager.v1.AudienceSegmentService", - "rpcName": "GetAudienceSegment", + "rpcName": "BatchActivateAudienceSegments", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - AudienceSegmentServiceRestTransport._GetAudienceSegment._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = AudienceSegmentServiceRestTransport._BatchActivateAudienceSegments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -457,22 +767,26 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = audience_segment_messages.AudienceSegment() - pb_resp = audience_segment_messages.AudienceSegment.pb(resp) + resp = audience_segment_service.BatchActivateAudienceSegmentsResponse() + pb_resp = audience_segment_service.BatchActivateAudienceSegmentsResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_audience_segment(resp) + resp = self._interceptor.post_batch_activate_audience_segments(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_audience_segment_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_batch_activate_audience_segments_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - audience_segment_messages.AudienceSegment.to_json(response) + response_payload = audience_segment_service.BatchActivateAudienceSegmentsResponse.to_json( + response ) except: response_payload = None @@ -482,22 +796,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.ads.admanager_v1.AudienceSegmentServiceClient.get_audience_segment", + "Received response for google.ads.admanager_v1.AudienceSegmentServiceClient.batch_activate_audience_segments", extra={ "serviceName": "google.ads.admanager.v1.AudienceSegmentService", - "rpcName": "GetAudienceSegment", + "rpcName": "BatchActivateAudienceSegments", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAudienceSegments( - _BaseAudienceSegmentServiceRestTransport._BaseListAudienceSegments, + class _BatchApproveAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments, AudienceSegmentServiceRestStub, ): def __hash__(self): - return hash("AudienceSegmentServiceRestTransport.ListAudienceSegments") + return hash( + "AudienceSegmentServiceRestTransport.BatchApproveAudienceSegments" + ) @staticmethod def _get_response( @@ -518,27 +834,830 @@ 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: audience_segment_service.ListAudienceSegmentsRequest, + request: audience_segment_service.BatchApproveAudienceSegmentsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> audience_segment_service.ListAudienceSegmentsResponse: - r"""Call the list audience segments method over HTTP. + ) -> audience_segment_service.BatchApproveAudienceSegmentsResponse: + r"""Call the batch approve audience + segments method over HTTP. + + Args: + request (~.audience_segment_service.BatchApproveAudienceSegmentsRequest): + The request object. Request message for ``BatchApproveAudienceSegments`` + 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: + ~.audience_segment_service.BatchApproveAudienceSegmentsResponse: + Response message for ``BatchApproveAudienceSegments`` + method. - Args: - request (~.audience_segment_service.ListAudienceSegmentsRequest): - The request object. Request object for ``ListAudienceSegments`` 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`, + """ + + http_options = _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments._get_http_options() + + request, metadata = self._interceptor.pre_batch_approve_audience_segments( + request, metadata + ) + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments._get_transcoded_request( + http_options, request + ) + + body = _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments._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.ads.admanager_v1.AudienceSegmentServiceClient.BatchApproveAudienceSegments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchApproveAudienceSegments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AudienceSegmentServiceRestTransport._BatchApproveAudienceSegments._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 = audience_segment_service.BatchApproveAudienceSegmentsResponse() + pb_resp = audience_segment_service.BatchApproveAudienceSegmentsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_approve_audience_segments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_approve_audience_segments_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = audience_segment_service.BatchApproveAudienceSegmentsResponse.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.ads.admanager_v1.AudienceSegmentServiceClient.batch_approve_audience_segments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchApproveAudienceSegments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeactivateAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments, + AudienceSegmentServiceRestStub, + ): + def __hash__(self): + return hash( + "AudienceSegmentServiceRestTransport.BatchDeactivateAudienceSegments" + ) + + @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: audience_segment_service.BatchDeactivateAudienceSegmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchDeactivateAudienceSegmentsResponse: + r"""Call the batch deactivate audience + segments method over HTTP. + + Args: + request (~.audience_segment_service.BatchDeactivateAudienceSegmentsRequest): + The request object. Request message for ``BatchDeactivateAudienceSegments`` + 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: + ~.audience_segment_service.BatchDeactivateAudienceSegmentsResponse: + Response message for ``BatchDeactivateAudienceSegments`` + method. + + """ + + http_options = _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments._get_http_options() + + request, metadata = ( + self._interceptor.pre_batch_deactivate_audience_segments( + request, metadata + ) + ) + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments._get_transcoded_request( + http_options, request + ) + + body = _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments._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.ads.admanager_v1.AudienceSegmentServiceClient.BatchDeactivateAudienceSegments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchDeactivateAudienceSegments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AudienceSegmentServiceRestTransport._BatchDeactivateAudienceSegments._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 = audience_segment_service.BatchDeactivateAudienceSegmentsResponse() + pb_resp = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_deactivate_audience_segments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_deactivate_audience_segments_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = audience_segment_service.BatchDeactivateAudienceSegmentsResponse.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.ads.admanager_v1.AudienceSegmentServiceClient.batch_deactivate_audience_segments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchDeactivateAudienceSegments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchPopulateAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments, + AudienceSegmentServiceRestStub, + ): + def __hash__(self): + return hash( + "AudienceSegmentServiceRestTransport.BatchPopulateAudienceSegments" + ) + + @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: audience_segment_service.BatchPopulateAudienceSegmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchPopulateAudienceSegmentsResponse: + r"""Call the batch populate audience + segments method over HTTP. + + Args: + request (~.audience_segment_service.BatchPopulateAudienceSegmentsRequest): + The request object. Request message for ``BatchPopulateAudienceSegments`` + 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: + ~.audience_segment_service.BatchPopulateAudienceSegmentsResponse: + Response message for ``BatchPopulateAudienceSegments`` + method. + + """ + + http_options = _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments._get_http_options() + + request, metadata = self._interceptor.pre_batch_populate_audience_segments( + request, metadata + ) + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments._get_transcoded_request( + http_options, request + ) + + body = _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments._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.ads.admanager_v1.AudienceSegmentServiceClient.BatchPopulateAudienceSegments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchPopulateAudienceSegments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AudienceSegmentServiceRestTransport._BatchPopulateAudienceSegments._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 = audience_segment_service.BatchPopulateAudienceSegmentsResponse() + pb_resp = audience_segment_service.BatchPopulateAudienceSegmentsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_populate_audience_segments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_populate_audience_segments_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = audience_segment_service.BatchPopulateAudienceSegmentsResponse.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.ads.admanager_v1.AudienceSegmentServiceClient.batch_populate_audience_segments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchPopulateAudienceSegments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchRejectAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments, + AudienceSegmentServiceRestStub, + ): + def __hash__(self): + return hash( + "AudienceSegmentServiceRestTransport.BatchRejectAudienceSegments" + ) + + @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: audience_segment_service.BatchRejectAudienceSegmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.BatchRejectAudienceSegmentsResponse: + r"""Call the batch reject audience + segments method over HTTP. + + Args: + request (~.audience_segment_service.BatchRejectAudienceSegmentsRequest): + The request object. Request message for ``BatchRejectAudienceSegments`` + 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: + ~.audience_segment_service.BatchRejectAudienceSegmentsResponse: + Response message for ``BatchRejectAudienceSegments`` + method. + + """ + + http_options = _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments._get_http_options() + + request, metadata = self._interceptor.pre_batch_reject_audience_segments( + request, metadata + ) + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments._get_transcoded_request( + http_options, request + ) + + body = _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments._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.ads.admanager_v1.AudienceSegmentServiceClient.BatchRejectAudienceSegments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchRejectAudienceSegments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AudienceSegmentServiceRestTransport._BatchRejectAudienceSegments._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 = audience_segment_service.BatchRejectAudienceSegmentsResponse() + pb_resp = audience_segment_service.BatchRejectAudienceSegmentsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_reject_audience_segments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_reject_audience_segments_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = audience_segment_service.BatchRejectAudienceSegmentsResponse.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.ads.admanager_v1.AudienceSegmentServiceClient.batch_reject_audience_segments", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "BatchRejectAudienceSegments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAudienceSegment( + _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment, + AudienceSegmentServiceRestStub, + ): + def __hash__(self): + return hash("AudienceSegmentServiceRestTransport.GetAudienceSegment") + + @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: audience_segment_service.GetAudienceSegmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_messages.AudienceSegment: + r"""Call the get audience segment method over HTTP. + + Args: + request (~.audience_segment_service.GetAudienceSegmentRequest): + The request object. Request object for ``GetAudienceSegment`` 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: + ~.audience_segment_messages.AudienceSegment: + The ``AudienceSegment`` resource. + """ + + http_options = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._get_http_options() + + request, metadata = self._interceptor.pre_get_audience_segment( + request, metadata + ) + transcoded_request = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAudienceSegmentServiceRestTransport._BaseGetAudienceSegment._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.ads.admanager_v1.AudienceSegmentServiceClient.GetAudienceSegment", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "GetAudienceSegment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AudienceSegmentServiceRestTransport._GetAudienceSegment._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 = audience_segment_messages.AudienceSegment() + pb_resp = audience_segment_messages.AudienceSegment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_audience_segment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_audience_segment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + audience_segment_messages.AudienceSegment.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.ads.admanager_v1.AudienceSegmentServiceClient.get_audience_segment", + extra={ + "serviceName": "google.ads.admanager.v1.AudienceSegmentService", + "rpcName": "GetAudienceSegment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAudienceSegments( + _BaseAudienceSegmentServiceRestTransport._BaseListAudienceSegments, + AudienceSegmentServiceRestStub, + ): + def __hash__(self): + return hash("AudienceSegmentServiceRestTransport.ListAudienceSegments") + + @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: audience_segment_service.ListAudienceSegmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> audience_segment_service.ListAudienceSegmentsResponse: + r"""Call the list audience segments method over HTTP. + + Args: + request (~.audience_segment_service.ListAudienceSegmentsRequest): + The request object. Request object for ``ListAudienceSegments`` 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`. @@ -645,6 +1764,71 @@ def __call__( ) return resp + @property + def batch_activate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchActivateAudienceSegmentsRequest], + audience_segment_service.BatchActivateAudienceSegmentsResponse, + ]: + # 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._BatchActivateAudienceSegments( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_approve_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchApproveAudienceSegmentsRequest], + audience_segment_service.BatchApproveAudienceSegmentsResponse, + ]: + # 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._BatchApproveAudienceSegments( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_deactivate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchDeactivateAudienceSegmentsRequest], + audience_segment_service.BatchDeactivateAudienceSegmentsResponse, + ]: + # 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._BatchDeactivateAudienceSegments( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_populate_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchPopulateAudienceSegmentsRequest], + audience_segment_service.BatchPopulateAudienceSegmentsResponse, + ]: + # 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._BatchPopulateAudienceSegments( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_reject_audience_segments( + self, + ) -> Callable[ + [audience_segment_service.BatchRejectAudienceSegmentsRequest], + audience_segment_service.BatchRejectAudienceSegmentsResponse, + ]: + # 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._BatchRejectAudienceSegments( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_audience_segment( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest_base.py index 22d6afeca1f0..54a6ef88348d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest_base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/audience_segment_service/transports/rest_base.py @@ -91,6 +91,307 @@ def __init__( api_audience=api_audience, ) + class _BaseBatchActivateAudienceSegments: + 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=networks/*}/audienceSegments:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + audience_segment_service.BatchActivateAudienceSegmentsRequest.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( + _BaseAudienceSegmentServiceRestTransport._BaseBatchActivateAudienceSegments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchApproveAudienceSegments: + 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=networks/*}/audienceSegments:batchApprove", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + audience_segment_service.BatchApproveAudienceSegmentsRequest.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( + _BaseAudienceSegmentServiceRestTransport._BaseBatchApproveAudienceSegments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeactivateAudienceSegments: + 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=networks/*}/audienceSegments:batchDeactivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + audience_segment_service.BatchDeactivateAudienceSegmentsRequest.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( + _BaseAudienceSegmentServiceRestTransport._BaseBatchDeactivateAudienceSegments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchPopulateAudienceSegments: + 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=networks/*}/audienceSegments:batchPopulate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + audience_segment_service.BatchPopulateAudienceSegmentsRequest.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( + _BaseAudienceSegmentServiceRestTransport._BaseBatchPopulateAudienceSegments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchRejectAudienceSegments: + 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=networks/*}/audienceSegments:batchReject", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = audience_segment_service.BatchRejectAudienceSegmentsRequest.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( + _BaseAudienceSegmentServiceRestTransport._BaseBatchRejectAudienceSegments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetAudienceSegment: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/client.py index 0f2b77e5ceb5..6f3eadbaa726 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/client.py @@ -1513,6 +1513,565 @@ def sample_batch_update_child_publishers(): # Done; return the response. return response + def batch_resend_child_publisher_invitation_emails( + self, + request: Optional[ + Union[ + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse: + r"""Batch resends invitation emails to + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s. + + Only expired and pending + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s can be + sent invitation emails. Rejected, withdrawn, and accepted + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s will + be ignored. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_resend_child_publisher_invitation_emails(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchResendChildPublisherInvitationEmailsRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_resend_child_publisher_invitation_emails(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchResendChildPublisherInvitationEmailsRequest, dict]): + The request object. Request message for + [BatchResendChildPublisherInvitationEmails][] method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s + that should be resent invitation emails. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchResendChildPublisherInvitationEmailsResponse: + Response message for + [BatchResendChildPublisherInvitationEmails][] 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 = [parent, names] + 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, + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, + ): + request = child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_resend_child_publisher_invitation_emails + ] + + # 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 batch_renegotiate_child_publisher_agreements( + self, + request: Optional[ + Union[ + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[ + child_publisher_service.RenegotiateChildPublisherAgreementRequest + ] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse: + r"""Batch renegotiates + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + agreements (i.e., invite with updated terms). + + Only the agreements of rejected or withdrawn + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s can be + renegotiated. Expired, pending, and accepted + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s will + be ignored. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_renegotiate_child_publisher_agreements(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.RenegotiateChildPublisherAgreementRequest() + requests.name = "name_value" + + request = admanager_v1.BatchRenegotiateChildPublisherAgreementsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_renegotiate_child_publisher_agreements(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchRenegotiateChildPublisherAgreementsRequest, dict]): + The request object. Request message for + [BatchRenegotiateChildPublisherAgreements][] method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.RenegotiateChildPublisherAgreementRequest]): + Required. The requests to renegotiate + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + agreements. + + This corresponds to the ``requests`` 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.ads.admanager_v1.types.BatchRenegotiateChildPublisherAgreementsResponse: + Response message for + [BatchRenegotiateChildPublisherAgreements][] 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 = [parent, requests] + 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, + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, + ): + request = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_renegotiate_child_publisher_agreements + ] + + # 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 batch_reject_child_publishers( + self, + request: Optional[ + Union[child_publisher_service.BatchRejectChildPublishersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchRejectChildPublishersResponse: + r"""Batch rejects + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s. + + Only pending or active + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s can be + rejected. Expired, rejected, and withdrawn + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s will + be ignored. + + This method is only intended to be called in response to a child + user rejecting an invitation and exists to support the rejection + of [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s + that are not yet associated with an Ad Manager network. + + To sever the relationship from the parent publisher's side, use + [BatchWithdrawChildPublisher][]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_reject_child_publishers(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchRejectChildPublishersRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_reject_child_publishers(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchRejectChildPublishersRequest, dict]): + The request object. Request message for [BatchRejectChildPublishers][] + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s + to reject. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchRejectChildPublishersResponse: + Response message for [BatchRejectChildPublishers][] + 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 = [parent, names] + 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, child_publisher_service.BatchRejectChildPublishersRequest + ): + request = child_publisher_service.BatchRejectChildPublishersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_reject_child_publishers + ] + + # 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 batch_withdraw_child_publishers( + self, + request: Optional[ + Union[child_publisher_service.BatchWithdrawChildPublishersRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchWithdrawChildPublishersResponse: + r"""Batch withdraws + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s. + + Only expired, pending, and accepted + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s can be + withdrawn. Rejected or withdrawn + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s will + be ignored. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_withdraw_child_publishers(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchWithdrawChildPublishersRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_withdraw_child_publishers(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchWithdrawChildPublishersRequest, dict]): + The request object. Request message for [BatchWithdrawChildPublishers][] + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s + to withdraw. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchWithdrawChildPublishersResponse: + Response message for [BatchWithdrawChildPublishers][] + 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 = [parent, names] + 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, child_publisher_service.BatchWithdrawChildPublishersRequest + ): + request = child_publisher_service.BatchWithdrawChildPublishersRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_withdraw_child_publishers + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ChildPublisherServiceClient": return self diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/base.py index 1fdcebe123ba..d078f8f534c9 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/base.py @@ -177,6 +177,26 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.batch_resend_child_publisher_invitation_emails: gapic_v1.method.wrap_method( + self.batch_resend_child_publisher_invitation_emails, + default_timeout=None, + client_info=client_info, + ), + self.batch_renegotiate_child_publisher_agreements: gapic_v1.method.wrap_method( + self.batch_renegotiate_child_publisher_agreements, + default_timeout=None, + client_info=client_info, + ), + self.batch_reject_child_publishers: gapic_v1.method.wrap_method( + self.batch_reject_child_publishers, + default_timeout=None, + client_info=client_info, + ), + self.batch_withdraw_child_publishers: gapic_v1.method.wrap_method( + self.batch_withdraw_child_publishers, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -270,6 +290,58 @@ def batch_update_child_publishers( ]: raise NotImplementedError() + @property + def batch_resend_child_publisher_invitation_emails( + self, + ) -> Callable[ + [child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest], + Union[ + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, + Awaitable[ + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def batch_renegotiate_child_publisher_agreements( + self, + ) -> Callable[ + [child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest], + Union[ + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + Awaitable[ + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def batch_reject_child_publishers( + self, + ) -> Callable[ + [child_publisher_service.BatchRejectChildPublishersRequest], + Union[ + child_publisher_service.BatchRejectChildPublishersResponse, + Awaitable[child_publisher_service.BatchRejectChildPublishersResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_withdraw_child_publishers( + self, + ) -> Callable[ + [child_publisher_service.BatchWithdrawChildPublishersRequest], + Union[ + child_publisher_service.BatchWithdrawChildPublishersResponse, + Awaitable[child_publisher_service.BatchWithdrawChildPublishersResponse], + ], + ]: + raise NotImplementedError() + @property def get_operation( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest.py index 8bd1734017f3..231bc5b0e472 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest.py @@ -83,6 +83,30 @@ def post_batch_create_child_publishers(self, response): logging.log(f"Received response: {response}") return response + def pre_batch_reject_child_publishers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_reject_child_publishers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_renegotiate_child_publisher_agreements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_renegotiate_child_publisher_agreements(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_resend_child_publisher_invitation_emails(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_resend_child_publisher_invitation_emails(self, response): + logging.log(f"Received response: {response}") + return response + def pre_batch_update_child_publishers(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -91,6 +115,14 @@ def post_batch_update_child_publishers(self, response): logging.log(f"Received response: {response}") return response + def pre_batch_withdraw_child_publishers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_withdraw_child_publishers(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_child_publisher(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -181,6 +213,164 @@ def post_batch_create_child_publishers_with_metadata( """ return response, metadata + def pre_batch_reject_child_publishers( + self, + request: child_publisher_service.BatchRejectChildPublishersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchRejectChildPublishersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_reject_child_publishers + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChildPublisherService server. + """ + return request, metadata + + def post_batch_reject_child_publishers( + self, response: child_publisher_service.BatchRejectChildPublishersResponse + ) -> child_publisher_service.BatchRejectChildPublishersResponse: + """Post-rpc interceptor for batch_reject_child_publishers + + DEPRECATED. Please use the `post_batch_reject_child_publishers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChildPublisherService server but before + it is returned to user code. This `post_batch_reject_child_publishers` interceptor runs + before the `post_batch_reject_child_publishers_with_metadata` interceptor. + """ + return response + + def post_batch_reject_child_publishers_with_metadata( + self, + response: child_publisher_service.BatchRejectChildPublishersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchRejectChildPublishersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_reject_child_publishers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChildPublisherService server but before it is returned to user code. + + We recommend only using this `post_batch_reject_child_publishers_with_metadata` + interceptor in new development instead of the `post_batch_reject_child_publishers` interceptor. + When both interceptors are used, this `post_batch_reject_child_publishers_with_metadata` interceptor runs after the + `post_batch_reject_child_publishers` interceptor. The (possibly modified) response returned by + `post_batch_reject_child_publishers` will be passed to + `post_batch_reject_child_publishers_with_metadata`. + """ + return response, metadata + + def pre_batch_renegotiate_child_publisher_agreements( + self, + request: child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_renegotiate_child_publisher_agreements + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChildPublisherService server. + """ + return request, metadata + + def post_batch_renegotiate_child_publisher_agreements( + self, + response: child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + ) -> child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse: + """Post-rpc interceptor for batch_renegotiate_child_publisher_agreements + + DEPRECATED. Please use the `post_batch_renegotiate_child_publisher_agreements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChildPublisherService server but before + it is returned to user code. This `post_batch_renegotiate_child_publisher_agreements` interceptor runs + before the `post_batch_renegotiate_child_publisher_agreements_with_metadata` interceptor. + """ + return response + + def post_batch_renegotiate_child_publisher_agreements_with_metadata( + self, + response: child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_renegotiate_child_publisher_agreements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChildPublisherService server but before it is returned to user code. + + We recommend only using this `post_batch_renegotiate_child_publisher_agreements_with_metadata` + interceptor in new development instead of the `post_batch_renegotiate_child_publisher_agreements` interceptor. + When both interceptors are used, this `post_batch_renegotiate_child_publisher_agreements_with_metadata` interceptor runs after the + `post_batch_renegotiate_child_publisher_agreements` interceptor. The (possibly modified) response returned by + `post_batch_renegotiate_child_publisher_agreements` will be passed to + `post_batch_renegotiate_child_publisher_agreements_with_metadata`. + """ + return response, metadata + + def pre_batch_resend_child_publisher_invitation_emails( + self, + request: child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_resend_child_publisher_invitation_emails + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChildPublisherService server. + """ + return request, metadata + + def post_batch_resend_child_publisher_invitation_emails( + self, + response: child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, + ) -> child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse: + """Post-rpc interceptor for batch_resend_child_publisher_invitation_emails + + DEPRECATED. Please use the `post_batch_resend_child_publisher_invitation_emails_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChildPublisherService server but before + it is returned to user code. This `post_batch_resend_child_publisher_invitation_emails` interceptor runs + before the `post_batch_resend_child_publisher_invitation_emails_with_metadata` interceptor. + """ + return response + + def post_batch_resend_child_publisher_invitation_emails_with_metadata( + self, + response: child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_resend_child_publisher_invitation_emails + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChildPublisherService server but before it is returned to user code. + + We recommend only using this `post_batch_resend_child_publisher_invitation_emails_with_metadata` + interceptor in new development instead of the `post_batch_resend_child_publisher_invitation_emails` interceptor. + When both interceptors are used, this `post_batch_resend_child_publisher_invitation_emails_with_metadata` interceptor runs after the + `post_batch_resend_child_publisher_invitation_emails` interceptor. The (possibly modified) response returned by + `post_batch_resend_child_publisher_invitation_emails` will be passed to + `post_batch_resend_child_publisher_invitation_emails_with_metadata`. + """ + return response, metadata + def pre_batch_update_child_publishers( self, request: child_publisher_service.BatchUpdateChildPublishersRequest, @@ -233,6 +423,58 @@ def post_batch_update_child_publishers_with_metadata( """ return response, metadata + def pre_batch_withdraw_child_publishers( + self, + request: child_publisher_service.BatchWithdrawChildPublishersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchWithdrawChildPublishersRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_withdraw_child_publishers + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChildPublisherService server. + """ + return request, metadata + + def post_batch_withdraw_child_publishers( + self, response: child_publisher_service.BatchWithdrawChildPublishersResponse + ) -> child_publisher_service.BatchWithdrawChildPublishersResponse: + """Post-rpc interceptor for batch_withdraw_child_publishers + + DEPRECATED. Please use the `post_batch_withdraw_child_publishers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ChildPublisherService server but before + it is returned to user code. This `post_batch_withdraw_child_publishers` interceptor runs + before the `post_batch_withdraw_child_publishers_with_metadata` interceptor. + """ + return response + + def post_batch_withdraw_child_publishers_with_metadata( + self, + response: child_publisher_service.BatchWithdrawChildPublishersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + child_publisher_service.BatchWithdrawChildPublishersResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_withdraw_child_publishers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ChildPublisherService server but before it is returned to user code. + + We recommend only using this `post_batch_withdraw_child_publishers_with_metadata` + interceptor in new development instead of the `post_batch_withdraw_child_publishers` interceptor. + When both interceptors are used, this `post_batch_withdraw_child_publishers_with_metadata` interceptor runs after the + `post_batch_withdraw_child_publishers` interceptor. The (possibly modified) response returned by + `post_batch_withdraw_child_publishers` will be passed to + `post_batch_withdraw_child_publishers_with_metadata`. + """ + return response, metadata + def pre_create_child_publisher( self, request: child_publisher_service.CreateChildPublisherRequest, @@ -581,12 +823,503 @@ def __init__( self._interceptor = interceptor or ChildPublisherServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _BatchCreateChildPublishers( - _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers, + class _BatchCreateChildPublishers( + _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers, + ChildPublisherServiceRestStub, + ): + def __hash__(self): + return hash("ChildPublisherServiceRestTransport.BatchCreateChildPublishers") + + @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: child_publisher_service.BatchCreateChildPublishersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchCreateChildPublishersResponse: + r"""Call the batch create child + publishers method over HTTP. + + Args: + request (~.child_publisher_service.BatchCreateChildPublishersRequest): + The request object. Request object for [BatchCreateChildPublishers][] + 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: + ~.child_publisher_service.BatchCreateChildPublishersResponse: + Response object for [BatchCreateChildPublishers][] + method. + + """ + + http_options = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_child_publishers( + request, metadata + ) + transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_transcoded_request( + http_options, request + ) + + body = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._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.ads.admanager_v1.ChildPublisherServiceClient.BatchCreateChildPublishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchCreateChildPublishers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChildPublisherServiceRestTransport._BatchCreateChildPublishers._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 = child_publisher_service.BatchCreateChildPublishersResponse() + pb_resp = child_publisher_service.BatchCreateChildPublishersResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_child_publishers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_create_child_publishers_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = child_publisher_service.BatchCreateChildPublishersResponse.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.ads.admanager_v1.ChildPublisherServiceClient.batch_create_child_publishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchCreateChildPublishers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchRejectChildPublishers( + _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers, + ChildPublisherServiceRestStub, + ): + def __hash__(self): + return hash("ChildPublisherServiceRestTransport.BatchRejectChildPublishers") + + @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: child_publisher_service.BatchRejectChildPublishersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchRejectChildPublishersResponse: + r"""Call the batch reject child + publishers method over HTTP. + + Args: + request (~.child_publisher_service.BatchRejectChildPublishersRequest): + The request object. Request message for [BatchRejectChildPublishers][] + 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: + ~.child_publisher_service.BatchRejectChildPublishersResponse: + Response message for [BatchRejectChildPublishers][] + method. + + """ + + http_options = _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers._get_http_options() + + request, metadata = self._interceptor.pre_batch_reject_child_publishers( + request, metadata + ) + transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers._get_transcoded_request( + http_options, request + ) + + body = _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers._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.ads.admanager_v1.ChildPublisherServiceClient.BatchRejectChildPublishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchRejectChildPublishers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChildPublisherServiceRestTransport._BatchRejectChildPublishers._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 = child_publisher_service.BatchRejectChildPublishersResponse() + pb_resp = child_publisher_service.BatchRejectChildPublishersResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_reject_child_publishers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_reject_child_publishers_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = child_publisher_service.BatchRejectChildPublishersResponse.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.ads.admanager_v1.ChildPublisherServiceClient.batch_reject_child_publishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchRejectChildPublishers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchRenegotiateChildPublisherAgreements( + _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements, + ChildPublisherServiceRestStub, + ): + def __hash__(self): + return hash( + "ChildPublisherServiceRestTransport.BatchRenegotiateChildPublisherAgreements" + ) + + @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: child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse: + r"""Call the batch renegotiate child + publisher agreements method over HTTP. + + Args: + request (~.child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest): + The request object. Request message for + [BatchRenegotiateChildPublisherAgreements][] 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: + ~.child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse: + Response message for + [BatchRenegotiateChildPublisherAgreements][] method. + + """ + + http_options = _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements._get_http_options() + + request, metadata = ( + self._interceptor.pre_batch_renegotiate_child_publisher_agreements( + request, metadata + ) + ) + transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements._get_transcoded_request( + http_options, request + ) + + body = _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements._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.ads.admanager_v1.ChildPublisherServiceClient.BatchRenegotiateChildPublisherAgreements", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchRenegotiateChildPublisherAgreements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChildPublisherServiceRestTransport._BatchRenegotiateChildPublisherAgreements._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 = child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + pb_resp = child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_renegotiate_child_publisher_agreements( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_renegotiate_child_publisher_agreements_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.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.ads.admanager_v1.ChildPublisherServiceClient.batch_renegotiate_child_publisher_agreements", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchRenegotiateChildPublisherAgreements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchResendChildPublisherInvitationEmails( + _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails, ChildPublisherServiceRestStub, ): def __hash__(self): - return hash("ChildPublisherServiceRestTransport.BatchCreateChildPublishers") + return hash( + "ChildPublisherServiceRestTransport.BatchResendChildPublisherInvitationEmails" + ) @staticmethod def _get_response( @@ -613,19 +1346,19 @@ def _get_response( def __call__( self, - request: child_publisher_service.BatchCreateChildPublishersRequest, + request: child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> child_publisher_service.BatchCreateChildPublishersResponse: - r"""Call the batch create child - publishers method over HTTP. + ) -> child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse: + r"""Call the batch resend child + publisher invitation emails method over HTTP. Args: - request (~.child_publisher_service.BatchCreateChildPublishersRequest): - The request object. Request object for [BatchCreateChildPublishers][] - method. + request (~.child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest): + The request object. Request message for + [BatchResendChildPublisherInvitationEmails][] method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -635,27 +1368,29 @@ def __call__( be of type `bytes`. Returns: - ~.child_publisher_service.BatchCreateChildPublishersResponse: - Response object for [BatchCreateChildPublishers][] - method. + ~.child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse: + Response message for + [BatchResendChildPublisherInvitationEmails][] method. """ - http_options = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_http_options() + http_options = _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails._get_http_options() - request, metadata = self._interceptor.pre_batch_create_child_publishers( - request, metadata + request, metadata = ( + self._interceptor.pre_batch_resend_child_publisher_invitation_emails( + request, metadata + ) ) - transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_transcoded_request( + transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails._get_transcoded_request( http_options, request ) - body = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_request_body_json( + body = _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseChildPublisherServiceRestTransport._BaseBatchCreateChildPublishers._get_query_params_json( + query_params = _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails._get_query_params_json( transcoded_request ) @@ -677,17 +1412,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.ads.admanager_v1.ChildPublisherServiceClient.BatchCreateChildPublishers", + f"Sending request for google.ads.admanager_v1.ChildPublisherServiceClient.BatchResendChildPublisherInvitationEmails", extra={ "serviceName": "google.ads.admanager.v1.ChildPublisherService", - "rpcName": "BatchCreateChildPublishers", + "rpcName": "BatchResendChildPublisherInvitationEmails", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ChildPublisherServiceRestTransport._BatchCreateChildPublishers._get_response( + response = ChildPublisherServiceRestTransport._BatchResendChildPublisherInvitationEmails._get_response( self._host, metadata, query_params, @@ -703,17 +1438,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = child_publisher_service.BatchCreateChildPublishersResponse() - pb_resp = child_publisher_service.BatchCreateChildPublishersResponse.pb( + resp = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() + pb_resp = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.pb( resp ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_child_publishers(resp) + resp = ( + self._interceptor.post_batch_resend_child_publisher_invitation_emails( + resp + ) + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_batch_create_child_publishers_with_metadata( + self._interceptor.post_batch_resend_child_publisher_invitation_emails_with_metadata( resp, response_metadata ) ) @@ -721,7 +1460,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = child_publisher_service.BatchCreateChildPublishersResponse.to_json( + response_payload = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.to_json( response ) except: @@ -732,10 +1471,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.ads.admanager_v1.ChildPublisherServiceClient.batch_create_child_publishers", + "Received response for google.ads.admanager_v1.ChildPublisherServiceClient.batch_resend_child_publisher_invitation_emails", extra={ "serviceName": "google.ads.admanager.v1.ChildPublisherService", - "rpcName": "BatchCreateChildPublishers", + "rpcName": "BatchResendChildPublisherInvitationEmails", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -903,6 +1642,169 @@ def __call__( ) return resp + class _BatchWithdrawChildPublishers( + _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers, + ChildPublisherServiceRestStub, + ): + def __hash__(self): + return hash( + "ChildPublisherServiceRestTransport.BatchWithdrawChildPublishers" + ) + + @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: child_publisher_service.BatchWithdrawChildPublishersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> child_publisher_service.BatchWithdrawChildPublishersResponse: + r"""Call the batch withdraw child + publishers method over HTTP. + + Args: + request (~.child_publisher_service.BatchWithdrawChildPublishersRequest): + The request object. Request message for [BatchWithdrawChildPublishers][] + 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: + ~.child_publisher_service.BatchWithdrawChildPublishersResponse: + Response message for [BatchWithdrawChildPublishers][] + method. + + """ + + http_options = _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers._get_http_options() + + request, metadata = self._interceptor.pre_batch_withdraw_child_publishers( + request, metadata + ) + transcoded_request = _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers._get_transcoded_request( + http_options, request + ) + + body = _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers._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.ads.admanager_v1.ChildPublisherServiceClient.BatchWithdrawChildPublishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchWithdrawChildPublishers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ChildPublisherServiceRestTransport._BatchWithdrawChildPublishers._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 = child_publisher_service.BatchWithdrawChildPublishersResponse() + pb_resp = child_publisher_service.BatchWithdrawChildPublishersResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_withdraw_child_publishers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_withdraw_child_publishers_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = child_publisher_service.BatchWithdrawChildPublishersResponse.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.ads.admanager_v1.ChildPublisherServiceClient.batch_withdraw_child_publishers", + extra={ + "serviceName": "google.ads.admanager.v1.ChildPublisherService", + "rpcName": "BatchWithdrawChildPublishers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateChildPublisher( _BaseChildPublisherServiceRestTransport._BaseCreateChildPublisher, ChildPublisherServiceRestStub, @@ -1539,6 +2441,45 @@ def batch_create_child_publishers( self._session, self._host, self._interceptor ) # type: ignore + @property + def batch_reject_child_publishers( + self, + ) -> Callable[ + [child_publisher_service.BatchRejectChildPublishersRequest], + child_publisher_service.BatchRejectChildPublishersResponse, + ]: + # 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._BatchRejectChildPublishers( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_renegotiate_child_publisher_agreements( + self, + ) -> Callable[ + [child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest], + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + ]: + # 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._BatchRenegotiateChildPublisherAgreements( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_resend_child_publisher_invitation_emails( + self, + ) -> Callable[ + [child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest], + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, + ]: + # 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._BatchResendChildPublisherInvitationEmails( + self._session, self._host, self._interceptor + ) # type: ignore + @property def batch_update_child_publishers( self, @@ -1552,6 +2493,19 @@ def batch_update_child_publishers( self._session, self._host, self._interceptor ) # type: ignore + @property + def batch_withdraw_child_publishers( + self, + ) -> Callable[ + [child_publisher_service.BatchWithdrawChildPublishersRequest], + child_publisher_service.BatchWithdrawChildPublishersResponse, + ]: + # 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._BatchWithdrawChildPublishers( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_child_publisher( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest_base.py index 0243e9333e26..89099d600754 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest_base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/child_publisher_service/transports/rest_base.py @@ -150,6 +150,183 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseBatchRejectChildPublishers: + 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=networks/*}/childPublishers:batchReject", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = child_publisher_service.BatchRejectChildPublishersRequest.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( + _BaseChildPublisherServiceRestTransport._BaseBatchRejectChildPublishers._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchRenegotiateChildPublisherAgreements: + 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=networks/*}/childPublishers:batchRenegotiateAgreements", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest.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( + _BaseChildPublisherServiceRestTransport._BaseBatchRenegotiateChildPublisherAgreements._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchResendChildPublisherInvitationEmails: + 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=networks/*}/childPublishers:batchResendInvitationEmails", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest.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( + _BaseChildPublisherServiceRestTransport._BaseBatchResendChildPublisherInvitationEmails._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseBatchUpdateChildPublishers: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -209,6 +386,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseBatchWithdrawChildPublishers: + 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=networks/*}/childPublishers:batchWithdraw", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = child_publisher_service.BatchWithdrawChildPublishersRequest.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( + _BaseChildPublisherServiceRestTransport._BaseBatchWithdrawChildPublishers._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateChildPublisher: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/__init__.py new file mode 100644 index 000000000000..71fadb7fad42 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/__init__.py @@ -0,0 +1,18 @@ +# -*- 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 .client import NativeStyleServiceClient + +__all__ = ("NativeStyleServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/client.py new file mode 100644 index 000000000000..1630456ca1ab --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/client.py @@ -0,0 +1,2186 @@ +# -*- 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.ads.admanager_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__) + +from google.longrunning import operations_pb2 # type: ignore + +from google.ads.admanager_v1.services.native_style_service import pagers +from google.ads.admanager_v1.types import ( + native_style_enums, + native_style_messages, + native_style_service, + size, + targeting, +) + +from .transports.base import DEFAULT_CLIENT_INFO, NativeStyleServiceTransport +from .transports.rest import NativeStyleServiceRestTransport + + +class NativeStyleServiceClientMeta(type): + """Metaclass for the NativeStyleService 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[NativeStyleServiceTransport]] + _transport_registry["rest"] = NativeStyleServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[NativeStyleServiceTransport]: + """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 NativeStyleServiceClient(metaclass=NativeStyleServiceClientMeta): + """Provides methods for handling ``NativeStyle`` objects.""" + + @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 = "admanager.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "admanager.{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: + NativeStyleServiceClient: 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: + NativeStyleServiceClient: 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) -> NativeStyleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + NativeStyleServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ad_unit_path( + network_code: str, + ad_unit: str, + ) -> str: + """Returns a fully-qualified ad_unit string.""" + return "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + + @staticmethod + def parse_ad_unit_path(path: str) -> Dict[str, str]: + """Parses a ad_unit path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/adUnits/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def application_path( + network_code: str, + application: str, + ) -> str: + """Returns a fully-qualified application string.""" + return "networks/{network_code}/applications/{application}".format( + network_code=network_code, + application=application, + ) + + @staticmethod + def parse_application_path(path: str) -> Dict[str, str]: + """Parses a application path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/applications/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def audience_segment_path( + network_code: str, + audience_segment: str, + ) -> str: + """Returns a fully-qualified audience_segment string.""" + return "networks/{network_code}/audienceSegments/{audience_segment}".format( + network_code=network_code, + audience_segment=audience_segment, + ) + + @staticmethod + def parse_audience_segment_path(path: str) -> Dict[str, str]: + """Parses a audience_segment path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/audienceSegments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def bandwidth_group_path( + network_code: str, + bandwidth_group: str, + ) -> str: + """Returns a fully-qualified bandwidth_group string.""" + return "networks/{network_code}/bandwidthGroups/{bandwidth_group}".format( + network_code=network_code, + bandwidth_group=bandwidth_group, + ) + + @staticmethod + def parse_bandwidth_group_path(path: str) -> Dict[str, str]: + """Parses a bandwidth_group path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/bandwidthGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_path( + network_code: str, + browser: str, + ) -> str: + """Returns a fully-qualified browser string.""" + return "networks/{network_code}/browsers/{browser}".format( + network_code=network_code, + browser=browser, + ) + + @staticmethod + def parse_browser_path(path: str) -> Dict[str, str]: + """Parses a browser path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browsers/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def browser_language_path( + network_code: str, + browser_language: str, + ) -> str: + """Returns a fully-qualified browser_language string.""" + return "networks/{network_code}/browserLanguages/{browser_language}".format( + network_code=network_code, + browser_language=browser_language, + ) + + @staticmethod + def parse_browser_language_path(path: str) -> Dict[str, str]: + """Parses a browser_language path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/browserLanguages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def cms_metadata_value_path( + network_code: str, + cms_metadata_value: str, + ) -> str: + """Returns a fully-qualified cms_metadata_value string.""" + return "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + + @staticmethod + def parse_cms_metadata_value_path(path: str) -> Dict[str, str]: + """Parses a cms_metadata_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/cmsMetadataValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def content_path( + network_code: str, + content: str, + ) -> str: + """Returns a fully-qualified content string.""" + return "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + + @staticmethod + def parse_content_path(path: str) -> Dict[str, str]: + """Parses a content path into its component segments.""" + m = re.match(r"^networks/(?P.+?)/content/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def content_bundle_path( + network_code: str, + content_bundle: str, + ) -> str: + """Returns a fully-qualified content_bundle string.""" + return "networks/{network_code}/contentBundles/{content_bundle}".format( + network_code=network_code, + content_bundle=content_bundle, + ) + + @staticmethod + def parse_content_bundle_path(path: str) -> Dict[str, str]: + """Parses a content_bundle path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/contentBundles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def creative_template_path( + network_code: str, + creative_template: str, + ) -> str: + """Returns a fully-qualified creative_template string.""" + return "networks/{network_code}/creativeTemplates/{creative_template}".format( + network_code=network_code, + creative_template=creative_template, + ) + + @staticmethod + def parse_creative_template_path(path: str) -> Dict[str, str]: + """Parses a creative_template path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/creativeTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_key_path( + network_code: str, + custom_targeting_key: str, + ) -> str: + """Returns a fully-qualified custom_targeting_key string.""" + return ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + + @staticmethod + def parse_custom_targeting_key_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_key path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def custom_targeting_value_path( + network_code: str, + custom_targeting_value: str, + ) -> str: + """Returns a fully-qualified custom_targeting_value string.""" + return "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + + @staticmethod + def parse_custom_targeting_value_path(path: str) -> Dict[str, str]: + """Parses a custom_targeting_value path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/customTargetingValues/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_capability_path( + network_code: str, + device_capability: str, + ) -> str: + """Returns a fully-qualified device_capability string.""" + return "networks/{network_code}/deviceCapabilities/{device_capability}".format( + network_code=network_code, + device_capability=device_capability, + ) + + @staticmethod + def parse_device_capability_path(path: str) -> Dict[str, str]: + """Parses a device_capability path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCapabilities/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_category_path( + network_code: str, + device_category: str, + ) -> str: + """Returns a fully-qualified device_category string.""" + return "networks/{network_code}/deviceCategories/{device_category}".format( + network_code=network_code, + device_category=device_category, + ) + + @staticmethod + def parse_device_category_path(path: str) -> Dict[str, str]: + """Parses a device_category path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceCategories/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def device_manufacturer_path( + network_code: str, + device_manufacturer: str, + ) -> str: + """Returns a fully-qualified device_manufacturer string.""" + return ( + "networks/{network_code}/deviceManufacturers/{device_manufacturer}".format( + network_code=network_code, + device_manufacturer=device_manufacturer, + ) + ) + + @staticmethod + def parse_device_manufacturer_path(path: str) -> Dict[str, str]: + """Parses a device_manufacturer path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/deviceManufacturers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def geo_target_path( + network_code: str, + geo_target: str, + ) -> str: + """Returns a fully-qualified geo_target string.""" + return "networks/{network_code}/geoTargets/{geo_target}".format( + network_code=network_code, + geo_target=geo_target, + ) + + @staticmethod + def parse_geo_target_path(path: str) -> Dict[str, str]: + """Parses a geo_target path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/geoTargets/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_carrier_path( + network_code: str, + mobile_carrier: str, + ) -> str: + """Returns a fully-qualified mobile_carrier string.""" + return "networks/{network_code}/mobileCarriers/{mobile_carrier}".format( + network_code=network_code, + mobile_carrier=mobile_carrier, + ) + + @staticmethod + def parse_mobile_carrier_path(path: str) -> Dict[str, str]: + """Parses a mobile_carrier path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileCarriers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_device_path( + network_code: str, + mobile_device: str, + ) -> str: + """Returns a fully-qualified mobile_device string.""" + return "networks/{network_code}/mobileDevices/{mobile_device}".format( + network_code=network_code, + mobile_device=mobile_device, + ) + + @staticmethod + def parse_mobile_device_path(path: str) -> Dict[str, str]: + """Parses a mobile_device path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileDevices/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mobile_device_submodel_path( + network_code: str, + mobile_device_submodel: str, + ) -> str: + """Returns a fully-qualified mobile_device_submodel string.""" + return "networks/{network_code}/mobileDeviceSubmodels/{mobile_device_submodel}".format( + network_code=network_code, + mobile_device_submodel=mobile_device_submodel, + ) + + @staticmethod + def parse_mobile_device_submodel_path(path: str) -> Dict[str, str]: + """Parses a mobile_device_submodel path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/mobileDeviceSubmodels/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def native_style_path( + network_code: str, + native_style: str, + ) -> str: + """Returns a fully-qualified native_style string.""" + return "networks/{network_code}/nativeStyles/{native_style}".format( + network_code=network_code, + native_style=native_style, + ) + + @staticmethod + def parse_native_style_path(path: str) -> Dict[str, str]: + """Parses a native_style path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/nativeStyles/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + network_code: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "networks/{network_code}".format( + network_code=network_code, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match(r"^networks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def operating_system_path( + network_code: str, + operating_system: str, + ) -> str: + """Returns a fully-qualified operating_system string.""" + return "networks/{network_code}/operatingSystems/{operating_system}".format( + network_code=network_code, + operating_system=operating_system, + ) + + @staticmethod + def parse_operating_system_path(path: str) -> Dict[str, str]: + """Parses a operating_system path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/operatingSystems/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def operating_system_version_path( + network_code: str, + operating_system_version: str, + ) -> str: + """Returns a fully-qualified operating_system_version string.""" + return "networks/{network_code}/operatingSystemVersions/{operating_system_version}".format( + network_code=network_code, + operating_system_version=operating_system_version, + ) + + @staticmethod + def parse_operating_system_version_path(path: str) -> Dict[str, str]: + """Parses a operating_system_version path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/operatingSystemVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def placement_path( + network_code: str, + placement: str, + ) -> str: + """Returns a fully-qualified placement string.""" + return "networks/{network_code}/placements/{placement}".format( + network_code=network_code, + placement=placement, + ) + + @staticmethod + def parse_placement_path(path: str) -> Dict[str, str]: + """Parses a placement path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/placements/(?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 = NativeStyleServiceClient._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 = NativeStyleServiceClient._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 = NativeStyleServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = NativeStyleServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NativeStyleServiceClient._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 = NativeStyleServiceClient._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, + NativeStyleServiceTransport, + Callable[..., NativeStyleServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the native style 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,NativeStyleServiceTransport,Callable[..., NativeStyleServiceTransport]]]): + 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 NativeStyleServiceTransport 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 = ( + NativeStyleServiceClient._read_environment_variables() + ) + self._client_cert_source = NativeStyleServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = NativeStyleServiceClient._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, NativeStyleServiceTransport) + if transport_provided: + # transport is a NativeStyleServiceTransport 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(NativeStyleServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or NativeStyleServiceClient._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[NativeStyleServiceTransport], + Callable[..., NativeStyleServiceTransport], + ] = ( + NativeStyleServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NativeStyleServiceTransport], 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.ads.admanager_v1.NativeStyleServiceClient`.", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "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.ads.admanager.v1.NativeStyleService", + "credentialsType": None, + }, + ) + + def get_native_style( + self, + request: Optional[ + Union[native_style_service.GetNativeStyleRequest, 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]]] = (), + ) -> native_style_messages.NativeStyle: + r"""Retrieves a ``NativeStyle`` object. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_native_style(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetNativeStyleRequest( + name="name_value", + ) + + # Make the request + response = client.get_native_style(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetNativeStyleRequest, dict]): + The request object. Request object for ``GetNativeStyle`` method. + name (str): + Required. The resource name of the NativeStyle. Format: + ``networks/{network_code}/nativeStyles/{native_style_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.ads.admanager_v1.types.NativeStyle: + Used to define the look and feel of + native ads, for both web and apps. + Native styles determine how native + creatives look for a segment of + inventory. + + """ + # 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, native_style_service.GetNativeStyleRequest): + request = native_style_service.GetNativeStyleRequest(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_native_style] + + # 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_native_styles( + self, + request: Optional[ + Union[native_style_service.ListNativeStylesRequest, 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.ListNativeStylesPager: + r"""Lists ``NativeStyle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_list_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListNativeStylesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_native_styles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ListNativeStylesRequest, dict]): + The request object. Request object for ``ListNativeStyles`` method. + parent (str): + Required. The parent, which owns this collection of + NativeStyles. Format: ``networks/{network_code}`` + + 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.ads.admanager_v1.services.native_style_service.pagers.ListNativeStylesPager: + Response object for ListNativeStylesRequest containing matching + NativeStyle objects. + + 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, native_style_service.ListNativeStylesRequest): + request = native_style_service.ListNativeStylesRequest(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_native_styles] + + # 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.ListNativeStylesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_native_styles( + self, + request: Optional[ + Union[native_style_service.BatchCreateNativeStylesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[native_style_service.CreateNativeStyleRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchCreateNativeStylesResponse: + r"""Creates ``NativeStyle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_create_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateNativeStyleRequest() + requests.parent = "parent_value" + requests.native_style.size.width = 544 + requests.native_style.size.height = 633 + requests.native_style.size.size_type = "AUDIO" + + request = admanager_v1.BatchCreateNativeStylesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_native_styles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchCreateNativeStylesRequest, dict]): + The request object. Request object for ``BatchCreateNativeStyles`` method. + parent (str): + Required. The parent resource where ``NativeStyles`` + will be created. Format: ``networks/{network_code}`` The + parent field in the CreateNativeStyleRequest must match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.CreateNativeStyleRequest]): + Required. The ``NativeStyle`` objects to create. A + maximum of 100 objects can be created in a batch. + + This corresponds to the ``requests`` 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.ads.admanager_v1.types.BatchCreateNativeStylesResponse: + Response object for BatchCreateNativeStyles 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 = [parent, requests] + 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, native_style_service.BatchCreateNativeStylesRequest): + request = native_style_service.BatchCreateNativeStylesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_create_native_styles + ] + + # 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 batch_update_native_styles( + self, + request: Optional[ + Union[native_style_service.BatchUpdateNativeStylesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[native_style_service.UpdateNativeStyleRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchUpdateNativeStylesResponse: + r"""Batch updates ``NativeStyle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_update_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.UpdateNativeStyleRequest() + requests.native_style.size.width = 544 + requests.native_style.size.height = 633 + requests.native_style.size.size_type = "AUDIO" + + request = admanager_v1.BatchUpdateNativeStylesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_update_native_styles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchUpdateNativeStylesRequest, dict]): + The request object. Request object for ``BatchUpdateNativeStyles`` method. + parent (str): + Required. The parent resource where ``NativeStyles`` + will be updated. Format: ``networks/{network_code}`` The + parent field in the UpdateNativeStyleRequest must match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateNativeStyleRequest]): + Required. The ``NativeStyle`` objects to update. A + maximum of 100 objects can be updated in a batch. + + This corresponds to the ``requests`` 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.ads.admanager_v1.types.BatchUpdateNativeStylesResponse: + Response object for BatchUpdateNativeStyles 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 = [parent, requests] + 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, native_style_service.BatchUpdateNativeStylesRequest): + request = native_style_service.BatchUpdateNativeStylesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_update_native_styles + ] + + # 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 batch_activate_native_styles( + self, + request: Optional[ + Union[native_style_service.BatchActivateNativeStylesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchActivateNativeStylesResponse: + r"""Beginning of non-CRUD Activates a list of ``NativeStyle`` + objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_activate_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateNativeStylesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_activate_native_styles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchActivateNativeStylesRequest, dict]): + The request object. Request object for ``BatchActivateNativeStyles`` method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. + Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchActivateNativeStylesResponse: + Response object for BatchActivateNativeStyles 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 = [parent, names] + 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, native_style_service.BatchActivateNativeStylesRequest + ): + request = native_style_service.BatchActivateNativeStylesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_activate_native_styles + ] + + # 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 batch_deactivate_native_styles( + self, + request: Optional[ + Union[native_style_service.BatchDeactivateNativeStylesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchDeactivateNativeStylesResponse: + r"""Deactivates a list of ``NativeStyle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_deactivate_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateNativeStylesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_deactivate_native_styles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchDeactivateNativeStylesRequest, dict]): + The request object. Request object for ``BatchDeactivateNativeStyles`` + method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. + Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchDeactivateNativeStylesResponse: + Response object for BatchDeactivateNativeStyles 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 = [parent, names] + 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, native_style_service.BatchDeactivateNativeStylesRequest + ): + request = native_style_service.BatchDeactivateNativeStylesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_deactivate_native_styles + ] + + # 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 batch_archive_native_styles( + self, + request: Optional[ + Union[native_style_service.BatchArchiveNativeStylesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + names: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchArchiveNativeStylesResponse: + r"""Archives a list of ``NativeStyle`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_batch_archive_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchArchiveNativeStylesRequest( + parent="parent_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_archive_native_styles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.BatchArchiveNativeStylesRequest, dict]): + The request object. Request object for ``BatchArchiveNativeStyles`` method. + parent (str): + Required. Format: ``networks/{network_code}`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. + Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + + This corresponds to the ``names`` 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.ads.admanager_v1.types.BatchArchiveNativeStylesResponse: + Response object for BatchArchiveNativeStyles 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 = [parent, names] + 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, native_style_service.BatchArchiveNativeStylesRequest + ): + request = native_style_service.BatchArchiveNativeStylesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if names is not None: + request.names = names + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_archive_native_styles + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NativeStyleServiceClient": + 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 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 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, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("NativeStyleServiceClient",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/pagers.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/pagers.py new file mode 100644 index 000000000000..7735cb91122a --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/pagers.py @@ -0,0 +1,117 @@ +# -*- 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.ads.admanager_v1.types import native_style_messages, native_style_service + + +class ListNativeStylesPager: + """A pager for iterating through ``list_native_styles`` requests. + + This class thinly wraps an initial + :class:`google.ads.admanager_v1.types.ListNativeStylesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``native_styles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNativeStyles`` requests and continue to iterate + through the ``native_styles`` field on the + corresponding responses. + + All the usual :class:`google.ads.admanager_v1.types.ListNativeStylesResponse` + 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[..., native_style_service.ListNativeStylesResponse], + request: native_style_service.ListNativeStylesRequest, + response: native_style_service.ListNativeStylesResponse, + *, + 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.ads.admanager_v1.types.ListNativeStylesRequest): + The initial request object. + response (google.ads.admanager_v1.types.ListNativeStylesResponse): + 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 = native_style_service.ListNativeStylesRequest(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[native_style_service.ListNativeStylesResponse]: + 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[native_style_messages.NativeStyle]: + for page in self.pages: + yield from page.native_styles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/README.rst b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/README.rst new file mode 100644 index 000000000000..92db72e6d439 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``NativeStyleServiceTransport`` is the ABC for all transports. + +- public child ``NativeStyleServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``NativeStyleServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseNativeStyleServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``NativeStyleServiceRestTransport`` 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-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/__init__.py new file mode 100644 index 000000000000..7d856d3c0e37 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- 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 NativeStyleServiceTransport +from .rest import NativeStyleServiceRestInterceptor, NativeStyleServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NativeStyleServiceTransport]] +_transport_registry["rest"] = NativeStyleServiceRestTransport + +__all__ = ( + "NativeStyleServiceTransport", + "NativeStyleServiceRestTransport", + "NativeStyleServiceRestInterceptor", +) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/base.py new file mode 100644 index 000000000000..93b8fef303ec --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/base.py @@ -0,0 +1,310 @@ +# -*- 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 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ads.admanager_v1 import gapic_version as package_version +from google.ads.admanager_v1.types import native_style_messages, native_style_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NativeStyleServiceTransport(abc.ABC): + """Abstract transport class for NativeStyleService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ) + + DEFAULT_HOST: str = "admanager.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: 'admanager.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.get_native_style: gapic_v1.method.wrap_method( + self.get_native_style, + default_timeout=None, + client_info=client_info, + ), + self.list_native_styles: gapic_v1.method.wrap_method( + self.list_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_native_styles: gapic_v1.method.wrap_method( + self.batch_create_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_native_styles: gapic_v1.method.wrap_method( + self.batch_update_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.batch_activate_native_styles: gapic_v1.method.wrap_method( + self.batch_activate_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.batch_deactivate_native_styles: gapic_v1.method.wrap_method( + self.batch_deactivate_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.batch_archive_native_styles: gapic_v1.method.wrap_method( + self.batch_archive_native_styles, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + 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 get_native_style( + self, + ) -> Callable[ + [native_style_service.GetNativeStyleRequest], + Union[ + native_style_messages.NativeStyle, + Awaitable[native_style_messages.NativeStyle], + ], + ]: + raise NotImplementedError() + + @property + def list_native_styles( + self, + ) -> Callable[ + [native_style_service.ListNativeStylesRequest], + Union[ + native_style_service.ListNativeStylesResponse, + Awaitable[native_style_service.ListNativeStylesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_create_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchCreateNativeStylesRequest], + Union[ + native_style_service.BatchCreateNativeStylesResponse, + Awaitable[native_style_service.BatchCreateNativeStylesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_update_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchUpdateNativeStylesRequest], + Union[ + native_style_service.BatchUpdateNativeStylesResponse, + Awaitable[native_style_service.BatchUpdateNativeStylesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_activate_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchActivateNativeStylesRequest], + Union[ + native_style_service.BatchActivateNativeStylesResponse, + Awaitable[native_style_service.BatchActivateNativeStylesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_deactivate_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchDeactivateNativeStylesRequest], + Union[ + native_style_service.BatchDeactivateNativeStylesResponse, + Awaitable[native_style_service.BatchDeactivateNativeStylesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_archive_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchArchiveNativeStylesRequest], + Union[ + native_style_service.BatchArchiveNativeStylesResponse, + Awaitable[native_style_service.BatchArchiveNativeStylesResponse], + ], + ]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("NativeStyleServiceTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest.py new file mode 100644 index 000000000000..b234ce840c1a --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest.py @@ -0,0 +1,2080 @@ +# -*- 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, 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.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ads.admanager_v1.types import native_style_messages, native_style_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseNativeStyleServiceRestTransport + +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}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NativeStyleServiceRestInterceptor: + """Interceptor for NativeStyleService. + + 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 NativeStyleServiceRestTransport. + + .. code-block:: python + class MyCustomNativeStyleServiceInterceptor(NativeStyleServiceRestInterceptor): + def pre_batch_activate_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_activate_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_archive_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_archive_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_create_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_deactivate_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_deactivate_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_update_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_native_style(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_native_style(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_native_styles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_native_styles(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NativeStyleServiceRestTransport(interceptor=MyCustomNativeStyleServiceInterceptor()) + client = NativeStyleServiceClient(transport=transport) + + + """ + + def pre_batch_activate_native_styles( + self, + request: native_style_service.BatchActivateNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchActivateNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_activate_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_batch_activate_native_styles( + self, response: native_style_service.BatchActivateNativeStylesResponse + ) -> native_style_service.BatchActivateNativeStylesResponse: + """Post-rpc interceptor for batch_activate_native_styles + + DEPRECATED. Please use the `post_batch_activate_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_batch_activate_native_styles` interceptor runs + before the `post_batch_activate_native_styles_with_metadata` interceptor. + """ + return response + + def post_batch_activate_native_styles_with_metadata( + self, + response: native_style_service.BatchActivateNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchActivateNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_activate_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_batch_activate_native_styles_with_metadata` + interceptor in new development instead of the `post_batch_activate_native_styles` interceptor. + When both interceptors are used, this `post_batch_activate_native_styles_with_metadata` interceptor runs after the + `post_batch_activate_native_styles` interceptor. The (possibly modified) response returned by + `post_batch_activate_native_styles` will be passed to + `post_batch_activate_native_styles_with_metadata`. + """ + return response, metadata + + def pre_batch_archive_native_styles( + self, + request: native_style_service.BatchArchiveNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchArchiveNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_archive_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_batch_archive_native_styles( + self, response: native_style_service.BatchArchiveNativeStylesResponse + ) -> native_style_service.BatchArchiveNativeStylesResponse: + """Post-rpc interceptor for batch_archive_native_styles + + DEPRECATED. Please use the `post_batch_archive_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_batch_archive_native_styles` interceptor runs + before the `post_batch_archive_native_styles_with_metadata` interceptor. + """ + return response + + def post_batch_archive_native_styles_with_metadata( + self, + response: native_style_service.BatchArchiveNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchArchiveNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_archive_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_batch_archive_native_styles_with_metadata` + interceptor in new development instead of the `post_batch_archive_native_styles` interceptor. + When both interceptors are used, this `post_batch_archive_native_styles_with_metadata` interceptor runs after the + `post_batch_archive_native_styles` interceptor. The (possibly modified) response returned by + `post_batch_archive_native_styles` will be passed to + `post_batch_archive_native_styles_with_metadata`. + """ + return response, metadata + + def pre_batch_create_native_styles( + self, + request: native_style_service.BatchCreateNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchCreateNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_batch_create_native_styles( + self, response: native_style_service.BatchCreateNativeStylesResponse + ) -> native_style_service.BatchCreateNativeStylesResponse: + """Post-rpc interceptor for batch_create_native_styles + + DEPRECATED. Please use the `post_batch_create_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_batch_create_native_styles` interceptor runs + before the `post_batch_create_native_styles_with_metadata` interceptor. + """ + return response + + def post_batch_create_native_styles_with_metadata( + self, + response: native_style_service.BatchCreateNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchCreateNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_batch_create_native_styles_with_metadata` + interceptor in new development instead of the `post_batch_create_native_styles` interceptor. + When both interceptors are used, this `post_batch_create_native_styles_with_metadata` interceptor runs after the + `post_batch_create_native_styles` interceptor. The (possibly modified) response returned by + `post_batch_create_native_styles` will be passed to + `post_batch_create_native_styles_with_metadata`. + """ + return response, metadata + + def pre_batch_deactivate_native_styles( + self, + request: native_style_service.BatchDeactivateNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchDeactivateNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_deactivate_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_batch_deactivate_native_styles( + self, response: native_style_service.BatchDeactivateNativeStylesResponse + ) -> native_style_service.BatchDeactivateNativeStylesResponse: + """Post-rpc interceptor for batch_deactivate_native_styles + + DEPRECATED. Please use the `post_batch_deactivate_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_batch_deactivate_native_styles` interceptor runs + before the `post_batch_deactivate_native_styles_with_metadata` interceptor. + """ + return response + + def post_batch_deactivate_native_styles_with_metadata( + self, + response: native_style_service.BatchDeactivateNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchDeactivateNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_deactivate_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_batch_deactivate_native_styles_with_metadata` + interceptor in new development instead of the `post_batch_deactivate_native_styles` interceptor. + When both interceptors are used, this `post_batch_deactivate_native_styles_with_metadata` interceptor runs after the + `post_batch_deactivate_native_styles` interceptor. The (possibly modified) response returned by + `post_batch_deactivate_native_styles` will be passed to + `post_batch_deactivate_native_styles_with_metadata`. + """ + return response, metadata + + def pre_batch_update_native_styles( + self, + request: native_style_service.BatchUpdateNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchUpdateNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_batch_update_native_styles( + self, response: native_style_service.BatchUpdateNativeStylesResponse + ) -> native_style_service.BatchUpdateNativeStylesResponse: + """Post-rpc interceptor for batch_update_native_styles + + DEPRECATED. Please use the `post_batch_update_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_batch_update_native_styles` interceptor runs + before the `post_batch_update_native_styles_with_metadata` interceptor. + """ + return response + + def post_batch_update_native_styles_with_metadata( + self, + response: native_style_service.BatchUpdateNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.BatchUpdateNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_batch_update_native_styles_with_metadata` + interceptor in new development instead of the `post_batch_update_native_styles` interceptor. + When both interceptors are used, this `post_batch_update_native_styles_with_metadata` interceptor runs after the + `post_batch_update_native_styles` interceptor. The (possibly modified) response returned by + `post_batch_update_native_styles` will be passed to + `post_batch_update_native_styles_with_metadata`. + """ + return response, metadata + + def pre_get_native_style( + self, + request: native_style_service.GetNativeStyleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.GetNativeStyleRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_native_style + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_get_native_style( + self, response: native_style_messages.NativeStyle + ) -> native_style_messages.NativeStyle: + """Post-rpc interceptor for get_native_style + + DEPRECATED. Please use the `post_get_native_style_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_get_native_style` interceptor runs + before the `post_get_native_style_with_metadata` interceptor. + """ + return response + + def post_get_native_style_with_metadata( + self, + response: native_style_messages.NativeStyle, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_messages.NativeStyle, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_native_style + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_get_native_style_with_metadata` + interceptor in new development instead of the `post_get_native_style` interceptor. + When both interceptors are used, this `post_get_native_style_with_metadata` interceptor runs after the + `post_get_native_style` interceptor. The (possibly modified) response returned by + `post_get_native_style` will be passed to + `post_get_native_style_with_metadata`. + """ + return response, metadata + + def pre_list_native_styles( + self, + request: native_style_service.ListNativeStylesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.ListNativeStylesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_native_styles + + Override in a subclass to manipulate the request or metadata + before they are sent to the NativeStyleService server. + """ + return request, metadata + + def post_list_native_styles( + self, response: native_style_service.ListNativeStylesResponse + ) -> native_style_service.ListNativeStylesResponse: + """Post-rpc interceptor for list_native_styles + + DEPRECATED. Please use the `post_list_native_styles_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NativeStyleService server but before + it is returned to user code. This `post_list_native_styles` interceptor runs + before the `post_list_native_styles_with_metadata` interceptor. + """ + return response + + def post_list_native_styles_with_metadata( + self, + response: native_style_service.ListNativeStylesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + native_style_service.ListNativeStylesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_native_styles + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NativeStyleService server but before it is returned to user code. + + We recommend only using this `post_list_native_styles_with_metadata` + interceptor in new development instead of the `post_list_native_styles` interceptor. + When both interceptors are used, this `post_list_native_styles_with_metadata` interceptor runs after the + `post_list_native_styles` interceptor. The (possibly modified) response returned by + `post_list_native_styles` will be passed to + `post_list_native_styles_with_metadata`. + """ + return response, metadata + + 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 NativeStyleService 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 NativeStyleService 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 NativeStyleService 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 NativeStyleService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NativeStyleServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NativeStyleServiceRestInterceptor + + +class NativeStyleServiceRestTransport(_BaseNativeStyleServiceRestTransport): + """REST backend synchronous transport for NativeStyleService. + + Provides methods for handling ``NativeStyle`` objects. + + 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 = "admanager.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[NativeStyleServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'admanager.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[NativeStyleServiceRestInterceptor]): 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 + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or NativeStyleServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchActivateNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.BatchActivateNativeStyles") + + @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: native_style_service.BatchActivateNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchActivateNativeStylesResponse: + r"""Call the batch activate native + styles method over HTTP. + + Args: + request (~.native_style_service.BatchActivateNativeStylesRequest): + The request object. Request object for ``BatchActivateNativeStyles`` 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: + ~.native_style_service.BatchActivateNativeStylesResponse: + Response object for ``BatchActivateNativeStyles`` + method. + + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_batch_activate_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles._get_transcoded_request( + http_options, request + ) + + body = _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.BatchActivateNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchActivateNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._BatchActivateNativeStyles._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 = native_style_service.BatchActivateNativeStylesResponse() + pb_resp = native_style_service.BatchActivateNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_activate_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_activate_native_styles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + native_style_service.BatchActivateNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.batch_activate_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchActivateNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchArchiveNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.BatchArchiveNativeStyles") + + @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: native_style_service.BatchArchiveNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchArchiveNativeStylesResponse: + r"""Call the batch archive native + styles method over HTTP. + + Args: + request (~.native_style_service.BatchArchiveNativeStylesRequest): + The request object. Request object for ``BatchArchiveNativeStyles`` 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: + ~.native_style_service.BatchArchiveNativeStylesResponse: + Response object for ``BatchArchiveNativeStyles`` method. + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_batch_archive_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles._get_transcoded_request( + http_options, request + ) + + body = _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.BatchArchiveNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchArchiveNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + NativeStyleServiceRestTransport._BatchArchiveNativeStyles._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 = native_style_service.BatchArchiveNativeStylesResponse() + pb_resp = native_style_service.BatchArchiveNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_archive_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_archive_native_styles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + native_style_service.BatchArchiveNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.batch_archive_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchArchiveNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchCreateNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.BatchCreateNativeStyles") + + @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: native_style_service.BatchCreateNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchCreateNativeStylesResponse: + r"""Call the batch create native + styles method over HTTP. + + Args: + request (~.native_style_service.BatchCreateNativeStylesRequest): + The request object. Request object for ``BatchCreateNativeStyles`` 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: + ~.native_style_service.BatchCreateNativeStylesResponse: + Response object for ``BatchCreateNativeStyles`` method. + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles._get_transcoded_request( + http_options, request + ) + + body = _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.BatchCreateNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchCreateNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + NativeStyleServiceRestTransport._BatchCreateNativeStyles._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 = native_style_service.BatchCreateNativeStylesResponse() + pb_resp = native_style_service.BatchCreateNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_native_styles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + native_style_service.BatchCreateNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.batch_create_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchCreateNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeactivateNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.BatchDeactivateNativeStyles") + + @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: native_style_service.BatchDeactivateNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchDeactivateNativeStylesResponse: + r"""Call the batch deactivate native + styles method over HTTP. + + Args: + request (~.native_style_service.BatchDeactivateNativeStylesRequest): + The request object. Request object for ``BatchDeactivateNativeStyles`` + 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: + ~.native_style_service.BatchDeactivateNativeStylesResponse: + Response object for ``BatchDeactivateNativeStyles`` + method. + + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_batch_deactivate_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles._get_transcoded_request( + http_options, request + ) + + body = _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.BatchDeactivateNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchDeactivateNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._BatchDeactivateNativeStyles._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 = native_style_service.BatchDeactivateNativeStylesResponse() + pb_resp = native_style_service.BatchDeactivateNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_deactivate_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_batch_deactivate_native_styles_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = native_style_service.BatchDeactivateNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.batch_deactivate_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchDeactivateNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchUpdateNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.BatchUpdateNativeStyles") + + @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: native_style_service.BatchUpdateNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.BatchUpdateNativeStylesResponse: + r"""Call the batch update native + styles method over HTTP. + + Args: + request (~.native_style_service.BatchUpdateNativeStylesRequest): + The request object. Request object for ``BatchUpdateNativeStyles`` 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: + ~.native_style_service.BatchUpdateNativeStylesResponse: + Response object for ``BatchUpdateNativeStyles`` method. + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_batch_update_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles._get_transcoded_request( + http_options, request + ) + + body = _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.BatchUpdateNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchUpdateNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + NativeStyleServiceRestTransport._BatchUpdateNativeStyles._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 = native_style_service.BatchUpdateNativeStylesResponse() + pb_resp = native_style_service.BatchUpdateNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_native_styles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + native_style_service.BatchUpdateNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.batch_update_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "BatchUpdateNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetNativeStyle( + _BaseNativeStyleServiceRestTransport._BaseGetNativeStyle, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.GetNativeStyle") + + @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: native_style_service.GetNativeStyleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_messages.NativeStyle: + r"""Call the get native style method over HTTP. + + Args: + request (~.native_style_service.GetNativeStyleRequest): + The request object. Request object for ``GetNativeStyle`` 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: + ~.native_style_messages.NativeStyle: + Used to define the look and feel of + native ads, for both web and apps. + Native styles determine how native + creatives look for a segment of + inventory. + + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseGetNativeStyle._get_http_options() + + request, metadata = self._interceptor.pre_get_native_style( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseGetNativeStyle._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseGetNativeStyle._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.ads.admanager_v1.NativeStyleServiceClient.GetNativeStyle", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "GetNativeStyle", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._GetNativeStyle._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 = native_style_messages.NativeStyle() + pb_resp = native_style_messages.NativeStyle.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_native_style(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_native_style_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = native_style_messages.NativeStyle.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.ads.admanager_v1.NativeStyleServiceClient.get_native_style", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "GetNativeStyle", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListNativeStyles( + _BaseNativeStyleServiceRestTransport._BaseListNativeStyles, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.ListNativeStyles") + + @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: native_style_service.ListNativeStylesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> native_style_service.ListNativeStylesResponse: + r"""Call the list native styles method over HTTP. + + Args: + request (~.native_style_service.ListNativeStylesRequest): + The request object. Request object for ``ListNativeStyles`` 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: + ~.native_style_service.ListNativeStylesResponse: + Response object for ``ListNativeStylesRequest`` + containing matching ``NativeStyle`` objects. + + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseListNativeStyles._get_http_options() + + request, metadata = self._interceptor.pre_list_native_styles( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseListNativeStyles._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._BaseListNativeStyles._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.ads.admanager_v1.NativeStyleServiceClient.ListNativeStyles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "ListNativeStyles", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._ListNativeStyles._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 = native_style_service.ListNativeStylesResponse() + pb_resp = native_style_service.ListNativeStylesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_native_styles(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_native_styles_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + native_style_service.ListNativeStylesResponse.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.ads.admanager_v1.NativeStyleServiceClient.list_native_styles", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "ListNativeStyles", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_activate_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchActivateNativeStylesRequest], + native_style_service.BatchActivateNativeStylesResponse, + ]: + # 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._BatchActivateNativeStyles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_archive_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchArchiveNativeStylesRequest], + native_style_service.BatchArchiveNativeStylesResponse, + ]: + # 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._BatchArchiveNativeStyles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_create_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchCreateNativeStylesRequest], + native_style_service.BatchCreateNativeStylesResponse, + ]: + # 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._BatchCreateNativeStyles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_deactivate_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchDeactivateNativeStylesRequest], + native_style_service.BatchDeactivateNativeStylesResponse, + ]: + # 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._BatchDeactivateNativeStyles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def batch_update_native_styles( + self, + ) -> Callable[ + [native_style_service.BatchUpdateNativeStylesRequest], + native_style_service.BatchUpdateNativeStylesResponse, + ]: + # 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._BatchUpdateNativeStyles( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_native_style( + self, + ) -> Callable[ + [native_style_service.GetNativeStyleRequest], native_style_messages.NativeStyle + ]: + # 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._GetNativeStyle(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_native_styles( + self, + ) -> Callable[ + [native_style_service.ListNativeStylesRequest], + native_style_service.ListNativeStylesResponse, + ]: + # 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._ListNativeStyles(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseNativeStyleServiceRestTransport._BaseCancelOperation, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNativeStyleServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._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.ads.admanager_v1.NativeStyleServiceClient.CancelOperation", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseNativeStyleServiceRestTransport._BaseGetOperation, + NativeStyleServiceRestStub, + ): + def __hash__(self): + return hash("NativeStyleServiceRestTransport.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 = _BaseNativeStyleServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseNativeStyleServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseNativeStyleServiceRestTransport._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.ads.admanager_v1.NativeStyleServiceClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NativeStyleServiceRestTransport._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.ads.admanager_v1.NativeStyleServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ads.admanager.v1.NativeStyleService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("NativeStyleServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest_base.py new file mode 100644 index 000000000000..05d192f4d06c --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/native_style_service/transports/rest_base.py @@ -0,0 +1,527 @@ +# -*- 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.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ads.admanager_v1.types import native_style_messages, native_style_service + +from .base import DEFAULT_CLIENT_INFO, NativeStyleServiceTransport + + +class _BaseNativeStyleServiceRestTransport(NativeStyleServiceTransport): + """Base REST backend transport for NativeStyleService. + + 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 = "admanager.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: 'admanager.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 _BaseBatchActivateNativeStyles: + 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=networks/*}/nativeStyles:batchActivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.BatchActivateNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseBatchActivateNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchArchiveNativeStyles: + 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=networks/*}/nativeStyles:batchArchive", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.BatchArchiveNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseBatchArchiveNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchCreateNativeStyles: + 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=networks/*}/nativeStyles:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.BatchCreateNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseBatchCreateNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeactivateNativeStyles: + 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=networks/*}/nativeStyles:batchDeactivate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.BatchDeactivateNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseBatchDeactivateNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateNativeStyles: + 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=networks/*}/nativeStyles:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.BatchUpdateNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseBatchUpdateNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetNativeStyle: + 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=networks/*/nativeStyles/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.GetNativeStyleRequest.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( + _BaseNativeStyleServiceRestTransport._BaseGetNativeStyle._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListNativeStyles: + 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=networks/*}/nativeStyles", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = native_style_service.ListNativeStylesRequest.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( + _BaseNativeStyleServiceRestTransport._BaseListNativeStyles._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + 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=networks/*/operations/reports/runs/*}:cancel", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=networks/*/operations/reports/runs/*}", + }, + ] + 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__ = ("_BaseNativeStyleServiceRestTransport",) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py index 694862b995a2..a24d707b4e83 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/client.py @@ -61,10 +61,15 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.ads.admanager_v1.services.network_service import pagers -from google.ads.admanager_v1.types import network_messages, network_service +from google.ads.admanager_v1.types import ( + network_messages, + network_service, + third_party_data_declaration, +) from .transports.base import DEFAULT_CLIENT_INFO, NetworkServiceTransport from .transports.rest import NetworkServiceRestTransport @@ -241,6 +246,23 @@ def parse_ad_unit_path(path: str) -> Dict[str, str]: m = re.match(r"^networks/(?P.+?)/adUnits/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def default_third_party_data_declaration_path( + network_code: str, + ) -> str: + """Returns a fully-qualified default_third_party_data_declaration string.""" + return "networks/{network_code}/defaultThirdPartyDataDeclaration".format( + network_code=network_code, + ) + + @staticmethod + def parse_default_third_party_data_declaration_path(path: str) -> Dict[str, str]: + """Parses a default_third_party_data_declaration path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/defaultThirdPartyDataDeclaration$", path + ) + return m.groupdict() if m else {} + @staticmethod def network_path( network_code: str, @@ -256,6 +278,28 @@ def parse_network_path(path: str) -> Dict[str, str]: m = re.match(r"^networks/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def third_party_company_path( + network_code: str, + third_party_company: str, + ) -> str: + """Returns a fully-qualified third_party_company string.""" + return ( + "networks/{network_code}/thirdPartyCompanies/{third_party_company}".format( + network_code=network_code, + third_party_company=third_party_company, + ) + ) + + @staticmethod + def parse_third_party_company_path(path: str) -> Dict[str, str]: + """Parses a third_party_company path into its component segments.""" + m = re.match( + r"^networks/(?P.+?)/thirdPartyCompanies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -931,6 +975,332 @@ def sample_list_networks(): # Done; return the response. return response + def update_network( + self, + request: Optional[Union[network_service.UpdateNetworkRequest, dict]] = None, + *, + network: Optional[network_messages.Network] = 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]]] = (), + ) -> network_messages.Network: + r"""Updates a ``Network`` object. Currently, only the network + display name can be updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_update_network(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateNetworkRequest( + ) + + # Make the request + response = client.update_network(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.UpdateNetworkRequest, dict]): + The request object. Request for the ``UpdateNetwork`` method. + network (google.ads.admanager_v1.types.Network): + Required. The ``Network`` to update. + + The ``Network``'s ``name`` is used to identify the + ``Network`` to update. + + This corresponds to the ``network`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ads.admanager_v1.types.Network: + The Network 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 = [network, 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, network_service.UpdateNetworkRequest): + request = network_service.UpdateNetworkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if network is not None: + request.network = network + 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_network] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("network.name", request.network.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 provision_test_network( + self, + request: Optional[ + Union[network_service.ProvisionTestNetworkRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> network_messages.Network: + r"""Provisions a test network associated with the current user. Only + one test network can be provisioned per user. + + Before the test network can be used, you must complete setup in + the Ad Manager UI. If the test network's owner is a service + account, you must add a non-service account user by calling + UserService.CreateUser. + + Test networks are limited in the following ways: + + - Test networks have a maximum of 10,000 objects per entity + type. + - Test networks cannot serve ads. + - Reports on serving data have zero rows. + - Forecast service results contain mock data. + - Test networks do not have Ad Manager 360 or premium features + enabled. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_provision_test_network(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ProvisionTestNetworkRequest( + ) + + # Make the request + response = client.provision_test_network(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.ProvisionTestNetworkRequest, dict]): + The request object. Request for the ``ProvisionTestNetwork`` 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: + google.ads.admanager_v1.types.Network: + The Network resource. + """ + # 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, network_service.ProvisionTestNetworkRequest): + request = network_service.ProvisionTestNetworkRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.provision_test_network] + + # 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_default_third_party_data_declaration( + self, + request: Optional[ + Union[network_service.GetDefaultThirdPartyDataDeclarationRequest, 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]]] = (), + ) -> network_messages.DefaultThirdPartyDataDeclaration: + r"""Returns the [DefaultThirdPartyDataDeclaration] for this network. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ads import admanager_v1 + + def sample_get_default_third_party_data_declaration(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetDefaultThirdPartyDataDeclarationRequest( + name="name_value", + ) + + # Make the request + response = client.get_default_third_party_data_declaration(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ads.admanager_v1.types.GetDefaultThirdPartyDataDeclarationRequest, dict]): + The request object. Request for the ``GetDefaultThirdPartyDataDeclaration`` + method. + name (str): + Required. Resource name of + DefaultThirdPartyDataDeclaration. Format: + networks/{network_code}/defaultThirdPartyDataDeclaration + + 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.ads.admanager_v1.types.DefaultThirdPartyDataDeclaration: + The DefaultThirdPartyDataDeclaration singleton 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, network_service.GetDefaultThirdPartyDataDeclarationRequest + ): + request = network_service.GetDefaultThirdPartyDataDeclarationRequest( + 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_default_third_party_data_declaration + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "NetworkServiceClient": return self diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/base.py index a37f1c8b7e5f..12cb38fd4490 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/base.py @@ -154,6 +154,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_network: gapic_v1.method.wrap_method( + self.update_network, + default_timeout=None, + client_info=client_info, + ), + self.provision_test_network: gapic_v1.method.wrap_method( + self.provision_test_network, + default_timeout=None, + client_info=client_info, + ), + self.get_default_third_party_data_declaration: gapic_v1.method.wrap_method( + self.get_default_third_party_data_declaration, + default_timeout=None, + client_info=client_info, + ), self.cancel_operation: gapic_v1.method.wrap_method( self.cancel_operation, default_timeout=None, @@ -196,6 +211,36 @@ def list_networks( ]: raise NotImplementedError() + @property + def update_network( + self, + ) -> Callable[ + [network_service.UpdateNetworkRequest], + Union[network_messages.Network, Awaitable[network_messages.Network]], + ]: + raise NotImplementedError() + + @property + def provision_test_network( + self, + ) -> Callable[ + [network_service.ProvisionTestNetworkRequest], + Union[network_messages.Network, Awaitable[network_messages.Network]], + ]: + raise NotImplementedError() + + @property + def get_default_third_party_data_declaration( + self, + ) -> Callable[ + [network_service.GetDefaultThirdPartyDataDeclarationRequest], + Union[ + network_messages.DefaultThirdPartyDataDeclaration, + Awaitable[network_messages.DefaultThirdPartyDataDeclaration], + ], + ]: + raise NotImplementedError() + @property def get_operation( self, diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest.py index cd6bf6404199..3654d66c9bb4 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest.py @@ -72,6 +72,14 @@ class NetworkServiceRestInterceptor: .. code-block:: python class MyCustomNetworkServiceInterceptor(NetworkServiceRestInterceptor): + def pre_get_default_third_party_data_declaration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_default_third_party_data_declaration(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_network(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -88,12 +96,80 @@ def post_list_networks(self, response): logging.log(f"Received response: {response}") return response + def pre_provision_test_network(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provision_test_network(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_network(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_network(self, response): + logging.log(f"Received response: {response}") + return response + transport = NetworkServiceRestTransport(interceptor=MyCustomNetworkServiceInterceptor()) client = NetworkServiceClient(transport=transport) """ + def pre_get_default_third_party_data_declaration( + self, + request: network_service.GetDefaultThirdPartyDataDeclarationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + network_service.GetDefaultThirdPartyDataDeclarationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_default_third_party_data_declaration + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkService server. + """ + return request, metadata + + def post_get_default_third_party_data_declaration( + self, response: network_messages.DefaultThirdPartyDataDeclaration + ) -> network_messages.DefaultThirdPartyDataDeclaration: + """Post-rpc interceptor for get_default_third_party_data_declaration + + DEPRECATED. Please use the `post_get_default_third_party_data_declaration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkService server but before + it is returned to user code. This `post_get_default_third_party_data_declaration` interceptor runs + before the `post_get_default_third_party_data_declaration_with_metadata` interceptor. + """ + return response + + def post_get_default_third_party_data_declaration_with_metadata( + self, + response: network_messages.DefaultThirdPartyDataDeclaration, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + network_messages.DefaultThirdPartyDataDeclaration, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_default_third_party_data_declaration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkService server but before it is returned to user code. + + We recommend only using this `post_get_default_third_party_data_declaration_with_metadata` + interceptor in new development instead of the `post_get_default_third_party_data_declaration` interceptor. + When both interceptors are used, this `post_get_default_third_party_data_declaration_with_metadata` interceptor runs after the + `post_get_default_third_party_data_declaration` interceptor. The (possibly modified) response returned by + `post_get_default_third_party_data_declaration` will be passed to + `post_get_default_third_party_data_declaration_with_metadata`. + """ + return response, metadata + def pre_get_network( self, request: network_service.GetNetworkRequest, @@ -192,6 +268,103 @@ def post_list_networks_with_metadata( """ return response, metadata + def pre_provision_test_network( + self, + request: network_service.ProvisionTestNetworkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + network_service.ProvisionTestNetworkRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for provision_test_network + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkService server. + """ + return request, metadata + + def post_provision_test_network( + self, response: network_messages.Network + ) -> network_messages.Network: + """Post-rpc interceptor for provision_test_network + + DEPRECATED. Please use the `post_provision_test_network_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkService server but before + it is returned to user code. This `post_provision_test_network` interceptor runs + before the `post_provision_test_network_with_metadata` interceptor. + """ + return response + + def post_provision_test_network_with_metadata( + self, + response: network_messages.Network, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[network_messages.Network, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for provision_test_network + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkService server but before it is returned to user code. + + We recommend only using this `post_provision_test_network_with_metadata` + interceptor in new development instead of the `post_provision_test_network` interceptor. + When both interceptors are used, this `post_provision_test_network_with_metadata` interceptor runs after the + `post_provision_test_network` interceptor. The (possibly modified) response returned by + `post_provision_test_network` will be passed to + `post_provision_test_network_with_metadata`. + """ + return response, metadata + + def pre_update_network( + self, + request: network_service.UpdateNetworkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + network_service.UpdateNetworkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_network + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkService server. + """ + return request, metadata + + def post_update_network( + self, response: network_messages.Network + ) -> network_messages.Network: + """Post-rpc interceptor for update_network + + DEPRECATED. Please use the `post_update_network_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkService server but before + it is returned to user code. This `post_update_network` interceptor runs + before the `post_update_network_with_metadata` interceptor. + """ + return response + + def post_update_network_with_metadata( + self, + response: network_messages.Network, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[network_messages.Network, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_network + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkService server but before it is returned to user code. + + We recommend only using this `post_update_network_with_metadata` + interceptor in new development instead of the `post_update_network` interceptor. + When both interceptors are used, this `post_update_network_with_metadata` interceptor runs after the + `post_update_network` interceptor. The (possibly modified) response returned by + `post_update_network` will be passed to + `post_update_network_with_metadata`. + """ + return response, metadata + def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, @@ -334,6 +507,165 @@ def __init__( self._interceptor = interceptor or NetworkServiceRestInterceptor() self._prep_wrapped_messages(client_info) + class _GetDefaultThirdPartyDataDeclaration( + _BaseNetworkServiceRestTransport._BaseGetDefaultThirdPartyDataDeclaration, + NetworkServiceRestStub, + ): + def __hash__(self): + return hash( + "NetworkServiceRestTransport.GetDefaultThirdPartyDataDeclaration" + ) + + @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: network_service.GetDefaultThirdPartyDataDeclarationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> network_messages.DefaultThirdPartyDataDeclaration: + r"""Call the get default third party + data declaration method over HTTP. + + Args: + request (~.network_service.GetDefaultThirdPartyDataDeclarationRequest): + The request object. Request for the ``GetDefaultThirdPartyDataDeclaration`` + 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: + ~.network_messages.DefaultThirdPartyDataDeclaration: + The ``DefaultThirdPartyDataDeclaration`` singleton + resource. + + """ + + http_options = _BaseNetworkServiceRestTransport._BaseGetDefaultThirdPartyDataDeclaration._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_default_third_party_data_declaration( + request, metadata + ) + ) + transcoded_request = _BaseNetworkServiceRestTransport._BaseGetDefaultThirdPartyDataDeclaration._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseNetworkServiceRestTransport._BaseGetDefaultThirdPartyDataDeclaration._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.ads.admanager_v1.NetworkServiceClient.GetDefaultThirdPartyDataDeclaration", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "GetDefaultThirdPartyDataDeclaration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServiceRestTransport._GetDefaultThirdPartyDataDeclaration._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 = network_messages.DefaultThirdPartyDataDeclaration() + pb_resp = network_messages.DefaultThirdPartyDataDeclaration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_default_third_party_data_declaration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_default_third_party_data_declaration_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + network_messages.DefaultThirdPartyDataDeclaration.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.ads.admanager_v1.NetworkServiceClient.get_default_third_party_data_declaration", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "GetDefaultThirdPartyDataDeclaration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetNetwork( _BaseNetworkServiceRestTransport._BaseGetNetwork, NetworkServiceRestStub ): @@ -626,6 +958,320 @@ def __call__( ) return resp + class _ProvisionTestNetwork( + _BaseNetworkServiceRestTransport._BaseProvisionTestNetwork, + NetworkServiceRestStub, + ): + def __hash__(self): + return hash("NetworkServiceRestTransport.ProvisionTestNetwork") + + @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: network_service.ProvisionTestNetworkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> network_messages.Network: + r"""Call the provision test network method over HTTP. + + Args: + request (~.network_service.ProvisionTestNetworkRequest): + The request object. Request for the ``ProvisionTestNetwork`` 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: + ~.network_messages.Network: + The Network resource. + """ + + http_options = _BaseNetworkServiceRestTransport._BaseProvisionTestNetwork._get_http_options() + + request, metadata = self._interceptor.pre_provision_test_network( + request, metadata + ) + transcoded_request = _BaseNetworkServiceRestTransport._BaseProvisionTestNetwork._get_transcoded_request( + http_options, request + ) + + body = _BaseNetworkServiceRestTransport._BaseProvisionTestNetwork._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNetworkServiceRestTransport._BaseProvisionTestNetwork._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.ads.admanager_v1.NetworkServiceClient.ProvisionTestNetwork", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "ProvisionTestNetwork", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServiceRestTransport._ProvisionTestNetwork._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 = network_messages.Network() + pb_resp = network_messages.Network.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_provision_test_network(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_provision_test_network_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = network_messages.Network.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.ads.admanager_v1.NetworkServiceClient.provision_test_network", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "ProvisionTestNetwork", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateNetwork( + _BaseNetworkServiceRestTransport._BaseUpdateNetwork, NetworkServiceRestStub + ): + def __hash__(self): + return hash("NetworkServiceRestTransport.UpdateNetwork") + + @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: network_service.UpdateNetworkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> network_messages.Network: + r"""Call the update network method over HTTP. + + Args: + request (~.network_service.UpdateNetworkRequest): + The request object. Request for the ``UpdateNetwork`` 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: + ~.network_messages.Network: + The Network resource. + """ + + http_options = ( + _BaseNetworkServiceRestTransport._BaseUpdateNetwork._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_network(request, metadata) + transcoded_request = _BaseNetworkServiceRestTransport._BaseUpdateNetwork._get_transcoded_request( + http_options, request + ) + + body = _BaseNetworkServiceRestTransport._BaseUpdateNetwork._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseNetworkServiceRestTransport._BaseUpdateNetwork._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.ads.admanager_v1.NetworkServiceClient.UpdateNetwork", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "UpdateNetwork", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkServiceRestTransport._UpdateNetwork._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 = network_messages.Network() + pb_resp = network_messages.Network.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_network(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_network_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = network_messages.Network.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.ads.admanager_v1.NetworkServiceClient.update_network", + extra={ + "serviceName": "google.ads.admanager.v1.NetworkService", + "rpcName": "UpdateNetwork", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_default_third_party_data_declaration( + self, + ) -> Callable[ + [network_service.GetDefaultThirdPartyDataDeclarationRequest], + network_messages.DefaultThirdPartyDataDeclaration, + ]: + # 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._GetDefaultThirdPartyDataDeclaration( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_network( self, @@ -644,6 +1290,24 @@ def list_networks( # In C++ this would require a dynamic_cast return self._ListNetworks(self._session, self._host, self._interceptor) # type: ignore + @property + def provision_test_network( + self, + ) -> Callable[ + [network_service.ProvisionTestNetworkRequest], network_messages.Network + ]: + # 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._ProvisionTestNetwork(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_network( + self, + ) -> Callable[[network_service.UpdateNetworkRequest], network_messages.Network]: + # 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._UpdateNetwork(self._session, self._host, self._interceptor) # type: ignore + @property def cancel_operation(self): return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest_base.py b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest_base.py index 796a7a7a8471..f08be657c95c 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest_base.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/services/network_service/transports/rest_base.py @@ -88,6 +88,55 @@ def __init__( api_audience=api_audience, ) + class _BaseGetDefaultThirdPartyDataDeclaration: + 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=networks/*/defaultThirdPartyDataDeclaration}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = network_service.GetDefaultThirdPartyDataDeclarationRequest.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( + _BaseNetworkServiceRestTransport._BaseGetDefaultThirdPartyDataDeclaration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetNetwork: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -167,6 +216,105 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseProvisionTestNetwork: + 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/networks:provisionTestNetwork", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = network_service.ProvisionTestNetworkRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateNetwork: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{network.name=networks/*}", + "body": "network", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = network_service.UpdateNetworkRequest.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( + _BaseNetworkServiceRestTransport._BaseUpdateNetwork._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCancelOperation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py index 4325fe4d33e3..c227056e445f 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/__init__.py @@ -151,10 +151,26 @@ from .applied_label import ( AppliedLabel, ) +from .audience_segment_enums import ( + AudienceSegmentApprovalStatusEnum, + AudienceSegmentLicenseTypeEnum, + AudienceSegmentStatusEnum, + AudienceSegmentTypeEnum, +) from .audience_segment_messages import ( AudienceSegment, ) from .audience_segment_service import ( + BatchActivateAudienceSegmentsRequest, + BatchActivateAudienceSegmentsResponse, + BatchApproveAudienceSegmentsRequest, + BatchApproveAudienceSegmentsResponse, + BatchDeactivateAudienceSegmentsRequest, + BatchDeactivateAudienceSegmentsResponse, + BatchPopulateAudienceSegmentsRequest, + BatchPopulateAudienceSegmentsResponse, + BatchRejectAudienceSegmentsRequest, + BatchRejectAudienceSegmentsResponse, GetAudienceSegmentRequest, ListAudienceSegmentsRequest, ListAudienceSegmentsResponse, @@ -229,12 +245,21 @@ from .child_publisher_service import ( BatchCreateChildPublishersRequest, BatchCreateChildPublishersResponse, + BatchRejectChildPublishersRequest, + BatchRejectChildPublishersResponse, + BatchRenegotiateChildPublisherAgreementsRequest, + BatchRenegotiateChildPublisherAgreementsResponse, + BatchResendChildPublisherInvitationEmailsRequest, + BatchResendChildPublisherInvitationEmailsResponse, BatchUpdateChildPublishersRequest, BatchUpdateChildPublishersResponse, + BatchWithdrawChildPublishersRequest, + BatchWithdrawChildPublishersResponse, CreateChildPublisherRequest, GetChildPublisherRequest, ListChildPublishersRequest, ListChildPublishersResponse, + RenegotiateChildPublisherAgreementRequest, UpdateChildPublisherRequest, ) from .cms_metadata_key_enums import ( @@ -777,13 +802,40 @@ ListMobileDeviceSubmodelsRequest, ListMobileDeviceSubmodelsResponse, ) +from .native_style_enums import ( + NativeStyleStatusEnum, +) +from .native_style_messages import ( + NativeStyle, +) +from .native_style_service import ( + BatchActivateNativeStylesRequest, + BatchActivateNativeStylesResponse, + BatchArchiveNativeStylesRequest, + BatchArchiveNativeStylesResponse, + BatchCreateNativeStylesRequest, + BatchCreateNativeStylesResponse, + BatchDeactivateNativeStylesRequest, + BatchDeactivateNativeStylesResponse, + BatchUpdateNativeStylesRequest, + BatchUpdateNativeStylesResponse, + CreateNativeStyleRequest, + GetNativeStyleRequest, + ListNativeStylesRequest, + ListNativeStylesResponse, + UpdateNativeStyleRequest, +) from .network_messages import ( + DefaultThirdPartyDataDeclaration, Network, ) from .network_service import ( + GetDefaultThirdPartyDataDeclarationRequest, GetNetworkRequest, ListNetworksRequest, ListNetworksResponse, + ProvisionTestNetworkRequest, + UpdateNetworkRequest, ) from .nielsen_ctv_pacing_enum import ( NielsenCtvPacingEnum, @@ -1283,7 +1335,21 @@ "ListApplicationsResponse", "UpdateApplicationRequest", "AppliedLabel", + "AudienceSegmentApprovalStatusEnum", + "AudienceSegmentLicenseTypeEnum", + "AudienceSegmentStatusEnum", + "AudienceSegmentTypeEnum", "AudienceSegment", + "BatchActivateAudienceSegmentsRequest", + "BatchActivateAudienceSegmentsResponse", + "BatchApproveAudienceSegmentsRequest", + "BatchApproveAudienceSegmentsResponse", + "BatchDeactivateAudienceSegmentsRequest", + "BatchDeactivateAudienceSegmentsResponse", + "BatchPopulateAudienceSegmentsRequest", + "BatchPopulateAudienceSegmentsResponse", + "BatchRejectAudienceSegmentsRequest", + "BatchRejectAudienceSegmentsResponse", "GetAudienceSegmentRequest", "ListAudienceSegmentsRequest", "ListAudienceSegmentsResponse", @@ -1326,12 +1392,21 @@ "ChildPublisher", "BatchCreateChildPublishersRequest", "BatchCreateChildPublishersResponse", + "BatchRejectChildPublishersRequest", + "BatchRejectChildPublishersResponse", + "BatchRenegotiateChildPublisherAgreementsRequest", + "BatchRenegotiateChildPublisherAgreementsResponse", + "BatchResendChildPublisherInvitationEmailsRequest", + "BatchResendChildPublisherInvitationEmailsResponse", "BatchUpdateChildPublishersRequest", "BatchUpdateChildPublishersResponse", + "BatchWithdrawChildPublishersRequest", + "BatchWithdrawChildPublishersResponse", "CreateChildPublisherRequest", "GetChildPublisherRequest", "ListChildPublishersRequest", "ListChildPublishersResponse", + "RenegotiateChildPublisherAgreementRequest", "UpdateChildPublisherRequest", "CmsMetadataKeyStatusEnum", "CmsMetadataKey", @@ -1667,10 +1742,31 @@ "GetMobileDeviceSubmodelRequest", "ListMobileDeviceSubmodelsRequest", "ListMobileDeviceSubmodelsResponse", + "NativeStyleStatusEnum", + "NativeStyle", + "BatchActivateNativeStylesRequest", + "BatchActivateNativeStylesResponse", + "BatchArchiveNativeStylesRequest", + "BatchArchiveNativeStylesResponse", + "BatchCreateNativeStylesRequest", + "BatchCreateNativeStylesResponse", + "BatchDeactivateNativeStylesRequest", + "BatchDeactivateNativeStylesResponse", + "BatchUpdateNativeStylesRequest", + "BatchUpdateNativeStylesResponse", + "CreateNativeStyleRequest", + "GetNativeStyleRequest", + "ListNativeStylesRequest", + "ListNativeStylesResponse", + "UpdateNativeStyleRequest", + "DefaultThirdPartyDataDeclaration", "Network", + "GetDefaultThirdPartyDataDeclarationRequest", "GetNetworkRequest", "ListNetworksRequest", "ListNetworksResponse", + "ProvisionTestNetworkRequest", + "UpdateNetworkRequest", "NielsenCtvPacingEnum", "NonGuaranteedDealPriority", "OperatingSystem", diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_enums.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_enums.py new file mode 100644 index 000000000000..4e444734874f --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_enums.py @@ -0,0 +1,155 @@ +# -*- 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.admanager.v1", + manifest={ + "AudienceSegmentTypeEnum", + "AudienceSegmentStatusEnum", + "AudienceSegmentLicenseTypeEnum", + "AudienceSegmentApprovalStatusEnum", + }, +) + + +class AudienceSegmentTypeEnum(proto.Message): + r"""Wraps the + [AudienceSegmentType][google.ads.admanager.v1.AudienceSegmentTypeEnum.AudienceSegmentType] + enum. + + """ + + class AudienceSegmentType(proto.Enum): + r"""Specifies the type of an AudienceSegment. + + Values: + AUDIENCE_SEGMENT_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + FIRST_PARTY (1): + Indicates that the segment is a first party + segment created and owned by the publisher. + SHARED (2): + Indicates that the segment is a first party + segment shared by other clients. + THIRD_PARTY (3): + Indicates that the segment is a third party + segment licensed by the publisher from data + providers. This does not include Google-provided + licensed segments. + """ + + AUDIENCE_SEGMENT_TYPE_UNSPECIFIED = 0 + FIRST_PARTY = 1 + SHARED = 2 + THIRD_PARTY = 3 + + +class AudienceSegmentStatusEnum(proto.Message): + r"""Wraps the + [AudienceSegmentStatus][google.ads.admanager.v1.AudienceSegmentStatusEnum.AudienceSegmentStatus] + enum. + + """ + + class AudienceSegmentStatus(proto.Enum): + r"""Specifies the status of an AudienceSegment. + + Values: + AUDIENCE_SEGMENT_STATUS_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Indicates that this audience segment is + available for targeting. + INACTIVE (2): + Indicates that this audience segment is not + available for targeting. + UNUSED (3): + Indicates that this audience segment was + deactivated by Google because it is unused. + """ + + AUDIENCE_SEGMENT_STATUS_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + UNUSED = 3 + + +class AudienceSegmentLicenseTypeEnum(proto.Message): + r"""Wraps the + [AudienceSegmentLicenseType][google.ads.admanager.v1.AudienceSegmentLicenseTypeEnum.AudienceSegmentLicenseType] + enum. + + """ + + class AudienceSegmentLicenseType(proto.Enum): + r"""Specifies the license type of a ThirdPartyAudienceSegment. + + Values: + AUDIENCE_SEGMENT_LICENSE_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + DIRECT (1): + Indicates that the license is the result of a + direct contract between the data provider and + the publisher. + GLOBAL (2): + Indicates that the license is the result of + an agreement between Google and the data + provider, which agrees to license their audience + segments to all the publishers and/or + advertisers of the Google ecosystem. + """ + + AUDIENCE_SEGMENT_LICENSE_TYPE_UNSPECIFIED = 0 + DIRECT = 1 + GLOBAL = 2 + + +class AudienceSegmentApprovalStatusEnum(proto.Message): + r"""Wraps the + [AudienceSegmentApprovalStatus][google.ads.admanager.v1.AudienceSegmentApprovalStatusEnum.AudienceSegmentApprovalStatus] + enum. + + """ + + class AudienceSegmentApprovalStatus(proto.Enum): + r"""Specifies the approval status of a ThirdPartyAudienceSegment. + + Values: + AUDIENCE_SEGMENT_APPROVAL_STATUS_UNSPECIFIED (0): + Default value. This value is unused. + APPROVED (1): + Indicates that this segment is approved and + can be targeted. + REJECTED (2): + Indicates that this segment is rejected and + cannot be targeted. + UNAPPROVED (3): + Indicates that this segment is waiting to be + approved or rejected. It cannot be targeted. + """ + + AUDIENCE_SEGMENT_APPROVAL_STATUS_UNSPECIFIED = 0 + APPROVED = 1 + REJECTED = 2 + UNAPPROVED = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_messages.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_messages.py index b16ba44e7bb2..e6ee971db80b 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_messages.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_messages.py @@ -17,8 +17,12 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.money_pb2 as money_pb2 # type: ignore import proto # type: ignore +from google.ads.admanager_v1.types import audience_segment_enums, targeting + __protobuf__ = proto.module( package="google.ads.admanager.v1", manifest={ @@ -30,34 +34,363 @@ class AudienceSegment(proto.Message): r"""The ``AudienceSegment`` 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: + non_rule_based_first_party_audience_segment (google.ads.admanager_v1.types.AudienceSegment.NonRuleBasedFirstPartyAudienceSegment): + Optional. An ``AudienceSegment`` owned by the publisher + network that does not contain a rule. Cookies are usually + added to these segments through cookie upload. + + This field is a member of `oneof`_ ``sub_type``. + rule_based_first_party_audience_segment (google.ads.admanager_v1.types.AudienceSegment.RuleBasedFirstPartyAudienceSegment): + Optional. An ``AudienceSegment`` owned by the publisher + network that contains a rule. + + This field is a member of `oneof`_ ``sub_type``. + third_party_audience_segment (google.ads.admanager_v1.types.AudienceSegment.ThirdPartyAudienceSegment): + Output only. An ``AudienceSegment`` owned by a data provider + and licensed to the Ad Manager publisher network. + + This field is a member of `oneof`_ ``sub_type``. name (str): Identifier. The resource name of the ``AudienceSegment``. Format: ``networks/{network_code}/audienceSegments/{audience_segment_id}`` - The ``audience_segment_id`` may have up to 1 of the - following suffixes: + The ``audience_segment_id`` is not always numerical and may + have one of the following suffixes: - ``~direct`` for directly licensed third-party segments - ``~global`` for globally licensed third-party segments + shared_id (int): + Output only. The ID of the ``AudienceSegment``. Up to two + resources may share this ID. display_name (str): Required. Display name of the ``AudienceSegment``. The attribute has a maximum length of 255 characters. This field is a member of `oneof`_ ``_display_name``. + category_ids (MutableSequence[int]): + Optional. Unordered list. IDs of the categories that this + audience segment belongs to. See ``segment_categories`` for + additional information about the categories. + description (str): + Optional. Description of the ``AudienceSegment``. This has a + maximum length of 8192 characters. + + This field is a member of `oneof`_ ``_description``. + status (google.ads.admanager_v1.types.AudienceSegmentStatusEnum.AudienceSegmentStatus): + Output only. Non-empty default. Status of the + ``AudienceSegment`` used to determine whether the segment is + available for targeting. Defaults to ``ACTIVE`` if not set. + + This field is a member of `oneof`_ ``_status``. + size (int): + Output only. Number of unique identifiers in the + ``AudienceSegment``. + + This field is a member of `oneof`_ ``_size``. + mobile_web_size (int): + Output only. Number of unique mobile web identifiers in the + ``AudienceSegment``. + + This field is a member of `oneof`_ ``_mobile_web_size``. + idfa_size (int): + Output only. Number of unique Identifier for Advertisers + (IDFA) identifiers in the ``AudienceSegment``. + + This field is a member of `oneof`_ ``_idfa_size``. + ad_id_size (int): + Output only. Number of unique AdID identifiers in the + ``AudienceSegment``. + + This field is a member of `oneof`_ ``_ad_id_size``. + ppid_size (int): + Output only. Number of unique publisher-provided (PPID) + identifiers in the ``AudienceSegment``. + + This field is a member of `oneof`_ ``_ppid_size``. + data_provider_display_name (str): + Output only. Display name of the owner data + provider. For a first-party audience segment, + this is the display name of the publisher + network. Otherwise, this is the display name of + the entity providing the audience segment. + + This field is a member of `oneof`_ ``_data_provider_display_name``. + segment_type (google.ads.admanager_v1.types.AudienceSegmentTypeEnum.AudienceSegmentType): + Output only. Non-empty default. Type of the + ``AudienceSegment``. Every ``AudienceSegment`` is either + ``FIRST_PARTY`` or ``THIRD_PARTY``. + + This field is a member of `oneof`_ ``_segment_type``. """ + class NonRuleBasedFirstPartyAudienceSegment(proto.Message): + r"""An ``AudienceSegment`` owned by the publisher network that does not + contain a rule. Cookies are usually added to these segments through + cookie upload. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + membership_expiration_days (int): + Required. Number of days after which a user's cookie will be + removed from the ``AudienceSegment`` due to inactivity. The + field can be between 1 and 540. + + This field is a member of `oneof`_ ``_membership_expiration_days``. + """ + + membership_expiration_days: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + + class RuleBasedFirstPartyAudienceSegment(proto.Message): + r"""An ``AudienceSegment`` owned by the publisher network that contains + a rule. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + page_views (int): + Required. Number of times a user's cookie must match the + ``rule`` before it's associated with the + ``AudienceSegment``. This is used with ``recency_days`` to + determine eligibility of the association. This attribute is + between 1 and 12. + + This field is a member of `oneof`_ ``_page_views``. + recency_days (int): + Optional. Number of days within which a user's cookie must + match the ``rule`` before it's associated with the + ``AudienceSegment``. This is used with ``page_views`` to + determine eligibility of the association. This attribute is + required if ``page_views`` is greater than 1. When set, it + can be between 1 and 30. + + This field is a member of `oneof`_ ``_recency_days``. + membership_expiration_days (int): + Required. Number of days after which a user's cookie will be + removed from the ``AudienceSegment`` due to inactivity. The + field can be between 1 and 540. + + This field is a member of `oneof`_ ``_membership_expiration_days``. + rule (google.ads.admanager_v1.types.AudienceSegment.Rule): + Required. The rule definition which determines the + eligibility criteria for the ``AudienceSegment``. + """ + + page_views: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + recency_days: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + membership_expiration_days: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + rule: "AudienceSegment.Rule" = proto.Field( + proto.MESSAGE, + number=4, + message="AudienceSegment.Rule", + ) + + class ThirdPartyAudienceSegment(proto.Message): + r"""An ``AudienceSegment`` owned by a data provider and licensed to the + Ad Manager publisher network. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + approval_status (google.ads.admanager_v1.types.AudienceSegmentApprovalStatusEnum.AudienceSegmentApprovalStatus): + Output only. Whether the publisher has + approved or rejected the segment. + + This field is a member of `oneof`_ ``_approval_status``. + cost (google.type.money_pb2.Money): + Output only. The CPM cost for the given + segment. This is assigned by the data provider. + The CPM cost comes from the active pricing if it + exists, otherwise it comes from the latest + pricing. + license_type (google.ads.admanager_v1.types.AudienceSegmentLicenseTypeEnum.AudienceSegmentLicenseType): + Output only. The license type of the external + segment. + + This field is a member of `oneof`_ ``_license_type``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time which this segment becomes + available for use. It is assigned by the data + provider. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time which this segment ceases + to be available. It is assigned by the data + provider. + """ + + approval_status: audience_segment_enums.AudienceSegmentApprovalStatusEnum.AudienceSegmentApprovalStatus = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=audience_segment_enums.AudienceSegmentApprovalStatusEnum.AudienceSegmentApprovalStatus, + ) + cost: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=2, + message=money_pb2.Money, + ) + license_type: audience_segment_enums.AudienceSegmentLicenseTypeEnum.AudienceSegmentLicenseType = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum=audience_segment_enums.AudienceSegmentLicenseTypeEnum.AudienceSegmentLicenseType, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + class Rule(proto.Message): + r"""Eligibility criteria for a user to be part of an + ``AudienceSegment``. + + Attributes: + inventory_targeting (google.ads.admanager_v1.types.InventoryTargeting): + Required. Specification of inventory (i.e. ad + units and placements) that are part of the rule + of the RuleBasedFirstPartyAudienceSegment. + custom_targeting (google.ads.admanager_v1.types.CustomTargeting): + Optional. Specification of custom criteria that are part of + the rule of the RuleBasedFirstPartyAudienceSegment. Once + specified, the server may return a normalized but equivalent + representation of the rule. There are up to 3 levels of + custom criteria allowed. See + [CustomTargeting][google.ads.admanager.v1.CustomTargeting] + and its sub-messages for limitations. + """ + + inventory_targeting: targeting.InventoryTargeting = proto.Field( + proto.MESSAGE, + number=1, + message=targeting.InventoryTargeting, + ) + custom_targeting: targeting.CustomTargeting = proto.Field( + proto.MESSAGE, + number=2, + message=targeting.CustomTargeting, + ) + + non_rule_based_first_party_audience_segment: NonRuleBasedFirstPartyAudienceSegment = proto.Field( + proto.MESSAGE, + number=13, + oneof="sub_type", + message=NonRuleBasedFirstPartyAudienceSegment, + ) + rule_based_first_party_audience_segment: RuleBasedFirstPartyAudienceSegment = ( + proto.Field( + proto.MESSAGE, + number=14, + oneof="sub_type", + message=RuleBasedFirstPartyAudienceSegment, + ) + ) + third_party_audience_segment: ThirdPartyAudienceSegment = proto.Field( + proto.MESSAGE, + number=16, + oneof="sub_type", + message=ThirdPartyAudienceSegment, + ) name: str = proto.Field( proto.STRING, number=1, ) + shared_id: int = proto.Field( + proto.INT64, + number=17, + ) display_name: str = proto.Field( proto.STRING, number=2, optional=True, ) + category_ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + status: audience_segment_enums.AudienceSegmentStatusEnum.AudienceSegmentStatus = ( + proto.Field( + proto.ENUM, + number=5, + optional=True, + enum=audience_segment_enums.AudienceSegmentStatusEnum.AudienceSegmentStatus, + ) + ) + size: int = proto.Field( + proto.INT64, + number=6, + optional=True, + ) + mobile_web_size: int = proto.Field( + proto.INT64, + number=7, + optional=True, + ) + idfa_size: int = proto.Field( + proto.INT64, + number=8, + optional=True, + ) + ad_id_size: int = proto.Field( + proto.INT64, + number=9, + optional=True, + ) + ppid_size: int = proto.Field( + proto.INT64, + number=10, + optional=True, + ) + data_provider_display_name: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + segment_type: audience_segment_enums.AudienceSegmentTypeEnum.AudienceSegmentType = ( + proto.Field( + proto.ENUM, + number=12, + optional=True, + enum=audience_segment_enums.AudienceSegmentTypeEnum.AudienceSegmentType, + ) + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_service.py index af4c14def9c6..188e79deada9 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_service.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/audience_segment_service.py @@ -27,6 +27,16 @@ "GetAudienceSegmentRequest", "ListAudienceSegmentsRequest", "ListAudienceSegmentsResponse", + "BatchActivateAudienceSegmentsRequest", + "BatchActivateAudienceSegmentsResponse", + "BatchDeactivateAudienceSegmentsRequest", + "BatchDeactivateAudienceSegmentsResponse", + "BatchApproveAudienceSegmentsRequest", + "BatchApproveAudienceSegmentsResponse", + "BatchRejectAudienceSegmentsRequest", + "BatchRejectAudienceSegmentsResponse", + "BatchPopulateAudienceSegmentsRequest", + "BatchPopulateAudienceSegmentsResponse", }, ) @@ -74,7 +84,21 @@ class ListAudienceSegmentsRequest(proto.Message): **Filterable fields:** + - ``adIdSize`` + - ``categoryIds`` + - ``dataProviderDisplayName`` - ``displayName`` + - ``idfaSize`` + - ``mobileWebSize`` + - ``ppidSize`` + - ``segmentType`` + - ``sharedId`` + - ``size`` + - ``status`` + - ``thirdPartyAudienceSegment.approvalStatus`` + - ``thirdPartyAudienceSegment.cost`` + - ``thirdPartyAudienceSegment.endTime`` + - ``thirdPartyAudienceSegment.startTime`` order_by (str): Optional. Expression to specify sorting order. See syntax details at @@ -157,4 +181,179 @@ def raw_page(self): ) +class BatchActivateAudienceSegmentsRequest(proto.Message): + r"""Request message for ``BatchActivateAudienceSegments`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchActivateAudienceSegmentsResponse(proto.Message): + r"""Response message for ``BatchActivateAudienceSegments`` method. + + Attributes: + change_count (int): + Number of audience segments activated. + """ + + change_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class BatchDeactivateAudienceSegmentsRequest(proto.Message): + r"""Request message for ``BatchDeactivateAudienceSegments`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchDeactivateAudienceSegmentsResponse(proto.Message): + r"""Response message for ``BatchDeactivateAudienceSegments`` method. + + Attributes: + change_count (int): + Number of audience segments deactivated. + """ + + change_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class BatchApproveAudienceSegmentsRequest(proto.Message): + r"""Request message for ``BatchApproveAudienceSegments`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchApproveAudienceSegmentsResponse(proto.Message): + r"""Response message for ``BatchApproveAudienceSegments`` method. + + Attributes: + change_count (int): + Number of audience segments approved. + """ + + change_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class BatchRejectAudienceSegmentsRequest(proto.Message): + r"""Request message for ``BatchRejectAudienceSegments`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchRejectAudienceSegmentsResponse(proto.Message): + r"""Response message for ``BatchRejectAudienceSegments`` method. + + Attributes: + change_count (int): + Number of audience segments rejected. + """ + + change_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class BatchPopulateAudienceSegmentsRequest(proto.Message): + r"""Request message for ``BatchPopulateAudienceSegments`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the AudienceSegments. Format: + ``networks/{network_code}/audienceSegments/{audience_segment_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchPopulateAudienceSegmentsResponse(proto.Message): + r"""Response message for ``BatchPopulateAudienceSegments`` method. + + Attributes: + change_count (int): + Number of audience segments populated. + """ + + change_count: int = proto.Field( + proto.INT64, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/child_publisher_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/child_publisher_service.py index cc73b27a641e..e450cd741448 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/child_publisher_service.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/child_publisher_service.py @@ -20,7 +20,7 @@ import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import proto # type: ignore -from google.ads.admanager_v1.types import child_publisher_messages +from google.ads.admanager_v1.types import child_publisher_messages, mcm_enums __protobuf__ = proto.module( package="google.ads.admanager.v1", @@ -34,6 +34,15 @@ "UpdateChildPublisherRequest", "BatchUpdateChildPublishersRequest", "BatchUpdateChildPublishersResponse", + "RenegotiateChildPublisherAgreementRequest", + "BatchRenegotiateChildPublisherAgreementsRequest", + "BatchRenegotiateChildPublisherAgreementsResponse", + "BatchResendChildPublisherInvitationEmailsRequest", + "BatchResendChildPublisherInvitationEmailsResponse", + "BatchWithdrawChildPublishersRequest", + "BatchWithdrawChildPublishersResponse", + "BatchRejectChildPublishersRequest", + "BatchRejectChildPublishersResponse", }, ) @@ -332,4 +341,207 @@ class BatchUpdateChildPublishersResponse(proto.Message): ) +class RenegotiateChildPublisherAgreementRequest(proto.Message): + r"""Request message to renegotiate a + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]'s agreement + (i.e., invite with updated terms). + + Attributes: + name (str): + Required. Resource name of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + display_name (str): + Optional. The display name to set for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + email_address (str): + Optional. The email address to set for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + network (str): + Optional. The resource name of the Ad Manager network to set + for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + + This field may not update the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]'s + Ad Manager network if it is already associated with one. + + Format: ``networks/{network_code}`` + delegation_type (google.ads.admanager_v1.types.DelegationTypeEnum.DelegationType): + Optional. The type of delegation to set for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + parent_revenue_share_millipercent (int): + Optional. The revenue share to set that the parent publisher + will receive in millipercent (e.g., 15000 millipercent is + %15) for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + + This field is only settable for Manage Account + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s of + non-reseller parent publishers. Otherwise, it is ignored and + always 100%. + seller_id (str): + Optional. The seller ID to set for the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + whose agreement is being renegotiated. + + This field is only applicable to Manage Inventory + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + email_address: str = proto.Field( + proto.STRING, + number=3, + ) + network: str = proto.Field( + proto.STRING, + number=4, + ) + delegation_type: mcm_enums.DelegationTypeEnum.DelegationType = proto.Field( + proto.ENUM, + number=5, + enum=mcm_enums.DelegationTypeEnum.DelegationType, + ) + parent_revenue_share_millipercent: int = proto.Field( + proto.INT64, + number=6, + ) + seller_id: str = proto.Field( + proto.STRING, + number=7, + ) + + +class BatchRenegotiateChildPublisherAgreementsRequest(proto.Message): + r"""Request message for [BatchRenegotiateChildPublisherAgreements][] + method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + requests (MutableSequence[google.ads.admanager_v1.types.RenegotiateChildPublisherAgreementRequest]): + Required. The requests to renegotiate + [ChildPublisher][google.ads.admanager.v1.ChildPublisher] + agreements. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["RenegotiateChildPublisherAgreementRequest"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="RenegotiateChildPublisherAgreementRequest", + ) + ) + + +class BatchRenegotiateChildPublisherAgreementsResponse(proto.Message): + r"""Response message for [BatchRenegotiateChildPublisherAgreements][] + method. + + """ + + +class BatchResendChildPublisherInvitationEmailsRequest(proto.Message): + r"""Request message for [BatchResendChildPublisherInvitationEmails][] + method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s + that should be resent invitation emails. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchResendChildPublisherInvitationEmailsResponse(proto.Message): + r"""Response message for [BatchResendChildPublisherInvitationEmails][] + method. + + """ + + +class BatchWithdrawChildPublishersRequest(proto.Message): + r"""Request message for [BatchWithdrawChildPublishers][] method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s to + withdraw. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchWithdrawChildPublishersResponse(proto.Message): + r"""Response message for [BatchWithdrawChildPublishers][] method.""" + + +class BatchRejectChildPublishersRequest(proto.Message): + r"""Request message for [BatchRejectChildPublishers][] method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names of the + [ChildPublisher][google.ads.admanager.v1.ChildPublisher]s to + reject. Format: + ``networks/{network_code}/childPublisher/{child_publisher_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchRejectChildPublishersResponse(proto.Message): + r"""Response message for [BatchRejectChildPublishers][] method.""" + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_enums.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_enums.py new file mode 100644 index 000000000000..3a76101985b3 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_enums.py @@ -0,0 +1,61 @@ +# -*- 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.admanager.v1", + manifest={ + "NativeStyleStatusEnum", + }, +) + + +class NativeStyleStatusEnum(proto.Message): + r"""Wrapper message for + [NativeStyleStatus][google.ads.admanager.v1.NativeStyleStatusEnum.NativeStyleStatus] + + """ + + class NativeStyleStatus(proto.Enum): + r"""Describes status of the native style. + + Values: + NATIVE_STYLE_STATUS_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The native style is active. Active native + styles are used in ad serving. + ARCHIVED (2): + The native style is archived. Archived native + styles are not visible in the UI and not used in + ad serving. + INACTIVE (3): + The native style is inactive. Inactive native + styles are not used in ad serving, but visible + in the UI. + """ + + NATIVE_STYLE_STATUS_UNSPECIFIED = 0 + ACTIVE = 1 + ARCHIVED = 2 + INACTIVE = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_messages.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_messages.py new file mode 100644 index 000000000000..bcc9b88f0f99 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_messages.py @@ -0,0 +1,124 @@ +# -*- 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 + +from google.ads.admanager_v1.types import native_style_enums +from google.ads.admanager_v1.types import size as gaa_size +from google.ads.admanager_v1.types import targeting as gaa_targeting + +__protobuf__ = proto.module( + package="google.ads.admanager.v1", + manifest={ + "NativeStyle", + }, +) + + +class NativeStyle(proto.Message): + r"""Used to define the look and feel of native ads, for both web + and apps. Native styles determine how native creatives look for + a segment of inventory. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the ``NativeStyle``. + Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + creative_template (str): + Required. Immutable. The creative template this native style + is associated with. Format: + "networks/{network_code}/creativeTemplates/{creative_template}". + + This field is a member of `oneof`_ ``_creative_template``. + display_name (str): + Required. The display name of the native + style. This attribute has a maximum length of + 255 characters. + + This field is a member of `oneof`_ ``_display_name``. + html_snippet (str): + Optional. The HTML snippet of the native + style with placeholders for the associated + variables. + + This field is a member of `oneof`_ ``_html_snippet``. + css_snippet (str): + Optional. The CSS snippet of the native + style, with placeholders for the associated + variables. + + This field is a member of `oneof`_ ``_css_snippet``. + targeting (google.ads.admanager_v1.types.Targeting): + Optional. The targeting criteria for this + native style. + status (google.ads.admanager_v1.types.NativeStyleStatusEnum.NativeStyleStatus): + Output only. The status of the native style. + + This field is a member of `oneof`_ ``_status``. + size (google.ads.admanager_v1.types.Size): + Required. The size of the native style. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + creative_template: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + html_snippet: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + css_snippet: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + targeting: gaa_targeting.Targeting = proto.Field( + proto.MESSAGE, + number=9, + message=gaa_targeting.Targeting, + ) + status: native_style_enums.NativeStyleStatusEnum.NativeStyleStatus = proto.Field( + proto.ENUM, + number=10, + optional=True, + enum=native_style_enums.NativeStyleStatusEnum.NativeStyleStatus, + ) + size: gaa_size.Size = proto.Field( + proto.MESSAGE, + number=12, + message=gaa_size.Size, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_service.py new file mode 100644 index 000000000000..f8269b302c47 --- /dev/null +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/native_style_service.py @@ -0,0 +1,381 @@ +# -*- 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.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.ads.admanager_v1.types import native_style_messages + +__protobuf__ = proto.module( + package="google.ads.admanager.v1", + manifest={ + "GetNativeStyleRequest", + "ListNativeStylesRequest", + "ListNativeStylesResponse", + "CreateNativeStyleRequest", + "BatchCreateNativeStylesRequest", + "BatchCreateNativeStylesResponse", + "UpdateNativeStyleRequest", + "BatchUpdateNativeStylesRequest", + "BatchUpdateNativeStylesResponse", + "BatchActivateNativeStylesRequest", + "BatchActivateNativeStylesResponse", + "BatchDeactivateNativeStylesRequest", + "BatchDeactivateNativeStylesResponse", + "BatchArchiveNativeStylesRequest", + "BatchArchiveNativeStylesResponse", + }, +) + + +class GetNativeStyleRequest(proto.Message): + r"""Request object for ``GetNativeStyle`` method. + + Attributes: + name (str): + Required. The resource name of the NativeStyle. Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListNativeStylesRequest(proto.Message): + r"""Request object for ``ListNativeStyles`` method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + NativeStyles. Format: ``networks/{network_code}`` + page_size (int): + Optional. The maximum number of ``NativeStyles`` to return. + The service may return fewer than this value. If + unspecified, at most 50 ``NativeStyles`` will be returned. + The maximum value is 1000; values greater than 1000 will be + coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListNativeStyles`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListNativeStyles`` must match the call that provided the + page token. + filter (str): + Optional. Expression to filter the response. See syntax + details at + https://developers.google.com/ad-manager/api/beta/filters + + **Filterable fields:** + + - ``creativeTemplate`` + - ``displayName`` + - ``name`` + - ``size.canonicalName`` + - ``status`` + order_by (str): + Optional. Expression to specify sorting + order. See syntax details at + https://developers.google.com/ad-manager/api/beta/filters#order + skip (int): + Optional. Number of individual resources to + skip while paginating. + """ + + 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, + ) + skip: int = proto.Field( + proto.INT32, + number=6, + ) + + +class ListNativeStylesResponse(proto.Message): + r"""Response object for ``ListNativeStylesRequest`` containing matching + ``NativeStyle`` objects. + + Attributes: + native_styles (MutableSequence[google.ads.admanager_v1.types.NativeStyle]): + The ``NativeStyle`` objects from the specified network. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + total_size (int): + Total number of ``NativeStyle`` objects. If a filter was + included in the request, this reflects the total number + after the filtering is applied. + + ``total_size`` won't be calculated in the response unless it + has been included in a response field mask. The response + field mask can be provided to the method by using the URL + parameter ``$fields`` or ``fields``, or by using the + HTTP/gRPC header ``X-Goog-FieldMask``. + + For more information, see + https://developers.google.com/ad-manager/api/beta/field-masks + """ + + @property + def raw_page(self): + return self + + native_styles: MutableSequence[native_style_messages.NativeStyle] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=native_style_messages.NativeStyle, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class CreateNativeStyleRequest(proto.Message): + r"""Request object for ``CreateNativeStyle`` method. + + Attributes: + parent (str): + Required. The parent resource where this ``NativeStyle`` + will be created. Format: ``networks/{network_code}`` + native_style (google.ads.admanager_v1.types.NativeStyle): + Required. The ``NativeStyle`` to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + native_style: native_style_messages.NativeStyle = proto.Field( + proto.MESSAGE, + number=2, + message=native_style_messages.NativeStyle, + ) + + +class BatchCreateNativeStylesRequest(proto.Message): + r"""Request object for ``BatchCreateNativeStyles`` method. + + Attributes: + parent (str): + Required. The parent resource where ``NativeStyles`` will be + created. Format: ``networks/{network_code}`` The parent + field in the CreateNativeStyleRequest must match this field. + requests (MutableSequence[google.ads.admanager_v1.types.CreateNativeStyleRequest]): + Required. The ``NativeStyle`` objects to create. A maximum + of 100 objects can be created in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["CreateNativeStyleRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CreateNativeStyleRequest", + ) + + +class BatchCreateNativeStylesResponse(proto.Message): + r"""Response object for ``BatchCreateNativeStyles`` method. + + Attributes: + native_styles (MutableSequence[google.ads.admanager_v1.types.NativeStyle]): + The ``NativeStyle`` objects created. + """ + + native_styles: MutableSequence[native_style_messages.NativeStyle] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=native_style_messages.NativeStyle, + ) + ) + + +class UpdateNativeStyleRequest(proto.Message): + r"""Request object for ``UpdateNativeStyle`` method. + + Attributes: + native_style (google.ads.admanager_v1.types.NativeStyle): + Required. The ``NativeStyle`` to update. + + The ``NativeStyle``'s ``name`` is used to identify the + ``NativeStyle`` to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + native_style: native_style_messages.NativeStyle = proto.Field( + proto.MESSAGE, + number=1, + message=native_style_messages.NativeStyle, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdateNativeStylesRequest(proto.Message): + r"""Request object for ``BatchUpdateNativeStyles`` method. + + Attributes: + parent (str): + Required. The parent resource where ``NativeStyles`` will be + updated. Format: ``networks/{network_code}`` The parent + field in the UpdateNativeStyleRequest must match this field. + requests (MutableSequence[google.ads.admanager_v1.types.UpdateNativeStyleRequest]): + Required. The ``NativeStyle`` objects to update. A maximum + of 100 objects can be updated in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["UpdateNativeStyleRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="UpdateNativeStyleRequest", + ) + + +class BatchUpdateNativeStylesResponse(proto.Message): + r"""Response object for ``BatchUpdateNativeStyles`` method. + + Attributes: + native_styles (MutableSequence[google.ads.admanager_v1.types.NativeStyle]): + The ``NativeStyle`` objects updated. + """ + + native_styles: MutableSequence[native_style_messages.NativeStyle] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=native_style_messages.NativeStyle, + ) + ) + + +class BatchActivateNativeStylesRequest(proto.Message): + r"""Request object for ``BatchActivateNativeStyles`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchActivateNativeStylesResponse(proto.Message): + r"""Response object for ``BatchActivateNativeStyles`` method.""" + + +class BatchDeactivateNativeStylesRequest(proto.Message): + r"""Request object for ``BatchDeactivateNativeStyles`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchDeactivateNativeStylesResponse(proto.Message): + r"""Response object for ``BatchDeactivateNativeStyles`` method.""" + + +class BatchArchiveNativeStylesRequest(proto.Message): + r"""Request object for ``BatchArchiveNativeStyles`` method. + + Attributes: + parent (str): + Required. Format: ``networks/{network_code}`` + names (MutableSequence[str]): + Required. Resource names for the ``NativeStyle``\ s. Format: + ``networks/{network_code}/nativeStyles/{native_style_id}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchArchiveNativeStylesResponse(proto.Message): + r"""Response object for ``BatchArchiveNativeStyles`` method.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/network_messages.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/network_messages.py index 8c16b418f2c8..d9e4c35d650d 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/network_messages.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/network_messages.py @@ -19,10 +19,15 @@ import proto # type: ignore +from google.ads.admanager_v1.types import ( + third_party_data_declaration as gaa_third_party_data_declaration, +) + __protobuf__ = proto.module( package="google.ads.admanager.v1", manifest={ "Network", + "DefaultThirdPartyDataDeclaration", }, ) @@ -129,4 +134,34 @@ class Network(proto.Message): ) +class DefaultThirdPartyDataDeclaration(proto.Message): + r"""The ``DefaultThirdPartyDataDeclaration`` singleton resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the + ``DefaultThirdPartyDataDeclaration``. Format: + ``networks/{network_code}/defaultThirdPartyDataDeclaration`` + third_party_data_declaration (google.ads.admanager_v1.types.ThirdPartyDataDeclaration): + Optional. Returns the default [ThirdPartyDataDeclaration] + for this network. If this setting has never been updated on + your network, then this API response will be unset. + + This field is a member of `oneof`_ ``_third_party_data_declaration``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + third_party_data_declaration: gaa_third_party_data_declaration.ThirdPartyDataDeclaration = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=gaa_third_party_data_declaration.ThirdPartyDataDeclaration, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/network_service.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/network_service.py index 87e74faa9524..2aa0f5427e7e 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/network_service.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/network_service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import proto # type: ignore from google.ads.admanager_v1.types import network_messages @@ -24,13 +25,41 @@ __protobuf__ = proto.module( package="google.ads.admanager.v1", manifest={ + "UpdateNetworkRequest", "GetNetworkRequest", "ListNetworksRequest", "ListNetworksResponse", + "ProvisionTestNetworkRequest", + "GetDefaultThirdPartyDataDeclarationRequest", }, ) +class UpdateNetworkRequest(proto.Message): + r"""Request for the ``UpdateNetwork`` method. + + Attributes: + network (google.ads.admanager_v1.types.Network): + Required. The ``Network`` to update. + + The ``Network``'s ``name`` is used to identify the + ``Network`` to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + network: network_messages.Network = proto.Field( + proto.MESSAGE, + number=1, + message=network_messages.Network, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + class GetNetworkRequest(proto.Message): r"""Request to get Network @@ -125,4 +154,24 @@ def raw_page(self): ) +class ProvisionTestNetworkRequest(proto.Message): + r"""Request for the ``ProvisionTestNetwork`` method.""" + + +class GetDefaultThirdPartyDataDeclarationRequest(proto.Message): + r"""Request for the ``GetDefaultThirdPartyDataDeclaration`` method. + + Attributes: + name (str): + Required. Resource name of DefaultThirdPartyDataDeclaration. + Format: + networks/{network_code}/defaultThirdPartyDataDeclaration + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py index b4a0be6ed461..3d8ddb9be0d7 100644 --- a/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py +++ b/packages/google-ads-admanager/google/ads/admanager_v1/types/report_definition.py @@ -2253,7 +2253,8 @@ class Dimension(proto.Enum): Corresponds to "Demand subchannel value" in the Ad Manager UI (when showing API fields). - Compatible with the following report types: ``HISTORICAL`` + Compatible with the following report types: ``HISTORICAL``, + ``ON_PLATFORM_MULTICALL`` Data format: ``ENUM`` DEMAND_SUBCHANNEL_NAME (23): @@ -2261,7 +2262,8 @@ class Dimension(proto.Enum): Corresponds to "Demand subchannel" in the Ad Manager UI. - Compatible with the following report types: ``HISTORICAL`` + Compatible with the following report types: ``HISTORICAL``, + ``ON_PLATFORM_MULTICALL`` Data format: ``STRING`` DEVICE (226): @@ -2561,6 +2563,15 @@ class Dimension(proto.Enum): Compatible with the following report types: ``HISTORICAL`` Data format: ``STRING`` + HIGH_ENGAGEMENT_ADS_ALLOWED (838): + High engagement ads allowed. + + Corresponds to "High engagement ads allowed" in the Ad + Manager UI. + + Compatible with the following report types: ``HISTORICAL`` + + Data format: ``BOOLEAN`` HOUR (100): Breaks down reporting data by hour in one day. @@ -5187,6 +5198,24 @@ class Dimension(proto.Enum): Compatible with the following report types: ``HISTORICAL`` + Data format: ``STRING`` + WEB_INTERSTITIAL_TRIGGER_TYPE (826): + Web interstitial trigger type. + + Corresponds to "Web interstitial trigger type value" in the + Ad Manager UI (when showing API fields). + + Compatible with the following report types: ``HISTORICAL`` + + Data format: ``ENUM`` + WEB_INTERSTITIAL_TRIGGER_TYPE_NAME (827): + Localized name of the web interstitial trigger type. + + Corresponds to "Web interstitial trigger type" in the Ad + Manager UI. + + Compatible with the following report types: ``HISTORICAL`` + Data format: ``STRING`` WEB_PROPERTY_CODE (730): Web property code @@ -6761,6 +6790,7 @@ class Dimension(proto.Enum): HBT_YIELD_PARTNER_NAME = 660 HEADER_BIDDER_INTEGRATION_TYPE = 718 HEADER_BIDDER_INTEGRATION_TYPE_NAME = 719 + HIGH_ENGAGEMENT_ADS_ALLOWED = 838 HOUR = 100 IMPRESSION_COUNTING_METHOD = 577 IMPRESSION_COUNTING_METHOD_NAME = 578 @@ -7032,6 +7062,8 @@ class Dimension(proto.Enum): VIDEO_SDK_VERSION_NAME = 441 VIDEO_STITCHER_TYPE = 752 VIDEO_STITCHER_TYPE_NAME = 753 + WEB_INTERSTITIAL_TRIGGER_TYPE = 826 + WEB_INTERSTITIAL_TRIGGER_TYPE_NAME = 827 WEB_PROPERTY_CODE = 730 WEEK = 5 YIELD_GROUP_BUYER_NAME = 184 @@ -13269,7 +13301,7 @@ class RelativeDateRange(proto.Enum): The entire previous 6 calendar months preceding the calendar month the report is run. LAST_12_MONTHS (20): - The entire previous 6 calendar months + The entire previous 12 calendar months preceding the calendar month the report is run. ALL_AVAILABLE (21): From 3 years before the report is run, to the diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_activate_audience_segments_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_activate_audience_segments_sync.py new file mode 100644 index 000000000000..4ceaa200373e --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_activate_audience_segments_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 BatchActivateAudienceSegments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_AudienceSegmentService_BatchActivateAudienceSegments_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.ads import admanager_v1 + + +def sample_batch_activate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateAudienceSegmentsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_activate_audience_segments(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_AudienceSegmentService_BatchActivateAudienceSegments_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_approve_audience_segments_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_approve_audience_segments_sync.py new file mode 100644 index 000000000000..e890fccb41d1 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_approve_audience_segments_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 BatchApproveAudienceSegments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_AudienceSegmentService_BatchApproveAudienceSegments_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.ads import admanager_v1 + + +def sample_batch_approve_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchApproveAudienceSegmentsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_approve_audience_segments(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_AudienceSegmentService_BatchApproveAudienceSegments_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_deactivate_audience_segments_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_deactivate_audience_segments_sync.py new file mode 100644 index 000000000000..9dd0fd5e8866 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_deactivate_audience_segments_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 BatchDeactivateAudienceSegments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_AudienceSegmentService_BatchDeactivateAudienceSegments_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.ads import admanager_v1 + + +def sample_batch_deactivate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateAudienceSegmentsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_deactivate_audience_segments(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_AudienceSegmentService_BatchDeactivateAudienceSegments_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_populate_audience_segments_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_populate_audience_segments_sync.py new file mode 100644 index 000000000000..6f84d8386f7b --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_populate_audience_segments_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 BatchPopulateAudienceSegments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_AudienceSegmentService_BatchPopulateAudienceSegments_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.ads import admanager_v1 + + +def sample_batch_populate_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchPopulateAudienceSegmentsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_populate_audience_segments(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_AudienceSegmentService_BatchPopulateAudienceSegments_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_reject_audience_segments_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_reject_audience_segments_sync.py new file mode 100644 index 000000000000..61d4dcc79069 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_audience_segment_service_batch_reject_audience_segments_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 BatchRejectAudienceSegments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_AudienceSegmentService_BatchRejectAudienceSegments_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.ads import admanager_v1 + + +def sample_batch_reject_audience_segments(): + # Create a client + client = admanager_v1.AudienceSegmentServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchRejectAudienceSegmentsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_reject_audience_segments(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_AudienceSegmentService_BatchRejectAudienceSegments_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_reject_child_publishers_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_reject_child_publishers_sync.py new file mode 100644 index 000000000000..5d58323e2374 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_reject_child_publishers_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 BatchRejectChildPublishers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_ChildPublisherService_BatchRejectChildPublishers_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.ads import admanager_v1 + + +def sample_batch_reject_child_publishers(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchRejectChildPublishersRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_reject_child_publishers(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_ChildPublisherService_BatchRejectChildPublishers_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_renegotiate_child_publisher_agreements_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_renegotiate_child_publisher_agreements_sync.py new file mode 100644 index 000000000000..e9a57cfeed6e --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_renegotiate_child_publisher_agreements_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 BatchRenegotiateChildPublisherAgreements +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_ChildPublisherService_BatchRenegotiateChildPublisherAgreements_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.ads import admanager_v1 + + +def sample_batch_renegotiate_child_publisher_agreements(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.RenegotiateChildPublisherAgreementRequest() + requests.name = "name_value" + + request = admanager_v1.BatchRenegotiateChildPublisherAgreementsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_renegotiate_child_publisher_agreements(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_ChildPublisherService_BatchRenegotiateChildPublisherAgreements_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_resend_child_publisher_invitation_emails_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_resend_child_publisher_invitation_emails_sync.py new file mode 100644 index 000000000000..3dd52ba0a864 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_resend_child_publisher_invitation_emails_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 BatchResendChildPublisherInvitationEmails +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_ChildPublisherService_BatchResendChildPublisherInvitationEmails_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.ads import admanager_v1 + + +def sample_batch_resend_child_publisher_invitation_emails(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchResendChildPublisherInvitationEmailsRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_resend_child_publisher_invitation_emails(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_ChildPublisherService_BatchResendChildPublisherInvitationEmails_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_withdraw_child_publishers_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_withdraw_child_publishers_sync.py new file mode 100644 index 000000000000..a98a3864db40 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_child_publisher_service_batch_withdraw_child_publishers_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 BatchWithdrawChildPublishers +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_ChildPublisherService_BatchWithdrawChildPublishers_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.ads import admanager_v1 + + +def sample_batch_withdraw_child_publishers(): + # Create a client + client = admanager_v1.ChildPublisherServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchWithdrawChildPublishersRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_withdraw_child_publishers(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_ChildPublisherService_BatchWithdrawChildPublishers_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_activate_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_activate_native_styles_sync.py new file mode 100644 index 000000000000..52cb9112df5d --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_activate_native_styles_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 BatchActivateNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_BatchActivateNativeStyles_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.ads import admanager_v1 + + +def sample_batch_activate_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchActivateNativeStylesRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_activate_native_styles(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_BatchActivateNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_archive_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_archive_native_styles_sync.py new file mode 100644 index 000000000000..2470f266ce55 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_archive_native_styles_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 BatchArchiveNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_BatchArchiveNativeStyles_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.ads import admanager_v1 + + +def sample_batch_archive_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchArchiveNativeStylesRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_archive_native_styles(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_BatchArchiveNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_create_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_create_native_styles_sync.py new file mode 100644 index 000000000000..6679a040baf2 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_create_native_styles_sync.py @@ -0,0 +1,60 @@ +# -*- 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 BatchCreateNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_BatchCreateNativeStyles_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.ads import admanager_v1 + + +def sample_batch_create_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.CreateNativeStyleRequest() + requests.parent = "parent_value" + requests.native_style.size.width = 544 + requests.native_style.size.height = 633 + requests.native_style.size.size_type = "AUDIO" + + request = admanager_v1.BatchCreateNativeStylesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_native_styles(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_BatchCreateNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_deactivate_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_deactivate_native_styles_sync.py new file mode 100644 index 000000000000..b72c79c81be6 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_deactivate_native_styles_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 BatchDeactivateNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_BatchDeactivateNativeStyles_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.ads import admanager_v1 + + +def sample_batch_deactivate_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.BatchDeactivateNativeStylesRequest( + parent="parent_value", + names=["names_value1", "names_value2"], + ) + + # Make the request + response = client.batch_deactivate_native_styles(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_BatchDeactivateNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_update_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_update_native_styles_sync.py new file mode 100644 index 000000000000..b4d0d3baac06 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_batch_update_native_styles_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 BatchUpdateNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_BatchUpdateNativeStyles_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.ads import admanager_v1 + + +def sample_batch_update_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + requests = admanager_v1.UpdateNativeStyleRequest() + requests.native_style.size.width = 544 + requests.native_style.size.height = 633 + requests.native_style.size.size_type = "AUDIO" + + request = admanager_v1.BatchUpdateNativeStylesRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_update_native_styles(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_BatchUpdateNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_get_native_style_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_get_native_style_sync.py new file mode 100644 index 000000000000..fccac987e19e --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_get_native_style_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 GetNativeStyle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_GetNativeStyle_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.ads import admanager_v1 + + +def sample_get_native_style(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetNativeStyleRequest( + name="name_value", + ) + + # Make the request + response = client.get_native_style(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NativeStyleService_GetNativeStyle_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_list_native_styles_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_list_native_styles_sync.py new file mode 100644 index 000000000000..6bcac34a07f8 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_native_style_service_list_native_styles_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 ListNativeStyles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NativeStyleService_ListNativeStyles_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.ads import admanager_v1 + + +def sample_list_native_styles(): + # Create a client + client = admanager_v1.NativeStyleServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ListNativeStylesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_native_styles(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END admanager_v1_generated_NativeStyleService_ListNativeStyles_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_get_default_third_party_data_declaration_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_get_default_third_party_data_declaration_sync.py new file mode 100644 index 000000000000..9d63c68c1790 --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_get_default_third_party_data_declaration_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 GetDefaultThirdPartyDataDeclaration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NetworkService_GetDefaultThirdPartyDataDeclaration_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.ads import admanager_v1 + + +def sample_get_default_third_party_data_declaration(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.GetDefaultThirdPartyDataDeclarationRequest( + name="name_value", + ) + + # Make the request + response = client.get_default_third_party_data_declaration(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NetworkService_GetDefaultThirdPartyDataDeclaration_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_provision_test_network_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_provision_test_network_sync.py new file mode 100644 index 000000000000..72eddea48ecc --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_provision_test_network_sync.py @@ -0,0 +1,51 @@ +# -*- 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 ProvisionTestNetwork +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NetworkService_ProvisionTestNetwork_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.ads import admanager_v1 + + +def sample_provision_test_network(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.ProvisionTestNetworkRequest() + + # Make the request + response = client.provision_test_network(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NetworkService_ProvisionTestNetwork_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_update_network_sync.py b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_update_network_sync.py new file mode 100644 index 000000000000..f2af67162b5f --- /dev/null +++ b/packages/google-ads-admanager/samples/generated_samples/admanager_v1_generated_network_service_update_network_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateNetwork +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-ads-admanager + + +# [START admanager_v1_generated_NetworkService_UpdateNetwork_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.ads import admanager_v1 + + +def sample_update_network(): + # Create a client + client = admanager_v1.NetworkServiceClient() + + # Initialize request argument(s) + request = admanager_v1.UpdateNetworkRequest() + + # Make the request + response = client.update_network(request=request) + + # Handle the response + print(response) + + +# [END admanager_v1_generated_NetworkService_UpdateNetwork_sync] diff --git a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json index a23728be835d..6f90dca8e0f3 100644 --- a/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json +++ b/packages/google-ads-admanager/samples/generated_samples/snippet_metadata_google.ads.admanager.v1.json @@ -3396,24 +3396,28 @@ "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.get_audience_segment", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.batch_activate_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.AudienceSegmentService.GetAudienceSegment", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.BatchActivateAudienceSegments", "service": { "fullName": "google.ads.admanager.v1.AudienceSegmentService", "shortName": "AudienceSegmentService" }, - "shortName": "GetAudienceSegment" + "shortName": "BatchActivateAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetAudienceSegmentRequest" + "type": "google.ads.admanager_v1.types.BatchActivateAudienceSegmentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3427,22 +3431,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.AudienceSegment", - "shortName": "get_audience_segment" + "resultType": "google.ads.admanager_v1.types.BatchActivateAudienceSegmentsResponse", + "shortName": "batch_activate_audience_segments" }, - "description": "Sample for GetAudienceSegment", - "file": "admanager_v1_generated_audience_segment_service_get_audience_segment_sync.py", + "description": "Sample for BatchActivateAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_batch_activate_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_AudienceSegmentService_GetAudienceSegment_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_BatchActivateAudienceSegments_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3452,22 +3456,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_audience_segment_service_get_audience_segment_sync.py" + "title": "admanager_v1_generated_audience_segment_service_batch_activate_audience_segments_sync.py" }, { "canonical": true, @@ -3476,24 +3480,28 @@ "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.list_audience_segments", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.batch_approve_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.AudienceSegmentService.ListAudienceSegments", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.BatchApproveAudienceSegments", "service": { "fullName": "google.ads.admanager.v1.AudienceSegmentService", "shortName": "AudienceSegmentService" }, - "shortName": "ListAudienceSegments" + "shortName": "BatchApproveAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListAudienceSegmentsRequest" + "type": "google.ads.admanager_v1.types.BatchApproveAudienceSegmentsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3507,14 +3515,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.audience_segment_service.pagers.ListAudienceSegmentsPager", - "shortName": "list_audience_segments" + "resultType": "google.ads.admanager_v1.types.BatchApproveAudienceSegmentsResponse", + "shortName": "batch_approve_audience_segments" }, - "description": "Sample for ListAudienceSegments", - "file": "admanager_v1_generated_audience_segment_service_list_audience_segments_sync.py", + "description": "Sample for BatchApproveAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_batch_approve_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_AudienceSegmentService_ListAudienceSegments_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_BatchApproveAudienceSegments_sync", "segments": [ { "end": 52, @@ -3532,48 +3540,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_audience_segment_service_list_audience_segments_sync.py" + "title": "admanager_v1_generated_audience_segment_service_batch_approve_audience_segments_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient", - "shortName": "BandwidthGroupServiceClient" + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", + "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient.get_bandwidth_group", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.batch_deactivate_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.BandwidthGroupService.GetBandwidthGroup", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.BatchDeactivateAudienceSegments", "service": { - "fullName": "google.ads.admanager.v1.BandwidthGroupService", - "shortName": "BandwidthGroupService" + "fullName": "google.ads.admanager.v1.AudienceSegmentService", + "shortName": "AudienceSegmentService" }, - "shortName": "GetBandwidthGroup" + "shortName": "BatchDeactivateAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetBandwidthGroupRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateAudienceSegmentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3587,22 +3599,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BandwidthGroup", - "shortName": "get_bandwidth_group" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateAudienceSegmentsResponse", + "shortName": "batch_deactivate_audience_segments" }, - "description": "Sample for GetBandwidthGroup", - "file": "admanager_v1_generated_bandwidth_group_service_get_bandwidth_group_sync.py", + "description": "Sample for BatchDeactivateAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_batch_deactivate_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BandwidthGroupService_GetBandwidthGroup_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_BatchDeactivateAudienceSegments_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3612,48 +3624,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_bandwidth_group_service_get_bandwidth_group_sync.py" + "title": "admanager_v1_generated_audience_segment_service_batch_deactivate_audience_segments_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient", - "shortName": "BandwidthGroupServiceClient" + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", + "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient.list_bandwidth_groups", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.batch_populate_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.BandwidthGroupService.ListBandwidthGroups", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.BatchPopulateAudienceSegments", "service": { - "fullName": "google.ads.admanager.v1.BandwidthGroupService", - "shortName": "BandwidthGroupService" + "fullName": "google.ads.admanager.v1.AudienceSegmentService", + "shortName": "AudienceSegmentService" }, - "shortName": "ListBandwidthGroups" + "shortName": "BatchPopulateAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListBandwidthGroupsRequest" + "type": "google.ads.admanager_v1.types.BatchPopulateAudienceSegmentsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3667,14 +3683,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.bandwidth_group_service.pagers.ListBandwidthGroupsPager", - "shortName": "list_bandwidth_groups" + "resultType": "google.ads.admanager_v1.types.BatchPopulateAudienceSegmentsResponse", + "shortName": "batch_populate_audience_segments" }, - "description": "Sample for ListBandwidthGroups", - "file": "admanager_v1_generated_bandwidth_group_service_list_bandwidth_groups_sync.py", + "description": "Sample for BatchPopulateAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_batch_populate_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BandwidthGroupService_ListBandwidthGroups_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_BatchPopulateAudienceSegments_sync", "segments": [ { "end": 52, @@ -3692,48 +3708,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_bandwidth_group_service_list_bandwidth_groups_sync.py" + "title": "admanager_v1_generated_audience_segment_service_batch_populate_audience_segments_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient", - "shortName": "BrowserLanguageServiceClient" + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", + "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient.get_browser_language", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.batch_reject_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.BrowserLanguageService.GetBrowserLanguage", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.BatchRejectAudienceSegments", "service": { - "fullName": "google.ads.admanager.v1.BrowserLanguageService", - "shortName": "BrowserLanguageService" + "fullName": "google.ads.admanager.v1.AudienceSegmentService", + "shortName": "AudienceSegmentService" }, - "shortName": "GetBrowserLanguage" + "shortName": "BatchRejectAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetBrowserLanguageRequest" + "type": "google.ads.admanager_v1.types.BatchRejectAudienceSegmentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3747,22 +3767,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BrowserLanguage", - "shortName": "get_browser_language" + "resultType": "google.ads.admanager_v1.types.BatchRejectAudienceSegmentsResponse", + "shortName": "batch_reject_audience_segments" }, - "description": "Sample for GetBrowserLanguage", - "file": "admanager_v1_generated_browser_language_service_get_browser_language_sync.py", + "description": "Sample for BatchRejectAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_batch_reject_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BrowserLanguageService_GetBrowserLanguage_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_BatchRejectAudienceSegments_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3772,46 +3792,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_browser_language_service_get_browser_language_sync.py" + "title": "admanager_v1_generated_audience_segment_service_batch_reject_audience_segments_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient", - "shortName": "BrowserLanguageServiceClient" + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", + "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient.list_browser_languages", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.get_audience_segment", "method": { - "fullName": "google.ads.admanager.v1.BrowserLanguageService.ListBrowserLanguages", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.GetAudienceSegment", "service": { - "fullName": "google.ads.admanager.v1.BrowserLanguageService", - "shortName": "BrowserLanguageService" + "fullName": "google.ads.admanager.v1.AudienceSegmentService", + "shortName": "AudienceSegmentService" }, - "shortName": "ListBrowserLanguages" + "shortName": "GetAudienceSegment" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListBrowserLanguagesRequest" + "type": "google.ads.admanager_v1.types.GetAudienceSegmentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3827,22 +3847,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.browser_language_service.pagers.ListBrowserLanguagesPager", - "shortName": "list_browser_languages" + "resultType": "google.ads.admanager_v1.types.AudienceSegment", + "shortName": "get_audience_segment" }, - "description": "Sample for ListBrowserLanguages", - "file": "admanager_v1_generated_browser_language_service_list_browser_languages_sync.py", + "description": "Sample for GetAudienceSegment", + "file": "admanager_v1_generated_audience_segment_service_get_audience_segment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BrowserLanguageService_ListBrowserLanguages_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_GetAudienceSegment_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -3862,36 +3882,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_browser_language_service_list_browser_languages_sync.py" + "title": "admanager_v1_generated_audience_segment_service_get_audience_segment_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BrowserServiceClient", - "shortName": "BrowserServiceClient" + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient", + "shortName": "AudienceSegmentServiceClient" }, - "fullName": "google.ads.admanager_v1.BrowserServiceClient.get_browser", + "fullName": "google.ads.admanager_v1.AudienceSegmentServiceClient.list_audience_segments", "method": { - "fullName": "google.ads.admanager.v1.BrowserService.GetBrowser", + "fullName": "google.ads.admanager.v1.AudienceSegmentService.ListAudienceSegments", "service": { - "fullName": "google.ads.admanager.v1.BrowserService", - "shortName": "BrowserService" + "fullName": "google.ads.admanager.v1.AudienceSegmentService", + "shortName": "AudienceSegmentService" }, - "shortName": "GetBrowser" + "shortName": "ListAudienceSegments" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetBrowserRequest" + "type": "google.ads.admanager_v1.types.ListAudienceSegmentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3907,22 +3927,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Browser", - "shortName": "get_browser" + "resultType": "google.ads.admanager_v1.services.audience_segment_service.pagers.ListAudienceSegmentsPager", + "shortName": "list_audience_segments" }, - "description": "Sample for GetBrowser", - "file": "admanager_v1_generated_browser_service_get_browser_sync.py", + "description": "Sample for ListAudienceSegments", + "file": "admanager_v1_generated_audience_segment_service_list_audience_segments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BrowserService_GetBrowser_sync", + "regionTag": "admanager_v1_generated_AudienceSegmentService_ListAudienceSegments_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3942,36 +3962,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_browser_service_get_browser_sync.py" + "title": "admanager_v1_generated_audience_segment_service_list_audience_segments_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.BrowserServiceClient", - "shortName": "BrowserServiceClient" + "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient", + "shortName": "BandwidthGroupServiceClient" }, - "fullName": "google.ads.admanager_v1.BrowserServiceClient.list_browsers", + "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient.get_bandwidth_group", "method": { - "fullName": "google.ads.admanager.v1.BrowserService.ListBrowsers", + "fullName": "google.ads.admanager.v1.BandwidthGroupService.GetBandwidthGroup", "service": { - "fullName": "google.ads.admanager.v1.BrowserService", - "shortName": "BrowserService" + "fullName": "google.ads.admanager.v1.BandwidthGroupService", + "shortName": "BandwidthGroupService" }, - "shortName": "ListBrowsers" + "shortName": "GetBandwidthGroup" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListBrowsersRequest" + "type": "google.ads.admanager_v1.types.GetBandwidthGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -3987,22 +4007,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.browser_service.pagers.ListBrowsersPager", - "shortName": "list_browsers" + "resultType": "google.ads.admanager_v1.types.BandwidthGroup", + "shortName": "get_bandwidth_group" }, - "description": "Sample for ListBrowsers", - "file": "admanager_v1_generated_browser_service_list_browsers_sync.py", + "description": "Sample for GetBandwidthGroup", + "file": "admanager_v1_generated_bandwidth_group_service_get_bandwidth_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_BrowserService_ListBrowsers_sync", + "regionTag": "admanager_v1_generated_BandwidthGroupService_GetBandwidthGroup_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -4022,42 +4042,38 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_browser_service_list_browsers_sync.py" + "title": "admanager_v1_generated_bandwidth_group_service_get_bandwidth_group_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", - "shortName": "CdnConfigServiceClient" + "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient", + "shortName": "BandwidthGroupServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_activate_cdn_configs", + "fullName": "google.ads.admanager_v1.BandwidthGroupServiceClient.list_bandwidth_groups", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.BatchActivateCdnConfigs", + "fullName": "google.ads.admanager.v1.BandwidthGroupService.ListBandwidthGroups", "service": { - "fullName": "google.ads.admanager.v1.CdnConfigService", - "shortName": "CdnConfigService" + "fullName": "google.ads.admanager.v1.BandwidthGroupService", + "shortName": "BandwidthGroupService" }, - "shortName": "BatchActivateCdnConfigs" + "shortName": "ListBandwidthGroups" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCdnConfigsRequest" + "type": "google.ads.admanager_v1.types.ListBandwidthGroupsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4071,14 +4087,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCdnConfigsResponse", - "shortName": "batch_activate_cdn_configs" + "resultType": "google.ads.admanager_v1.services.bandwidth_group_service.pagers.ListBandwidthGroupsPager", + "shortName": "list_bandwidth_groups" }, - "description": "Sample for BatchActivateCdnConfigs", - "file": "admanager_v1_generated_cdn_config_service_batch_activate_cdn_configs_sync.py", + "description": "Sample for ListBandwidthGroups", + "file": "admanager_v1_generated_bandwidth_group_service_list_bandwidth_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_BatchActivateCdnConfigs_sync", + "regionTag": "admanager_v1_generated_BandwidthGroupService_ListBandwidthGroups_sync", "segments": [ { "end": 52, @@ -4096,52 +4112,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_batch_activate_cdn_configs_sync.py" + "title": "admanager_v1_generated_bandwidth_group_service_list_bandwidth_groups_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", - "shortName": "CdnConfigServiceClient" + "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient", + "shortName": "BrowserLanguageServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_archive_cdn_configs", + "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient.get_browser_language", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.BatchArchiveCdnConfigs", + "fullName": "google.ads.admanager.v1.BrowserLanguageService.GetBrowserLanguage", "service": { - "fullName": "google.ads.admanager.v1.CdnConfigService", - "shortName": "CdnConfigService" + "fullName": "google.ads.admanager.v1.BrowserLanguageService", + "shortName": "BrowserLanguageService" }, - "shortName": "BatchArchiveCdnConfigs" + "shortName": "GetBrowserLanguage" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchArchiveCdnConfigsRequest" + "type": "google.ads.admanager_v1.types.GetBrowserLanguageRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4155,22 +4167,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchArchiveCdnConfigsResponse", - "shortName": "batch_archive_cdn_configs" + "resultType": "google.ads.admanager_v1.types.BrowserLanguage", + "shortName": "get_browser_language" }, - "description": "Sample for BatchArchiveCdnConfigs", - "file": "admanager_v1_generated_cdn_config_service_batch_archive_cdn_configs_sync.py", + "description": "Sample for GetBrowserLanguage", + "file": "admanager_v1_generated_browser_language_service_get_browser_language_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_BatchArchiveCdnConfigs_sync", + "regionTag": "admanager_v1_generated_BrowserLanguageService_GetBrowserLanguage_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -4180,52 +4192,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_batch_archive_cdn_configs_sync.py" + "title": "admanager_v1_generated_browser_language_service_get_browser_language_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", - "shortName": "CdnConfigServiceClient" + "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient", + "shortName": "BrowserLanguageServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_create_cdn_configs", + "fullName": "google.ads.admanager_v1.BrowserLanguageServiceClient.list_browser_languages", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.BatchCreateCdnConfigs", + "fullName": "google.ads.admanager.v1.BrowserLanguageService.ListBrowserLanguages", "service": { - "fullName": "google.ads.admanager.v1.CdnConfigService", - "shortName": "CdnConfigService" + "fullName": "google.ads.admanager.v1.BrowserLanguageService", + "shortName": "BrowserLanguageService" }, - "shortName": "BatchCreateCdnConfigs" + "shortName": "ListBrowserLanguages" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCdnConfigsRequest" + "type": "google.ads.admanager_v1.types.ListBrowserLanguagesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCdnConfigRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4239,22 +4247,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCdnConfigsResponse", - "shortName": "batch_create_cdn_configs" + "resultType": "google.ads.admanager_v1.services.browser_language_service.pagers.ListBrowserLanguagesPager", + "shortName": "list_browser_languages" }, - "description": "Sample for BatchCreateCdnConfigs", - "file": "admanager_v1_generated_cdn_config_service_batch_create_cdn_configs_sync.py", + "description": "Sample for ListBrowserLanguages", + "file": "admanager_v1_generated_browser_language_service_list_browser_languages_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_BatchCreateCdnConfigs_sync", + "regionTag": "admanager_v1_generated_BrowserLanguageService_ListBrowserLanguages_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4264,52 +4272,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_batch_create_cdn_configs_sync.py" + "title": "admanager_v1_generated_browser_language_service_list_browser_languages_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", - "shortName": "CdnConfigServiceClient" + "fullName": "google.ads.admanager_v1.BrowserServiceClient", + "shortName": "BrowserServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_update_cdn_configs", + "fullName": "google.ads.admanager_v1.BrowserServiceClient.get_browser", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.BatchUpdateCdnConfigs", + "fullName": "google.ads.admanager.v1.BrowserService.GetBrowser", "service": { - "fullName": "google.ads.admanager.v1.CdnConfigService", - "shortName": "CdnConfigService" + "fullName": "google.ads.admanager.v1.BrowserService", + "shortName": "BrowserService" }, - "shortName": "BatchUpdateCdnConfigs" + "shortName": "GetBrowser" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCdnConfigsRequest" + "type": "google.ads.admanager_v1.types.GetBrowserRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCdnConfigRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4323,14 +4327,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCdnConfigsResponse", - "shortName": "batch_update_cdn_configs" + "resultType": "google.ads.admanager_v1.types.Browser", + "shortName": "get_browser" }, - "description": "Sample for BatchUpdateCdnConfigs", - "file": "admanager_v1_generated_cdn_config_service_batch_update_cdn_configs_sync.py", + "description": "Sample for GetBrowser", + "file": "admanager_v1_generated_browser_service_get_browser_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_BatchUpdateCdnConfigs_sync", + "regionTag": "admanager_v1_generated_BrowserService_GetBrowser_sync", "segments": [ { "end": 51, @@ -4363,37 +4367,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_batch_update_cdn_configs_sync.py" + "title": "admanager_v1_generated_browser_service_get_browser_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", - "shortName": "CdnConfigServiceClient" + "fullName": "google.ads.admanager_v1.BrowserServiceClient", + "shortName": "BrowserServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.create_cdn_config", + "fullName": "google.ads.admanager_v1.BrowserServiceClient.list_browsers", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.CreateCdnConfig", + "fullName": "google.ads.admanager.v1.BrowserService.ListBrowsers", "service": { - "fullName": "google.ads.admanager.v1.CdnConfigService", - "shortName": "CdnConfigService" + "fullName": "google.ads.admanager.v1.BrowserService", + "shortName": "BrowserService" }, - "shortName": "CreateCdnConfig" + "shortName": "ListBrowsers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCdnConfigRequest" + "type": "google.ads.admanager_v1.types.ListBrowsersRequest" }, { "name": "parent", "type": "str" }, - { - "name": "cdn_config", - "type": "google.ads.admanager_v1.types.CdnConfig" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4407,22 +4407,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CdnConfig", - "shortName": "create_cdn_config" + "resultType": "google.ads.admanager_v1.services.browser_service.pagers.ListBrowsersPager", + "shortName": "list_browsers" }, - "description": "Sample for CreateCdnConfig", - "file": "admanager_v1_generated_cdn_config_service_create_cdn_config_sync.py", + "description": "Sample for ListBrowsers", + "file": "admanager_v1_generated_browser_service_list_browsers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_CreateCdnConfig_sync", + "regionTag": "admanager_v1_generated_BrowserService_ListBrowsers_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4442,12 +4442,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_create_cdn_config_sync.py" + "title": "admanager_v1_generated_browser_service_list_browsers_sync.py" }, { "canonical": true, @@ -4456,24 +4456,28 @@ "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.get_cdn_config", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_activate_cdn_configs", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.GetCdnConfig", + "fullName": "google.ads.admanager.v1.CdnConfigService.BatchActivateCdnConfigs", "service": { "fullName": "google.ads.admanager.v1.CdnConfigService", "shortName": "CdnConfigService" }, - "shortName": "GetCdnConfig" + "shortName": "BatchActivateCdnConfigs" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCdnConfigRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCdnConfigsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4487,22 +4491,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CdnConfig", - "shortName": "get_cdn_config" + "resultType": "google.ads.admanager_v1.types.BatchActivateCdnConfigsResponse", + "shortName": "batch_activate_cdn_configs" }, - "description": "Sample for GetCdnConfig", - "file": "admanager_v1_generated_cdn_config_service_get_cdn_config_sync.py", + "description": "Sample for BatchActivateCdnConfigs", + "file": "admanager_v1_generated_cdn_config_service_batch_activate_cdn_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_GetCdnConfig_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_BatchActivateCdnConfigs_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4512,22 +4516,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_get_cdn_config_sync.py" + "title": "admanager_v1_generated_cdn_config_service_batch_activate_cdn_configs_sync.py" }, { "canonical": true, @@ -4536,24 +4540,28 @@ "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.list_cdn_configs", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_archive_cdn_configs", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.ListCdnConfigs", + "fullName": "google.ads.admanager.v1.CdnConfigService.BatchArchiveCdnConfigs", "service": { "fullName": "google.ads.admanager.v1.CdnConfigService", "shortName": "CdnConfigService" }, - "shortName": "ListCdnConfigs" + "shortName": "BatchArchiveCdnConfigs" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCdnConfigsRequest" + "type": "google.ads.admanager_v1.types.BatchArchiveCdnConfigsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4567,14 +4575,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.cdn_config_service.pagers.ListCdnConfigsPager", - "shortName": "list_cdn_configs" + "resultType": "google.ads.admanager_v1.types.BatchArchiveCdnConfigsResponse", + "shortName": "batch_archive_cdn_configs" }, - "description": "Sample for ListCdnConfigs", - "file": "admanager_v1_generated_cdn_config_service_list_cdn_configs_sync.py", + "description": "Sample for BatchArchiveCdnConfigs", + "file": "admanager_v1_generated_cdn_config_service_batch_archive_cdn_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_ListCdnConfigs_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_BatchArchiveCdnConfigs_sync", "segments": [ { "end": 52, @@ -4592,22 +4600,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_list_cdn_configs_sync.py" + "title": "admanager_v1_generated_cdn_config_service_batch_archive_cdn_configs_sync.py" }, { "canonical": true, @@ -4616,27 +4624,27 @@ "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.update_cdn_config", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_create_cdn_configs", "method": { - "fullName": "google.ads.admanager.v1.CdnConfigService.UpdateCdnConfig", + "fullName": "google.ads.admanager.v1.CdnConfigService.BatchCreateCdnConfigs", "service": { "fullName": "google.ads.admanager.v1.CdnConfigService", "shortName": "CdnConfigService" }, - "shortName": "UpdateCdnConfig" + "shortName": "BatchCreateCdnConfigs" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCdnConfigRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCdnConfigsRequest" }, { - "name": "cdn_config", - "type": "google.ads.admanager_v1.types.CdnConfig" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCdnConfigRequest]" }, { "name": "retry", @@ -4651,22 +4659,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CdnConfig", - "shortName": "update_cdn_config" + "resultType": "google.ads.admanager_v1.types.BatchCreateCdnConfigsResponse", + "shortName": "batch_create_cdn_configs" }, - "description": "Sample for UpdateCdnConfig", - "file": "admanager_v1_generated_cdn_config_service_update_cdn_config_sync.py", + "description": "Sample for BatchCreateCdnConfigs", + "file": "admanager_v1_generated_cdn_config_service_batch_create_cdn_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CdnConfigService_UpdateCdnConfig_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_BatchCreateCdnConfigs_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4676,43 +4684,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cdn_config_service_update_cdn_config_sync.py" + "title": "admanager_v1_generated_cdn_config_service_batch_create_cdn_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", - "shortName": "ChildPublisherServiceClient" + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", + "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_create_child_publishers", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.batch_update_cdn_configs", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchCreateChildPublishers", + "fullName": "google.ads.admanager.v1.CdnConfigService.BatchUpdateCdnConfigs", "service": { - "fullName": "google.ads.admanager.v1.ChildPublisherService", - "shortName": "ChildPublisherService" + "fullName": "google.ads.admanager.v1.CdnConfigService", + "shortName": "CdnConfigService" }, - "shortName": "BatchCreateChildPublishers" + "shortName": "BatchUpdateCdnConfigs" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateChildPublishersRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCdnConfigsRequest" }, { "name": "parent", @@ -4720,7 +4728,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateChildPublisherRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCdnConfigRequest]" }, { "name": "retry", @@ -4735,22 +4743,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateChildPublishersResponse", - "shortName": "batch_create_child_publishers" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCdnConfigsResponse", + "shortName": "batch_update_cdn_configs" }, - "description": "Sample for BatchCreateChildPublishers", - "file": "admanager_v1_generated_child_publisher_service_batch_create_child_publishers_sync.py", + "description": "Sample for BatchUpdateCdnConfigs", + "file": "admanager_v1_generated_cdn_config_service_batch_update_cdn_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_BatchCreateChildPublishers_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_BatchUpdateCdnConfigs_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -4760,51 +4768,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_batch_create_child_publishers_sync.py" + "title": "admanager_v1_generated_cdn_config_service_batch_update_cdn_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", - "shortName": "ChildPublisherServiceClient" + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", + "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_update_child_publishers", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.create_cdn_config", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchUpdateChildPublishers", + "fullName": "google.ads.admanager.v1.CdnConfigService.CreateCdnConfig", "service": { - "fullName": "google.ads.admanager.v1.ChildPublisherService", - "shortName": "ChildPublisherService" + "fullName": "google.ads.admanager.v1.CdnConfigService", + "shortName": "CdnConfigService" }, - "shortName": "BatchUpdateChildPublishers" + "shortName": "CreateCdnConfig" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateChildPublishersRequest" + "type": "google.ads.admanager_v1.types.CreateCdnConfigRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateChildPublisherRequest]" + "name": "cdn_config", + "type": "google.ads.admanager_v1.types.CdnConfig" }, { "name": "retry", @@ -4819,14 +4827,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateChildPublishersResponse", - "shortName": "batch_update_child_publishers" + "resultType": "google.ads.admanager_v1.types.CdnConfig", + "shortName": "create_cdn_config" }, - "description": "Sample for BatchUpdateChildPublishers", - "file": "admanager_v1_generated_child_publisher_service_batch_update_child_publishers_sync.py", + "description": "Sample for CreateCdnConfig", + "file": "admanager_v1_generated_cdn_config_service_create_cdn_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_BatchUpdateChildPublishers_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_CreateCdnConfig_sync", "segments": [ { "end": 51, @@ -4859,37 +4867,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_batch_update_child_publishers_sync.py" + "title": "admanager_v1_generated_cdn_config_service_create_cdn_config_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", - "shortName": "ChildPublisherServiceClient" + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", + "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.create_child_publisher", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.get_cdn_config", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.CreateChildPublisher", + "fullName": "google.ads.admanager.v1.CdnConfigService.GetCdnConfig", "service": { - "fullName": "google.ads.admanager.v1.ChildPublisherService", - "shortName": "ChildPublisherService" + "fullName": "google.ads.admanager.v1.CdnConfigService", + "shortName": "CdnConfigService" }, - "shortName": "CreateChildPublisher" + "shortName": "GetCdnConfig" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateChildPublisherRequest" + "type": "google.ads.admanager_v1.types.GetCdnConfigRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "child_publisher", - "type": "google.ads.admanager_v1.types.ChildPublisher" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -4903,14 +4907,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.ChildPublisher", - "shortName": "create_child_publisher" + "resultType": "google.ads.admanager_v1.types.CdnConfig", + "shortName": "get_cdn_config" }, - "description": "Sample for CreateChildPublisher", - "file": "admanager_v1_generated_child_publisher_service_create_child_publisher_sync.py", + "description": "Sample for GetCdnConfig", + "file": "admanager_v1_generated_cdn_config_service_get_cdn_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_CreateChildPublisher_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_GetCdnConfig_sync", "segments": [ { "end": 51, @@ -4943,31 +4947,31 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_create_child_publisher_sync.py" + "title": "admanager_v1_generated_cdn_config_service_get_cdn_config_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", - "shortName": "ChildPublisherServiceClient" + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", + "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.get_child_publisher", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.list_cdn_configs", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.GetChildPublisher", + "fullName": "google.ads.admanager.v1.CdnConfigService.ListCdnConfigs", "service": { - "fullName": "google.ads.admanager.v1.ChildPublisherService", - "shortName": "ChildPublisherService" + "fullName": "google.ads.admanager.v1.CdnConfigService", + "shortName": "CdnConfigService" }, - "shortName": "GetChildPublisher" + "shortName": "ListCdnConfigs" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetChildPublisherRequest" + "type": "google.ads.admanager_v1.types.ListCdnConfigsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4983,22 +4987,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.ChildPublisher", - "shortName": "get_child_publisher" + "resultType": "google.ads.admanager_v1.services.cdn_config_service.pagers.ListCdnConfigsPager", + "shortName": "list_cdn_configs" }, - "description": "Sample for GetChildPublisher", - "file": "admanager_v1_generated_child_publisher_service_get_child_publisher_sync.py", + "description": "Sample for ListCdnConfigs", + "file": "admanager_v1_generated_cdn_config_service_list_cdn_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_GetChildPublisher_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_ListCdnConfigs_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -5018,37 +5022,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_get_child_publisher_sync.py" + "title": "admanager_v1_generated_cdn_config_service_list_cdn_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", - "shortName": "ChildPublisherServiceClient" + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient", + "shortName": "CdnConfigServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.list_child_publishers", + "fullName": "google.ads.admanager_v1.CdnConfigServiceClient.update_cdn_config", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.ListChildPublishers", + "fullName": "google.ads.admanager.v1.CdnConfigService.UpdateCdnConfig", "service": { - "fullName": "google.ads.admanager.v1.ChildPublisherService", - "shortName": "ChildPublisherService" + "fullName": "google.ads.admanager.v1.CdnConfigService", + "shortName": "CdnConfigService" }, - "shortName": "ListChildPublishers" + "shortName": "UpdateCdnConfig" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListChildPublishersRequest" + "type": "google.ads.admanager_v1.types.UpdateCdnConfigRequest" }, { - "name": "parent", - "type": "str" + "name": "cdn_config", + "type": "google.ads.admanager_v1.types.CdnConfig" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5063,22 +5071,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.child_publisher_service.pagers.ListChildPublishersPager", - "shortName": "list_child_publishers" + "resultType": "google.ads.admanager_v1.types.CdnConfig", + "shortName": "update_cdn_config" }, - "description": "Sample for ListChildPublishers", - "file": "admanager_v1_generated_child_publisher_service_list_child_publishers_sync.py", + "description": "Sample for UpdateCdnConfig", + "file": "admanager_v1_generated_cdn_config_service_update_cdn_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_ListChildPublishers_sync", + "regionTag": "admanager_v1_generated_CdnConfigService_UpdateCdnConfig_sync", "segments": [ { - "end": 52, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 50, "start": 27, "type": "SHORT" }, @@ -5088,22 +5096,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_list_child_publishers_sync.py" + "title": "admanager_v1_generated_cdn_config_service_update_cdn_config_sync.py" }, { "canonical": true, @@ -5112,27 +5120,27 @@ "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.update_child_publisher", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_create_child_publishers", "method": { - "fullName": "google.ads.admanager.v1.ChildPublisherService.UpdateChildPublisher", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchCreateChildPublishers", "service": { "fullName": "google.ads.admanager.v1.ChildPublisherService", "shortName": "ChildPublisherService" }, - "shortName": "UpdateChildPublisher" + "shortName": "BatchCreateChildPublishers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateChildPublisherRequest" + "type": "google.ads.admanager_v1.types.BatchCreateChildPublishersRequest" }, { - "name": "child_publisher", - "type": "google.ads.admanager_v1.types.ChildPublisher" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateChildPublisherRequest]" }, { "name": "retry", @@ -5147,22 +5155,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.ChildPublisher", - "shortName": "update_child_publisher" + "resultType": "google.ads.admanager_v1.types.BatchCreateChildPublishersResponse", + "shortName": "batch_create_child_publishers" }, - "description": "Sample for UpdateChildPublisher", - "file": "admanager_v1_generated_child_publisher_service_update_child_publisher_sync.py", + "description": "Sample for BatchCreateChildPublishers", + "file": "admanager_v1_generated_child_publisher_service_batch_create_child_publishers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ChildPublisherService_UpdateChildPublisher_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchCreateChildPublishers_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5172,43 +5180,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_child_publisher_service_update_child_publisher_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_create_child_publishers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", - "shortName": "CmsMetadataKeyServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.batch_activate_cms_metadata_keys", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_reject_child_publishers", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.BatchActivateCmsMetadataKeys", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchRejectChildPublishers", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", - "shortName": "CmsMetadataKeyService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "BatchActivateCmsMetadataKeys" + "shortName": "BatchRejectChildPublishers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCmsMetadataKeysRequest" + "type": "google.ads.admanager_v1.types.BatchRejectChildPublishersRequest" }, { "name": "parent", @@ -5231,14 +5239,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCmsMetadataKeysResponse", - "shortName": "batch_activate_cms_metadata_keys" + "resultType": "google.ads.admanager_v1.types.BatchRejectChildPublishersResponse", + "shortName": "batch_reject_child_publishers" }, - "description": "Sample for BatchActivateCmsMetadataKeys", - "file": "admanager_v1_generated_cms_metadata_key_service_batch_activate_cms_metadata_keys_sync.py", + "description": "Sample for BatchRejectChildPublishers", + "file": "admanager_v1_generated_child_publisher_service_batch_reject_child_publishers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataKeyService_BatchActivateCmsMetadataKeys_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchRejectChildPublishers_sync", "segments": [ { "end": 52, @@ -5271,36 +5279,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_key_service_batch_activate_cms_metadata_keys_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_reject_child_publishers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", - "shortName": "CmsMetadataKeyServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.batch_deactivate_cms_metadata_keys", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_renegotiate_child_publisher_agreements", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.BatchDeactivateCmsMetadataKeys", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchRenegotiateChildPublisherAgreements", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", - "shortName": "CmsMetadataKeyService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "BatchDeactivateCmsMetadataKeys" + "shortName": "BatchRenegotiateChildPublisherAgreements" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataKeysRequest" + "type": "google.ads.admanager_v1.types.BatchRenegotiateChildPublisherAgreementsRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.RenegotiateChildPublisherAgreementRequest]" }, { "name": "retry", @@ -5315,22 +5323,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataKeysResponse", - "shortName": "batch_deactivate_cms_metadata_keys" + "resultType": "google.ads.admanager_v1.types.BatchRenegotiateChildPublisherAgreementsResponse", + "shortName": "batch_renegotiate_child_publisher_agreements" }, - "description": "Sample for BatchDeactivateCmsMetadataKeys", - "file": "admanager_v1_generated_cms_metadata_key_service_batch_deactivate_cms_metadata_keys_sync.py", + "description": "Sample for BatchRenegotiateChildPublisherAgreements", + "file": "admanager_v1_generated_child_publisher_service_batch_renegotiate_child_publisher_agreements_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataKeyService_BatchDeactivateCmsMetadataKeys_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchRenegotiateChildPublisherAgreements_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5340,48 +5348,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_key_service_batch_deactivate_cms_metadata_keys_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_renegotiate_child_publisher_agreements_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", - "shortName": "CmsMetadataKeyServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.get_cms_metadata_key", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_resend_child_publisher_invitation_emails", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.GetCmsMetadataKey", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchResendChildPublisherInvitationEmails", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", - "shortName": "CmsMetadataKeyService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "GetCmsMetadataKey" + "shortName": "BatchResendChildPublisherInvitationEmails" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCmsMetadataKeyRequest" + "type": "google.ads.admanager_v1.types.BatchResendChildPublisherInvitationEmailsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -5395,22 +5407,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CmsMetadataKey", - "shortName": "get_cms_metadata_key" + "resultType": "google.ads.admanager_v1.types.BatchResendChildPublisherInvitationEmailsResponse", + "shortName": "batch_resend_child_publisher_invitation_emails" }, - "description": "Sample for GetCmsMetadataKey", - "file": "admanager_v1_generated_cms_metadata_key_service_get_cms_metadata_key_sync.py", + "description": "Sample for BatchResendChildPublisherInvitationEmails", + "file": "admanager_v1_generated_child_publisher_service_batch_resend_child_publisher_invitation_emails_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataKeyService_GetCmsMetadataKey_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchResendChildPublisherInvitationEmails_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -5420,48 +5432,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_key_service_get_cms_metadata_key_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_resend_child_publisher_invitation_emails_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", - "shortName": "CmsMetadataKeyServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.list_cms_metadata_keys", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_update_child_publishers", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.ListCmsMetadataKeys", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchUpdateChildPublishers", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", - "shortName": "CmsMetadataKeyService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "ListCmsMetadataKeys" + "shortName": "BatchUpdateChildPublishers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCmsMetadataKeysRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateChildPublishersRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateChildPublisherRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -5475,22 +5491,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.cms_metadata_key_service.pagers.ListCmsMetadataKeysPager", - "shortName": "list_cms_metadata_keys" + "resultType": "google.ads.admanager_v1.types.BatchUpdateChildPublishersResponse", + "shortName": "batch_update_child_publishers" }, - "description": "Sample for ListCmsMetadataKeys", - "file": "admanager_v1_generated_cms_metadata_key_service_list_cms_metadata_keys_sync.py", + "description": "Sample for BatchUpdateChildPublishers", + "file": "admanager_v1_generated_child_publisher_service_batch_update_child_publishers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataKeyService_ListCmsMetadataKeys_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchUpdateChildPublishers_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5510,33 +5526,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_key_service_list_cms_metadata_keys_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_update_child_publishers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", - "shortName": "CmsMetadataValueServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.batch_activate_cms_metadata_values", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.batch_withdraw_child_publishers", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService.BatchActivateCmsMetadataValues", + "fullName": "google.ads.admanager.v1.ChildPublisherService.BatchWithdrawChildPublishers", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService", - "shortName": "CmsMetadataValueService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "BatchActivateCmsMetadataValues" + "shortName": "BatchWithdrawChildPublishers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCmsMetadataValuesRequest" + "type": "google.ads.admanager_v1.types.BatchWithdrawChildPublishersRequest" }, { "name": "parent", @@ -5559,14 +5575,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCmsMetadataValuesResponse", - "shortName": "batch_activate_cms_metadata_values" + "resultType": "google.ads.admanager_v1.types.BatchWithdrawChildPublishersResponse", + "shortName": "batch_withdraw_child_publishers" }, - "description": "Sample for BatchActivateCmsMetadataValues", - "file": "admanager_v1_generated_cms_metadata_value_service_batch_activate_cms_metadata_values_sync.py", + "description": "Sample for BatchWithdrawChildPublishers", + "file": "admanager_v1_generated_child_publisher_service_batch_withdraw_child_publishers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataValueService_BatchActivateCmsMetadataValues_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_BatchWithdrawChildPublishers_sync", "segments": [ { "end": 52, @@ -5599,36 +5615,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_value_service_batch_activate_cms_metadata_values_sync.py" + "title": "admanager_v1_generated_child_publisher_service_batch_withdraw_child_publishers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", - "shortName": "CmsMetadataValueServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.batch_deactivate_cms_metadata_values", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.create_child_publisher", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService.BatchDeactivateCmsMetadataValues", + "fullName": "google.ads.admanager.v1.ChildPublisherService.CreateChildPublisher", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService", - "shortName": "CmsMetadataValueService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "BatchDeactivateCmsMetadataValues" + "shortName": "CreateChildPublisher" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataValuesRequest" + "type": "google.ads.admanager_v1.types.CreateChildPublisherRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "child_publisher", + "type": "google.ads.admanager_v1.types.ChildPublisher" }, { "name": "retry", @@ -5643,22 +5659,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataValuesResponse", - "shortName": "batch_deactivate_cms_metadata_values" + "resultType": "google.ads.admanager_v1.types.ChildPublisher", + "shortName": "create_child_publisher" }, - "description": "Sample for BatchDeactivateCmsMetadataValues", - "file": "admanager_v1_generated_cms_metadata_value_service_batch_deactivate_cms_metadata_values_sync.py", + "description": "Sample for CreateChildPublisher", + "file": "admanager_v1_generated_child_publisher_service_create_child_publisher_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataValueService_BatchDeactivateCmsMetadataValues_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_CreateChildPublisher_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -5668,43 +5684,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_value_service_batch_deactivate_cms_metadata_values_sync.py" + "title": "admanager_v1_generated_child_publisher_service_create_child_publisher_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", - "shortName": "CmsMetadataValueServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.get_cms_metadata_value", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.get_child_publisher", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService.GetCmsMetadataValue", + "fullName": "google.ads.admanager.v1.ChildPublisherService.GetChildPublisher", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService", - "shortName": "CmsMetadataValueService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "GetCmsMetadataValue" + "shortName": "GetChildPublisher" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCmsMetadataValueRequest" + "type": "google.ads.admanager_v1.types.GetChildPublisherRequest" }, { "name": "name", @@ -5723,14 +5739,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CmsMetadataValue", - "shortName": "get_cms_metadata_value" + "resultType": "google.ads.admanager_v1.types.ChildPublisher", + "shortName": "get_child_publisher" }, - "description": "Sample for GetCmsMetadataValue", - "file": "admanager_v1_generated_cms_metadata_value_service_get_cms_metadata_value_sync.py", + "description": "Sample for GetChildPublisher", + "file": "admanager_v1_generated_child_publisher_service_get_child_publisher_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataValueService_GetCmsMetadataValue_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_GetChildPublisher_sync", "segments": [ { "end": 51, @@ -5763,28 +5779,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_value_service_get_cms_metadata_value_sync.py" + "title": "admanager_v1_generated_child_publisher_service_get_child_publisher_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", - "shortName": "CmsMetadataValueServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.list_cms_metadata_values", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.list_child_publishers", "method": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService.ListCmsMetadataValues", + "fullName": "google.ads.admanager.v1.ChildPublisherService.ListChildPublishers", "service": { - "fullName": "google.ads.admanager.v1.CmsMetadataValueService", - "shortName": "CmsMetadataValueService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "ListCmsMetadataValues" + "shortName": "ListChildPublishers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCmsMetadataValuesRequest" + "type": "google.ads.admanager_v1.types.ListChildPublishersRequest" }, { "name": "parent", @@ -5803,14 +5819,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.cms_metadata_value_service.pagers.ListCmsMetadataValuesPager", - "shortName": "list_cms_metadata_values" + "resultType": "google.ads.admanager_v1.services.child_publisher_service.pagers.ListChildPublishersPager", + "shortName": "list_child_publishers" }, - "description": "Sample for ListCmsMetadataValues", - "file": "admanager_v1_generated_cms_metadata_value_service_list_cms_metadata_values_sync.py", + "description": "Sample for ListChildPublishers", + "file": "admanager_v1_generated_child_publisher_service_list_child_publishers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CmsMetadataValueService_ListCmsMetadataValues_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_ListChildPublishers_sync", "segments": [ { "end": 52, @@ -5843,36 +5859,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_cms_metadata_value_service_list_cms_metadata_values_sync.py" + "title": "admanager_v1_generated_child_publisher_service_list_child_publishers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient", + "shortName": "ChildPublisherServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.batch_create_companies", + "fullName": "google.ads.admanager_v1.ChildPublisherServiceClient.update_child_publisher", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.BatchCreateCompanies", + "fullName": "google.ads.admanager.v1.ChildPublisherService.UpdateChildPublisher", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.ChildPublisherService", + "shortName": "ChildPublisherService" }, - "shortName": "BatchCreateCompanies" + "shortName": "UpdateChildPublisher" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCompaniesRequest" + "type": "google.ads.admanager_v1.types.UpdateChildPublisherRequest" }, { - "name": "parent", - "type": "str" + "name": "child_publisher", + "type": "google.ads.admanager_v1.types.ChildPublisher" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCompanyRequest]" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5887,22 +5903,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCompaniesResponse", - "shortName": "batch_create_companies" + "resultType": "google.ads.admanager_v1.types.ChildPublisher", + "shortName": "update_child_publisher" }, - "description": "Sample for BatchCreateCompanies", - "file": "admanager_v1_generated_company_service_batch_create_companies_sync.py", + "description": "Sample for UpdateChildPublisher", + "file": "admanager_v1_generated_child_publisher_service_update_child_publisher_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_BatchCreateCompanies_sync", + "regionTag": "admanager_v1_generated_ChildPublisherService_UpdateChildPublisher_sync", "segments": [ { - "end": 55, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 50, "start": 27, "type": "SHORT" }, @@ -5912,51 +5928,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_batch_create_companies_sync.py" + "title": "admanager_v1_generated_child_publisher_service_update_child_publisher_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", + "shortName": "CmsMetadataKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.batch_update_companies", + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.batch_activate_cms_metadata_keys", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.BatchUpdateCompanies", + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.BatchActivateCmsMetadataKeys", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", + "shortName": "CmsMetadataKeyService" }, - "shortName": "BatchUpdateCompanies" + "shortName": "BatchActivateCmsMetadataKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCompaniesRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCmsMetadataKeysRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCompanyRequest]" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -5971,22 +5987,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCompaniesResponse", - "shortName": "batch_update_companies" + "resultType": "google.ads.admanager_v1.types.BatchActivateCmsMetadataKeysResponse", + "shortName": "batch_activate_cms_metadata_keys" }, - "description": "Sample for BatchUpdateCompanies", - "file": "admanager_v1_generated_company_service_batch_update_companies_sync.py", + "description": "Sample for BatchActivateCmsMetadataKeys", + "file": "admanager_v1_generated_cms_metadata_key_service_batch_activate_cms_metadata_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_BatchUpdateCompanies_sync", + "regionTag": "admanager_v1_generated_CmsMetadataKeyService_BatchActivateCmsMetadataKeys_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -5996,51 +6012,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_batch_update_companies_sync.py" + "title": "admanager_v1_generated_cms_metadata_key_service_batch_activate_cms_metadata_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", + "shortName": "CmsMetadataKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.create_company", + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.batch_deactivate_cms_metadata_keys", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.CreateCompany", + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.BatchDeactivateCmsMetadataKeys", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", + "shortName": "CmsMetadataKeyService" }, - "shortName": "CreateCompany" + "shortName": "BatchDeactivateCmsMetadataKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCompanyRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataKeysRequest" }, { "name": "parent", "type": "str" }, { - "name": "company", - "type": "google.ads.admanager_v1.types.Company" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -6055,22 +6071,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Company", - "shortName": "create_company" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataKeysResponse", + "shortName": "batch_deactivate_cms_metadata_keys" }, - "description": "Sample for CreateCompany", - "file": "admanager_v1_generated_company_service_create_company_sync.py", + "description": "Sample for BatchDeactivateCmsMetadataKeys", + "file": "admanager_v1_generated_cms_metadata_key_service_batch_deactivate_cms_metadata_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_CreateCompany_sync", + "regionTag": "admanager_v1_generated_CmsMetadataKeyService_BatchDeactivateCmsMetadataKeys_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6080,43 +6096,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_create_company_sync.py" + "title": "admanager_v1_generated_cms_metadata_key_service_batch_deactivate_cms_metadata_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", + "shortName": "CmsMetadataKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.get_company", + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.get_cms_metadata_key", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.GetCompany", + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.GetCmsMetadataKey", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", + "shortName": "CmsMetadataKeyService" }, - "shortName": "GetCompany" + "shortName": "GetCmsMetadataKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCompanyRequest" + "type": "google.ads.admanager_v1.types.GetCmsMetadataKeyRequest" }, { "name": "name", @@ -6135,14 +6151,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Company", - "shortName": "get_company" + "resultType": "google.ads.admanager_v1.types.CmsMetadataKey", + "shortName": "get_cms_metadata_key" }, - "description": "Sample for GetCompany", - "file": "admanager_v1_generated_company_service_get_company_sync.py", + "description": "Sample for GetCmsMetadataKey", + "file": "admanager_v1_generated_cms_metadata_key_service_get_cms_metadata_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_GetCompany_sync", + "regionTag": "admanager_v1_generated_CmsMetadataKeyService_GetCmsMetadataKey_sync", "segments": [ { "end": 51, @@ -6175,28 +6191,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_get_company_sync.py" + "title": "admanager_v1_generated_cms_metadata_key_service_get_cms_metadata_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient", + "shortName": "CmsMetadataKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.list_companies", + "fullName": "google.ads.admanager_v1.CmsMetadataKeyServiceClient.list_cms_metadata_keys", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.ListCompanies", + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService.ListCmsMetadataKeys", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.CmsMetadataKeyService", + "shortName": "CmsMetadataKeyService" }, - "shortName": "ListCompanies" + "shortName": "ListCmsMetadataKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCompaniesRequest" + "type": "google.ads.admanager_v1.types.ListCmsMetadataKeysRequest" }, { "name": "parent", @@ -6215,14 +6231,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.company_service.pagers.ListCompaniesPager", - "shortName": "list_companies" + "resultType": "google.ads.admanager_v1.services.cms_metadata_key_service.pagers.ListCmsMetadataKeysPager", + "shortName": "list_cms_metadata_keys" }, - "description": "Sample for ListCompanies", - "file": "admanager_v1_generated_company_service_list_companies_sync.py", + "description": "Sample for ListCmsMetadataKeys", + "file": "admanager_v1_generated_cms_metadata_key_service_list_cms_metadata_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_ListCompanies_sync", + "regionTag": "admanager_v1_generated_CmsMetadataKeyService_ListCmsMetadataKeys_sync", "segments": [ { "end": 52, @@ -6255,36 +6271,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_list_companies_sync.py" + "title": "admanager_v1_generated_cms_metadata_key_service_list_cms_metadata_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CompanyServiceClient", - "shortName": "CompanyServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", + "shortName": "CmsMetadataValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CompanyServiceClient.update_company", + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.batch_activate_cms_metadata_values", "method": { - "fullName": "google.ads.admanager.v1.CompanyService.UpdateCompany", + "fullName": "google.ads.admanager.v1.CmsMetadataValueService.BatchActivateCmsMetadataValues", "service": { - "fullName": "google.ads.admanager.v1.CompanyService", - "shortName": "CompanyService" + "fullName": "google.ads.admanager.v1.CmsMetadataValueService", + "shortName": "CmsMetadataValueService" }, - "shortName": "UpdateCompany" + "shortName": "BatchActivateCmsMetadataValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCompanyRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCmsMetadataValuesRequest" }, { - "name": "company", - "type": "google.ads.admanager_v1.types.Company" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -6299,22 +6315,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Company", - "shortName": "update_company" + "resultType": "google.ads.admanager_v1.types.BatchActivateCmsMetadataValuesResponse", + "shortName": "batch_activate_cms_metadata_values" }, - "description": "Sample for UpdateCompany", - "file": "admanager_v1_generated_company_service_update_company_sync.py", + "description": "Sample for BatchActivateCmsMetadataValues", + "file": "admanager_v1_generated_cms_metadata_value_service_batch_activate_cms_metadata_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CompanyService_UpdateCompany_sync", + "regionTag": "admanager_v1_generated_CmsMetadataValueService_BatchActivateCmsMetadataValues_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6324,51 +6340,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_company_service_update_company_sync.py" + "title": "admanager_v1_generated_cms_metadata_value_service_batch_activate_cms_metadata_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", + "shortName": "CmsMetadataValueServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.batch_create_contacts", + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.batch_deactivate_cms_metadata_values", "method": { - "fullName": "google.ads.admanager.v1.ContactService.BatchCreateContacts", + "fullName": "google.ads.admanager.v1.CmsMetadataValueService.BatchDeactivateCmsMetadataValues", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" + "fullName": "google.ads.admanager.v1.CmsMetadataValueService", + "shortName": "CmsMetadataValueService" }, - "shortName": "BatchCreateContacts" + "shortName": "BatchDeactivateCmsMetadataValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateContactsRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataValuesRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateContactRequest]" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -6383,22 +6399,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateContactsResponse", - "shortName": "batch_create_contacts" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCmsMetadataValuesResponse", + "shortName": "batch_deactivate_cms_metadata_values" }, - "description": "Sample for BatchCreateContacts", - "file": "admanager_v1_generated_contact_service_batch_create_contacts_sync.py", + "description": "Sample for BatchDeactivateCmsMetadataValues", + "file": "admanager_v1_generated_cms_metadata_value_service_batch_deactivate_cms_metadata_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_BatchCreateContacts_sync", + "regionTag": "admanager_v1_generated_CmsMetadataValueService_BatchDeactivateCmsMetadataValues_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6408,52 +6424,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_batch_create_contacts_sync.py" + "title": "admanager_v1_generated_cms_metadata_value_service_batch_deactivate_cms_metadata_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", + "shortName": "CmsMetadataValueServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.batch_update_contacts", + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.get_cms_metadata_value", "method": { - "fullName": "google.ads.admanager.v1.ContactService.BatchUpdateContacts", + "fullName": "google.ads.admanager.v1.CmsMetadataValueService.GetCmsMetadataValue", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" + "fullName": "google.ads.admanager.v1.CmsMetadataValueService", + "shortName": "CmsMetadataValueService" }, - "shortName": "BatchUpdateContacts" + "shortName": "GetCmsMetadataValue" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateContactsRequest" + "type": "google.ads.admanager_v1.types.GetCmsMetadataValueRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateContactRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6467,14 +6479,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateContactsResponse", - "shortName": "batch_update_contacts" + "resultType": "google.ads.admanager_v1.types.CmsMetadataValue", + "shortName": "get_cms_metadata_value" }, - "description": "Sample for BatchUpdateContacts", - "file": "admanager_v1_generated_contact_service_batch_update_contacts_sync.py", + "description": "Sample for GetCmsMetadataValue", + "file": "admanager_v1_generated_cms_metadata_value_service_get_cms_metadata_value_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_BatchUpdateContacts_sync", + "regionTag": "admanager_v1_generated_CmsMetadataValueService_GetCmsMetadataValue_sync", "segments": [ { "end": 51, @@ -6507,37 +6519,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_batch_update_contacts_sync.py" + "title": "admanager_v1_generated_cms_metadata_value_service_get_cms_metadata_value_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient", + "shortName": "CmsMetadataValueServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.create_contact", + "fullName": "google.ads.admanager_v1.CmsMetadataValueServiceClient.list_cms_metadata_values", "method": { - "fullName": "google.ads.admanager.v1.ContactService.CreateContact", + "fullName": "google.ads.admanager.v1.CmsMetadataValueService.ListCmsMetadataValues", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" + "fullName": "google.ads.admanager.v1.CmsMetadataValueService", + "shortName": "CmsMetadataValueService" }, - "shortName": "CreateContact" + "shortName": "ListCmsMetadataValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateContactRequest" + "type": "google.ads.admanager_v1.types.ListCmsMetadataValuesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "contact", - "type": "google.ads.admanager_v1.types.Contact" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6551,22 +6559,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Contact", - "shortName": "create_contact" + "resultType": "google.ads.admanager_v1.services.cms_metadata_value_service.pagers.ListCmsMetadataValuesPager", + "shortName": "list_cms_metadata_values" }, - "description": "Sample for CreateContact", - "file": "admanager_v1_generated_contact_service_create_contact_sync.py", + "description": "Sample for ListCmsMetadataValues", + "file": "admanager_v1_generated_cms_metadata_value_service_list_cms_metadata_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_CreateContact_sync", + "regionTag": "admanager_v1_generated_CmsMetadataValueService_ListCmsMetadataValues_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -6586,38 +6594,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_create_contact_sync.py" + "title": "admanager_v1_generated_cms_metadata_value_service_list_cms_metadata_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.get_contact", + "fullName": "google.ads.admanager_v1.CompanyServiceClient.batch_create_companies", "method": { - "fullName": "google.ads.admanager.v1.ContactService.GetContact", + "fullName": "google.ads.admanager.v1.CompanyService.BatchCreateCompanies", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" }, - "shortName": "GetContact" + "shortName": "BatchCreateCompanies" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetContactRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCompaniesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCompanyRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6631,22 +6643,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Contact", - "shortName": "get_contact" + "resultType": "google.ads.admanager_v1.types.BatchCreateCompaniesResponse", + "shortName": "batch_create_companies" }, - "description": "Sample for GetContact", - "file": "admanager_v1_generated_contact_service_get_contact_sync.py", + "description": "Sample for BatchCreateCompanies", + "file": "admanager_v1_generated_company_service_batch_create_companies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_GetContact_sync", + "regionTag": "admanager_v1_generated_CompanyService_BatchCreateCompanies_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6656,48 +6668,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_get_contact_sync.py" + "title": "admanager_v1_generated_company_service_batch_create_companies_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.list_contacts", + "fullName": "google.ads.admanager_v1.CompanyServiceClient.batch_update_companies", "method": { - "fullName": "google.ads.admanager.v1.ContactService.ListContacts", + "fullName": "google.ads.admanager.v1.CompanyService.BatchUpdateCompanies", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" }, - "shortName": "ListContacts" + "shortName": "BatchUpdateCompanies" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListContactsRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCompaniesRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCompanyRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6711,22 +6727,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.contact_service.pagers.ListContactsPager", - "shortName": "list_contacts" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCompaniesResponse", + "shortName": "batch_update_companies" }, - "description": "Sample for ListContacts", - "file": "admanager_v1_generated_contact_service_list_contacts_sync.py", + "description": "Sample for BatchUpdateCompanies", + "file": "admanager_v1_generated_company_service_batch_update_companies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_ListContacts_sync", + "regionTag": "admanager_v1_generated_CompanyService_BatchUpdateCompanies_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -6746,41 +6762,1513 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_list_contacts_sync.py" + "title": "admanager_v1_generated_company_service_batch_update_companies_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContactServiceClient", - "shortName": "ContactServiceClient" + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" }, - "fullName": "google.ads.admanager_v1.ContactServiceClient.update_contact", + "fullName": "google.ads.admanager_v1.CompanyServiceClient.create_company", "method": { - "fullName": "google.ads.admanager.v1.ContactService.UpdateContact", + "fullName": "google.ads.admanager.v1.CompanyService.CreateCompany", "service": { - "fullName": "google.ads.admanager.v1.ContactService", - "shortName": "ContactService" - }, + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" + }, + "shortName": "CreateCompany" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.CreateCompanyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "company", + "type": "google.ads.admanager_v1.types.Company" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.Company", + "shortName": "create_company" + }, + "description": "Sample for CreateCompany", + "file": "admanager_v1_generated_company_service_create_company_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_CompanyService_CreateCompany_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": "admanager_v1_generated_company_service_create_company_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" + }, + "fullName": "google.ads.admanager_v1.CompanyServiceClient.get_company", + "method": { + "fullName": "google.ads.admanager.v1.CompanyService.GetCompany", + "service": { + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" + }, + "shortName": "GetCompany" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetCompanyRequest" + }, + { + "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.ads.admanager_v1.types.Company", + "shortName": "get_company" + }, + "description": "Sample for GetCompany", + "file": "admanager_v1_generated_company_service_get_company_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_CompanyService_GetCompany_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": "admanager_v1_generated_company_service_get_company_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" + }, + "fullName": "google.ads.admanager_v1.CompanyServiceClient.list_companies", + "method": { + "fullName": "google.ads.admanager.v1.CompanyService.ListCompanies", + "service": { + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" + }, + "shortName": "ListCompanies" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.ListCompaniesRequest" + }, + { + "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.ads.admanager_v1.services.company_service.pagers.ListCompaniesPager", + "shortName": "list_companies" + }, + "description": "Sample for ListCompanies", + "file": "admanager_v1_generated_company_service_list_companies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_CompanyService_ListCompanies_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": "admanager_v1_generated_company_service_list_companies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.CompanyServiceClient", + "shortName": "CompanyServiceClient" + }, + "fullName": "google.ads.admanager_v1.CompanyServiceClient.update_company", + "method": { + "fullName": "google.ads.admanager.v1.CompanyService.UpdateCompany", + "service": { + "fullName": "google.ads.admanager.v1.CompanyService", + "shortName": "CompanyService" + }, + "shortName": "UpdateCompany" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.UpdateCompanyRequest" + }, + { + "name": "company", + "type": "google.ads.admanager_v1.types.Company" + }, + { + "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.ads.admanager_v1.types.Company", + "shortName": "update_company" + }, + "description": "Sample for UpdateCompany", + "file": "admanager_v1_generated_company_service_update_company_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_CompanyService_UpdateCompany_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "admanager_v1_generated_company_service_update_company_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.batch_create_contacts", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.BatchCreateContacts", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, + "shortName": "BatchCreateContacts" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.BatchCreateContactsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateContactRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.BatchCreateContactsResponse", + "shortName": "batch_create_contacts" + }, + "description": "Sample for BatchCreateContacts", + "file": "admanager_v1_generated_contact_service_batch_create_contacts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_BatchCreateContacts_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": "admanager_v1_generated_contact_service_batch_create_contacts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.batch_update_contacts", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.BatchUpdateContacts", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, + "shortName": "BatchUpdateContacts" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.BatchUpdateContactsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateContactRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.BatchUpdateContactsResponse", + "shortName": "batch_update_contacts" + }, + "description": "Sample for BatchUpdateContacts", + "file": "admanager_v1_generated_contact_service_batch_update_contacts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_BatchUpdateContacts_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": "admanager_v1_generated_contact_service_batch_update_contacts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.create_contact", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.CreateContact", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, + "shortName": "CreateContact" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.CreateContactRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "contact", + "type": "google.ads.admanager_v1.types.Contact" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.Contact", + "shortName": "create_contact" + }, + "description": "Sample for CreateContact", + "file": "admanager_v1_generated_contact_service_create_contact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_CreateContact_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": "admanager_v1_generated_contact_service_create_contact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.get_contact", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.GetContact", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, + "shortName": "GetContact" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetContactRequest" + }, + { + "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.ads.admanager_v1.types.Contact", + "shortName": "get_contact" + }, + "description": "Sample for GetContact", + "file": "admanager_v1_generated_contact_service_get_contact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_GetContact_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": "admanager_v1_generated_contact_service_get_contact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.list_contacts", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.ListContacts", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, + "shortName": "ListContacts" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.ListContactsRequest" + }, + { + "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.ads.admanager_v1.services.contact_service.pagers.ListContactsPager", + "shortName": "list_contacts" + }, + "description": "Sample for ListContacts", + "file": "admanager_v1_generated_contact_service_list_contacts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_ListContacts_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": "admanager_v1_generated_contact_service_list_contacts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContactServiceClient", + "shortName": "ContactServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContactServiceClient.update_contact", + "method": { + "fullName": "google.ads.admanager.v1.ContactService.UpdateContact", + "service": { + "fullName": "google.ads.admanager.v1.ContactService", + "shortName": "ContactService" + }, "shortName": "UpdateContact" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateContactRequest" + "type": "google.ads.admanager_v1.types.UpdateContactRequest" + }, + { + "name": "contact", + "type": "google.ads.admanager_v1.types.Contact" + }, + { + "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.ads.admanager_v1.types.Contact", + "shortName": "update_contact" + }, + "description": "Sample for UpdateContact", + "file": "admanager_v1_generated_contact_service_update_contact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContactService_UpdateContact_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "admanager_v1_generated_contact_service_update_contact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", + "shortName": "ContentBundleServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.batch_activate_content_bundles", + "method": { + "fullName": "google.ads.admanager.v1.ContentBundleService.BatchActivateContentBundles", + "service": { + "fullName": "google.ads.admanager.v1.ContentBundleService", + "shortName": "ContentBundleService" + }, + "shortName": "BatchActivateContentBundles" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.BatchActivateContentBundlesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "names", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.BatchActivateContentBundlesResponse", + "shortName": "batch_activate_content_bundles" + }, + "description": "Sample for BatchActivateContentBundles", + "file": "admanager_v1_generated_content_bundle_service_batch_activate_content_bundles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentBundleService_BatchActivateContentBundles_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "admanager_v1_generated_content_bundle_service_batch_activate_content_bundles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", + "shortName": "ContentBundleServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.batch_deactivate_content_bundles", + "method": { + "fullName": "google.ads.admanager.v1.ContentBundleService.BatchDeactivateContentBundles", + "service": { + "fullName": "google.ads.admanager.v1.ContentBundleService", + "shortName": "ContentBundleService" + }, + "shortName": "BatchDeactivateContentBundles" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.BatchDeactivateContentBundlesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "names", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.types.BatchDeactivateContentBundlesResponse", + "shortName": "batch_deactivate_content_bundles" + }, + "description": "Sample for BatchDeactivateContentBundles", + "file": "admanager_v1_generated_content_bundle_service_batch_deactivate_content_bundles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentBundleService_BatchDeactivateContentBundles_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "admanager_v1_generated_content_bundle_service_batch_deactivate_content_bundles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", + "shortName": "ContentBundleServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.get_content_bundle", + "method": { + "fullName": "google.ads.admanager.v1.ContentBundleService.GetContentBundle", + "service": { + "fullName": "google.ads.admanager.v1.ContentBundleService", + "shortName": "ContentBundleService" + }, + "shortName": "GetContentBundle" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetContentBundleRequest" + }, + { + "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.ads.admanager_v1.types.ContentBundle", + "shortName": "get_content_bundle" + }, + "description": "Sample for GetContentBundle", + "file": "admanager_v1_generated_content_bundle_service_get_content_bundle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentBundleService_GetContentBundle_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": "admanager_v1_generated_content_bundle_service_get_content_bundle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", + "shortName": "ContentBundleServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.list_content_bundles", + "method": { + "fullName": "google.ads.admanager.v1.ContentBundleService.ListContentBundles", + "service": { + "fullName": "google.ads.admanager.v1.ContentBundleService", + "shortName": "ContentBundleService" + }, + "shortName": "ListContentBundles" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.ListContentBundlesRequest" + }, + { + "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.ads.admanager_v1.services.content_bundle_service.pagers.ListContentBundlesPager", + "shortName": "list_content_bundles" + }, + "description": "Sample for ListContentBundles", + "file": "admanager_v1_generated_content_bundle_service_list_content_bundles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentBundleService_ListContentBundles_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": "admanager_v1_generated_content_bundle_service_list_content_bundles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentLabelServiceClient", + "shortName": "ContentLabelServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentLabelServiceClient.get_content_label", + "method": { + "fullName": "google.ads.admanager.v1.ContentLabelService.GetContentLabel", + "service": { + "fullName": "google.ads.admanager.v1.ContentLabelService", + "shortName": "ContentLabelService" + }, + "shortName": "GetContentLabel" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetContentLabelRequest" + }, + { + "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.ads.admanager_v1.types.ContentLabel", + "shortName": "get_content_label" + }, + "description": "Sample for GetContentLabel", + "file": "admanager_v1_generated_content_label_service_get_content_label_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentLabelService_GetContentLabel_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": "admanager_v1_generated_content_label_service_get_content_label_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentLabelServiceClient", + "shortName": "ContentLabelServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentLabelServiceClient.list_content_labels", + "method": { + "fullName": "google.ads.admanager.v1.ContentLabelService.ListContentLabels", + "service": { + "fullName": "google.ads.admanager.v1.ContentLabelService", + "shortName": "ContentLabelService" + }, + "shortName": "ListContentLabels" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.ListContentLabelsRequest" + }, + { + "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.ads.admanager_v1.services.content_label_service.pagers.ListContentLabelsPager", + "shortName": "list_content_labels" + }, + "description": "Sample for ListContentLabels", + "file": "admanager_v1_generated_content_label_service_list_content_labels_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentLabelService_ListContentLabels_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": "admanager_v1_generated_content_label_service_list_content_labels_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentServiceClient", + "shortName": "ContentServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentServiceClient.get_content", + "method": { + "fullName": "google.ads.admanager.v1.ContentService.GetContent", + "service": { + "fullName": "google.ads.admanager.v1.ContentService", + "shortName": "ContentService" + }, + "shortName": "GetContent" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetContentRequest" + }, + { + "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.ads.admanager_v1.types.Content", + "shortName": "get_content" + }, + "description": "Sample for GetContent", + "file": "admanager_v1_generated_content_service_get_content_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentService_GetContent_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": "admanager_v1_generated_content_service_get_content_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.ContentServiceClient", + "shortName": "ContentServiceClient" + }, + "fullName": "google.ads.admanager_v1.ContentServiceClient.list_content", + "method": { + "fullName": "google.ads.admanager.v1.ContentService.ListContent", + "service": { + "fullName": "google.ads.admanager.v1.ContentService", + "shortName": "ContentService" + }, + "shortName": "ListContent" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.ListContentRequest" }, { - "name": "contact", - "type": "google.ads.admanager_v1.types.Contact" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.ads.admanager_v1.services.content_service.pagers.ListContentPager", + "shortName": "list_content" + }, + "description": "Sample for ListContent", + "file": "admanager_v1_generated_content_service_list_content_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_ContentService_ListContent_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": "admanager_v1_generated_content_service_list_content_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", + "shortName": "CreativeSetServiceClient" + }, + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.create_creative_set", + "method": { + "fullName": "google.ads.admanager.v1.CreativeSetService.CreateCreativeSet", + "service": { + "fullName": "google.ads.admanager.v1.CreativeSetService", + "shortName": "CreativeSetService" + }, + "shortName": "CreateCreativeSet" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.CreateCreativeSetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "creative_set", + "type": "google.ads.admanager_v1.types.CreativeSet" }, { "name": "retry", @@ -6795,22 +8283,102 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Contact", - "shortName": "update_contact" + "resultType": "google.ads.admanager_v1.types.CreativeSet", + "shortName": "create_creative_set" }, - "description": "Sample for UpdateContact", - "file": "admanager_v1_generated_contact_service_update_contact_sync.py", + "description": "Sample for CreateCreativeSet", + "file": "admanager_v1_generated_creative_set_service_create_creative_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContactService_UpdateContact_sync", + "regionTag": "admanager_v1_generated_CreativeSetService_CreateCreativeSet_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "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": "admanager_v1_generated_creative_set_service_create_creative_set_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", + "shortName": "CreativeSetServiceClient" + }, + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.get_creative_set", + "method": { + "fullName": "google.ads.admanager.v1.CreativeSetService.GetCreativeSet", + "service": { + "fullName": "google.ads.admanager.v1.CreativeSetService", + "shortName": "CreativeSetService" + }, + "shortName": "GetCreativeSet" + }, + "parameters": [ + { + "name": "request", + "type": "google.ads.admanager_v1.types.GetCreativeSetRequest" + }, + { + "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.ads.admanager_v1.types.CreativeSet", + "shortName": "get_creative_set" + }, + "description": "Sample for GetCreativeSet", + "file": "admanager_v1_generated_creative_set_service_get_creative_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "admanager_v1_generated_CreativeSetService_GetCreativeSet_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, "start": 27, "type": "SHORT" }, @@ -6820,52 +8388,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_contact_service_update_contact_sync.py" + "title": "admanager_v1_generated_creative_set_service_get_creative_set_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", - "shortName": "ContentBundleServiceClient" + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", + "shortName": "CreativeSetServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.batch_activate_content_bundles", + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.list_creative_sets", "method": { - "fullName": "google.ads.admanager.v1.ContentBundleService.BatchActivateContentBundles", + "fullName": "google.ads.admanager.v1.CreativeSetService.ListCreativeSets", "service": { - "fullName": "google.ads.admanager.v1.ContentBundleService", - "shortName": "ContentBundleService" + "fullName": "google.ads.admanager.v1.CreativeSetService", + "shortName": "CreativeSetService" }, - "shortName": "BatchActivateContentBundles" + "shortName": "ListCreativeSets" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateContentBundlesRequest" + "type": "google.ads.admanager_v1.types.ListCreativeSetsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6879,14 +8443,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateContentBundlesResponse", - "shortName": "batch_activate_content_bundles" + "resultType": "google.ads.admanager_v1.services.creative_set_service.pagers.ListCreativeSetsPager", + "shortName": "list_creative_sets" }, - "description": "Sample for BatchActivateContentBundles", - "file": "admanager_v1_generated_content_bundle_service_batch_activate_content_bundles_sync.py", + "description": "Sample for ListCreativeSets", + "file": "admanager_v1_generated_creative_set_service_list_creative_sets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentBundleService_BatchActivateContentBundles_sync", + "regionTag": "admanager_v1_generated_CreativeSetService_ListCreativeSets_sync", "segments": [ { "end": 52, @@ -6904,51 +8468,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_bundle_service_batch_activate_content_bundles_sync.py" + "title": "admanager_v1_generated_creative_set_service_list_creative_sets_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", - "shortName": "ContentBundleServiceClient" + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", + "shortName": "CreativeSetServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.batch_deactivate_content_bundles", + "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.update_creative_set", "method": { - "fullName": "google.ads.admanager.v1.ContentBundleService.BatchDeactivateContentBundles", + "fullName": "google.ads.admanager.v1.CreativeSetService.UpdateCreativeSet", "service": { - "fullName": "google.ads.admanager.v1.ContentBundleService", - "shortName": "ContentBundleService" + "fullName": "google.ads.admanager.v1.CreativeSetService", + "shortName": "CreativeSetService" }, - "shortName": "BatchDeactivateContentBundles" + "shortName": "UpdateCreativeSet" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateContentBundlesRequest" + "type": "google.ads.admanager_v1.types.UpdateCreativeSetRequest" }, { - "name": "parent", - "type": "str" + "name": "creative_set", + "type": "google.ads.admanager_v1.types.CreativeSet" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -6963,22 +8527,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateContentBundlesResponse", - "shortName": "batch_deactivate_content_bundles" + "resultType": "google.ads.admanager_v1.types.CreativeSet", + "shortName": "update_creative_set" }, - "description": "Sample for BatchDeactivateContentBundles", - "file": "admanager_v1_generated_content_bundle_service_batch_deactivate_content_bundles_sync.py", + "description": "Sample for UpdateCreativeSet", + "file": "admanager_v1_generated_creative_set_service_update_creative_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentBundleService_BatchDeactivateContentBundles_sync", + "regionTag": "admanager_v1_generated_CreativeSetService_UpdateCreativeSet_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -6988,43 +8552,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_bundle_service_batch_deactivate_content_bundles_sync.py" + "title": "admanager_v1_generated_creative_set_service_update_creative_set_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", - "shortName": "ContentBundleServiceClient" + "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient", + "shortName": "CreativeTemplateServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.get_content_bundle", + "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient.get_creative_template", "method": { - "fullName": "google.ads.admanager.v1.ContentBundleService.GetContentBundle", + "fullName": "google.ads.admanager.v1.CreativeTemplateService.GetCreativeTemplate", "service": { - "fullName": "google.ads.admanager.v1.ContentBundleService", - "shortName": "ContentBundleService" + "fullName": "google.ads.admanager.v1.CreativeTemplateService", + "shortName": "CreativeTemplateService" }, - "shortName": "GetContentBundle" + "shortName": "GetCreativeTemplate" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetContentBundleRequest" + "type": "google.ads.admanager_v1.types.GetCreativeTemplateRequest" }, { "name": "name", @@ -7043,14 +8607,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.ContentBundle", - "shortName": "get_content_bundle" + "resultType": "google.ads.admanager_v1.types.CreativeTemplate", + "shortName": "get_creative_template" }, - "description": "Sample for GetContentBundle", - "file": "admanager_v1_generated_content_bundle_service_get_content_bundle_sync.py", + "description": "Sample for GetCreativeTemplate", + "file": "admanager_v1_generated_creative_template_service_get_creative_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentBundleService_GetContentBundle_sync", + "regionTag": "admanager_v1_generated_CreativeTemplateService_GetCreativeTemplate_sync", "segments": [ { "end": 51, @@ -7083,28 +8647,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_bundle_service_get_content_bundle_sync.py" + "title": "admanager_v1_generated_creative_template_service_get_creative_template_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient", - "shortName": "ContentBundleServiceClient" + "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient", + "shortName": "CreativeTemplateServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentBundleServiceClient.list_content_bundles", + "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient.list_creative_templates", "method": { - "fullName": "google.ads.admanager.v1.ContentBundleService.ListContentBundles", + "fullName": "google.ads.admanager.v1.CreativeTemplateService.ListCreativeTemplates", "service": { - "fullName": "google.ads.admanager.v1.ContentBundleService", - "shortName": "ContentBundleService" + "fullName": "google.ads.admanager.v1.CreativeTemplateService", + "shortName": "CreativeTemplateService" }, - "shortName": "ListContentBundles" + "shortName": "ListCreativeTemplates" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListContentBundlesRequest" + "type": "google.ads.admanager_v1.types.ListCreativeTemplatesRequest" }, { "name": "parent", @@ -7123,14 +8687,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.content_bundle_service.pagers.ListContentBundlesPager", - "shortName": "list_content_bundles" + "resultType": "google.ads.admanager_v1.services.creative_template_service.pagers.ListCreativeTemplatesPager", + "shortName": "list_creative_templates" }, - "description": "Sample for ListContentBundles", - "file": "admanager_v1_generated_content_bundle_service_list_content_bundles_sync.py", + "description": "Sample for ListCreativeTemplates", + "file": "admanager_v1_generated_creative_template_service_list_creative_templates_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentBundleService_ListContentBundles_sync", + "regionTag": "admanager_v1_generated_CreativeTemplateService_ListCreativeTemplates_sync", "segments": [ { "end": 52, @@ -7163,33 +8727,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_bundle_service_list_content_bundles_sync.py" + "title": "admanager_v1_generated_creative_template_service_list_creative_templates_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentLabelServiceClient", - "shortName": "ContentLabelServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentLabelServiceClient.get_content_label", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_activate_creative_wrappers", "method": { - "fullName": "google.ads.admanager.v1.ContentLabelService.GetContentLabel", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchActivateCreativeWrappers", "service": { - "fullName": "google.ads.admanager.v1.ContentLabelService", - "shortName": "ContentLabelService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "GetContentLabel" + "shortName": "BatchActivateCreativeWrappers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetContentLabelRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCreativeWrappersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7203,22 +8771,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.ContentLabel", - "shortName": "get_content_label" + "resultType": "google.ads.admanager_v1.types.BatchActivateCreativeWrappersResponse", + "shortName": "batch_activate_creative_wrappers" }, - "description": "Sample for GetContentLabel", - "file": "admanager_v1_generated_content_label_service_get_content_label_sync.py", + "description": "Sample for BatchActivateCreativeWrappers", + "file": "admanager_v1_generated_creative_wrapper_service_batch_activate_creative_wrappers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentLabelService_GetContentLabel_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchActivateCreativeWrappers_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7228,48 +8796,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_label_service_get_content_label_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_batch_activate_creative_wrappers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentLabelServiceClient", - "shortName": "ContentLabelServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentLabelServiceClient.list_content_labels", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_create_creative_wrappers", "method": { - "fullName": "google.ads.admanager.v1.ContentLabelService.ListContentLabels", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchCreateCreativeWrappers", "service": { - "fullName": "google.ads.admanager.v1.ContentLabelService", - "shortName": "ContentLabelService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "ListContentLabels" + "shortName": "BatchCreateCreativeWrappers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListContentLabelsRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCreativeWrappersRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCreativeWrapperRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7283,22 +8855,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.content_label_service.pagers.ListContentLabelsPager", - "shortName": "list_content_labels" + "resultType": "google.ads.admanager_v1.types.BatchCreateCreativeWrappersResponse", + "shortName": "batch_create_creative_wrappers" }, - "description": "Sample for ListContentLabels", - "file": "admanager_v1_generated_content_label_service_list_content_labels_sync.py", + "description": "Sample for BatchCreateCreativeWrappers", + "file": "admanager_v1_generated_creative_wrapper_service_batch_create_creative_wrappers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentLabelService_ListContentLabels_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchCreateCreativeWrappers_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -7308,48 +8880,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_label_service_list_content_labels_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_batch_create_creative_wrappers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentServiceClient", - "shortName": "ContentServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentServiceClient.get_content", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_deactivate_creative_wrappers", "method": { - "fullName": "google.ads.admanager.v1.ContentService.GetContent", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchDeactivateCreativeWrappers", "service": { - "fullName": "google.ads.admanager.v1.ContentService", - "shortName": "ContentService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "GetContent" + "shortName": "BatchDeactivateCreativeWrappers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetContentRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCreativeWrappersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7363,22 +8939,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Content", - "shortName": "get_content" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCreativeWrappersResponse", + "shortName": "batch_deactivate_creative_wrappers" }, - "description": "Sample for GetContent", - "file": "admanager_v1_generated_content_service_get_content_sync.py", + "description": "Sample for BatchDeactivateCreativeWrappers", + "file": "admanager_v1_generated_creative_wrapper_service_batch_deactivate_creative_wrappers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentService_GetContent_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchDeactivateCreativeWrappers_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7388,48 +8964,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_service_get_content_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_batch_deactivate_creative_wrappers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.ContentServiceClient", - "shortName": "ContentServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.ContentServiceClient.list_content", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_update_creative_wrappers", "method": { - "fullName": "google.ads.admanager.v1.ContentService.ListContent", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchUpdateCreativeWrappers", "service": { - "fullName": "google.ads.admanager.v1.ContentService", - "shortName": "ContentService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "ListContent" + "shortName": "BatchUpdateCreativeWrappers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListContentRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCreativeWrappersRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCreativeWrapperRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7443,22 +9023,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.content_service.pagers.ListContentPager", - "shortName": "list_content" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCreativeWrappersResponse", + "shortName": "batch_update_creative_wrappers" }, - "description": "Sample for ListContent", - "file": "admanager_v1_generated_content_service_list_content_sync.py", + "description": "Sample for BatchUpdateCreativeWrappers", + "file": "admanager_v1_generated_creative_wrapper_service_batch_update_creative_wrappers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_ContentService_ListContent_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchUpdateCreativeWrappers_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -7468,51 +9048,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_content_service_list_content_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_batch_update_creative_wrappers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", - "shortName": "CreativeSetServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.create_creative_set", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.create_creative_wrapper", "method": { - "fullName": "google.ads.admanager.v1.CreativeSetService.CreateCreativeSet", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.CreateCreativeWrapper", "service": { - "fullName": "google.ads.admanager.v1.CreativeSetService", - "shortName": "CreativeSetService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "CreateCreativeSet" + "shortName": "CreateCreativeWrapper" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCreativeSetRequest" + "type": "google.ads.admanager_v1.types.CreateCreativeWrapperRequest" }, { "name": "parent", "type": "str" }, { - "name": "creative_set", - "type": "google.ads.admanager_v1.types.CreativeSet" + "name": "creative_wrapper", + "type": "google.ads.admanager_v1.types.CreativeWrapper" }, { "name": "retry", @@ -7527,14 +9107,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeSet", - "shortName": "create_creative_set" + "resultType": "google.ads.admanager_v1.types.CreativeWrapper", + "shortName": "create_creative_wrapper" }, - "description": "Sample for CreateCreativeSet", - "file": "admanager_v1_generated_creative_set_service_create_creative_set_sync.py", + "description": "Sample for CreateCreativeWrapper", + "file": "admanager_v1_generated_creative_wrapper_service_create_creative_wrapper_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeSetService_CreateCreativeSet_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_CreateCreativeWrapper_sync", "segments": [ { "end": 55, @@ -7567,28 +9147,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_set_service_create_creative_set_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_create_creative_wrapper_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", - "shortName": "CreativeSetServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.get_creative_set", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.get_creative_wrapper", "method": { - "fullName": "google.ads.admanager.v1.CreativeSetService.GetCreativeSet", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.GetCreativeWrapper", "service": { - "fullName": "google.ads.admanager.v1.CreativeSetService", - "shortName": "CreativeSetService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "GetCreativeSet" + "shortName": "GetCreativeWrapper" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCreativeSetRequest" + "type": "google.ads.admanager_v1.types.GetCreativeWrapperRequest" }, { "name": "name", @@ -7607,14 +9187,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeSet", - "shortName": "get_creative_set" + "resultType": "google.ads.admanager_v1.types.CreativeWrapper", + "shortName": "get_creative_wrapper" }, - "description": "Sample for GetCreativeSet", - "file": "admanager_v1_generated_creative_set_service_get_creative_set_sync.py", + "description": "Sample for GetCreativeWrapper", + "file": "admanager_v1_generated_creative_wrapper_service_get_creative_wrapper_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeSetService_GetCreativeSet_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_GetCreativeWrapper_sync", "segments": [ { "end": 51, @@ -7647,28 +9227,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_set_service_get_creative_set_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_get_creative_wrapper_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", - "shortName": "CreativeSetServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.list_creative_sets", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.list_creative_wrappers", "method": { - "fullName": "google.ads.admanager.v1.CreativeSetService.ListCreativeSets", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.ListCreativeWrappers", "service": { - "fullName": "google.ads.admanager.v1.CreativeSetService", - "shortName": "CreativeSetService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "ListCreativeSets" + "shortName": "ListCreativeWrappers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCreativeSetsRequest" + "type": "google.ads.admanager_v1.types.ListCreativeWrappersRequest" }, { "name": "parent", @@ -7687,14 +9267,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.creative_set_service.pagers.ListCreativeSetsPager", - "shortName": "list_creative_sets" + "resultType": "google.ads.admanager_v1.services.creative_wrapper_service.pagers.ListCreativeWrappersPager", + "shortName": "list_creative_wrappers" }, - "description": "Sample for ListCreativeSets", - "file": "admanager_v1_generated_creative_set_service_list_creative_sets_sync.py", + "description": "Sample for ListCreativeWrappers", + "file": "admanager_v1_generated_creative_wrapper_service_list_creative_wrappers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeSetService_ListCreativeSets_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_ListCreativeWrappers_sync", "segments": [ { "end": 52, @@ -7727,32 +9307,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_set_service_list_creative_sets_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_list_creative_wrappers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient", - "shortName": "CreativeSetServiceClient" + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", + "shortName": "CreativeWrapperServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeSetServiceClient.update_creative_set", + "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.update_creative_wrapper", "method": { - "fullName": "google.ads.admanager.v1.CreativeSetService.UpdateCreativeSet", + "fullName": "google.ads.admanager.v1.CreativeWrapperService.UpdateCreativeWrapper", "service": { - "fullName": "google.ads.admanager.v1.CreativeSetService", - "shortName": "CreativeSetService" + "fullName": "google.ads.admanager.v1.CreativeWrapperService", + "shortName": "CreativeWrapperService" }, - "shortName": "UpdateCreativeSet" + "shortName": "UpdateCreativeWrapper" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCreativeSetRequest" + "type": "google.ads.admanager_v1.types.UpdateCreativeWrapperRequest" }, { - "name": "creative_set", - "type": "google.ads.admanager_v1.types.CreativeSet" + "name": "creative_wrapper", + "type": "google.ads.admanager_v1.types.CreativeWrapper" }, { "name": "update_mask", @@ -7771,14 +9351,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeSet", - "shortName": "update_creative_set" + "resultType": "google.ads.admanager_v1.types.CreativeWrapper", + "shortName": "update_creative_wrapper" }, - "description": "Sample for UpdateCreativeSet", - "file": "admanager_v1_generated_creative_set_service_update_creative_set_sync.py", + "description": "Sample for UpdateCreativeWrapper", + "file": "admanager_v1_generated_creative_wrapper_service_update_creative_wrapper_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeSetService_UpdateCreativeSet_sync", + "regionTag": "admanager_v1_generated_CreativeWrapperService_UpdateCreativeWrapper_sync", "segments": [ { "end": 54, @@ -7811,33 +9391,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_set_service_update_creative_set_sync.py" + "title": "admanager_v1_generated_creative_wrapper_service_update_creative_wrapper_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient", - "shortName": "CreativeTemplateServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient.get_creative_template", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_activate_custom_fields", "method": { - "fullName": "google.ads.admanager.v1.CreativeTemplateService.GetCreativeTemplate", + "fullName": "google.ads.admanager.v1.CustomFieldService.BatchActivateCustomFields", "service": { - "fullName": "google.ads.admanager.v1.CreativeTemplateService", - "shortName": "CreativeTemplateService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "GetCreativeTemplate" + "shortName": "BatchActivateCustomFields" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCreativeTemplateRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCustomFieldsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7851,22 +9435,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeTemplate", - "shortName": "get_creative_template" + "resultType": "google.ads.admanager_v1.types.BatchActivateCustomFieldsResponse", + "shortName": "batch_activate_custom_fields" }, - "description": "Sample for GetCreativeTemplate", - "file": "admanager_v1_generated_creative_template_service_get_creative_template_sync.py", + "description": "Sample for BatchActivateCustomFields", + "file": "admanager_v1_generated_custom_field_service_batch_activate_custom_fields_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeTemplateService_GetCreativeTemplate_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_BatchActivateCustomFields_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -7876,48 +9460,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_template_service_get_creative_template_sync.py" + "title": "admanager_v1_generated_custom_field_service_batch_activate_custom_fields_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient", - "shortName": "CreativeTemplateServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeTemplateServiceClient.list_creative_templates", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_create_custom_fields", "method": { - "fullName": "google.ads.admanager.v1.CreativeTemplateService.ListCreativeTemplates", + "fullName": "google.ads.admanager.v1.CustomFieldService.BatchCreateCustomFields", "service": { - "fullName": "google.ads.admanager.v1.CreativeTemplateService", - "shortName": "CreativeTemplateService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "ListCreativeTemplates" + "shortName": "BatchCreateCustomFields" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCreativeTemplatesRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCustomFieldsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomFieldRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7931,22 +9519,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.creative_template_service.pagers.ListCreativeTemplatesPager", - "shortName": "list_creative_templates" + "resultType": "google.ads.admanager_v1.types.BatchCreateCustomFieldsResponse", + "shortName": "batch_create_custom_fields" }, - "description": "Sample for ListCreativeTemplates", - "file": "admanager_v1_generated_creative_template_service_list_creative_templates_sync.py", + "description": "Sample for BatchCreateCustomFields", + "file": "admanager_v1_generated_custom_field_service_batch_create_custom_fields_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeTemplateService_ListCreativeTemplates_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_BatchCreateCustomFields_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -7956,43 +9544,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_template_service_list_creative_templates_sync.py" + "title": "admanager_v1_generated_custom_field_service_batch_create_custom_fields_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_activate_creative_wrappers", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_deactivate_custom_fields", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchActivateCreativeWrappers", + "fullName": "google.ads.admanager.v1.CustomFieldService.BatchDeactivateCustomFields", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "BatchActivateCreativeWrappers" + "shortName": "BatchDeactivateCustomFields" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCreativeWrappersRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCustomFieldsRequest" }, { "name": "parent", @@ -8015,14 +9603,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCreativeWrappersResponse", - "shortName": "batch_activate_creative_wrappers" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomFieldsResponse", + "shortName": "batch_deactivate_custom_fields" }, - "description": "Sample for BatchActivateCreativeWrappers", - "file": "admanager_v1_generated_creative_wrapper_service_batch_activate_creative_wrappers_sync.py", + "description": "Sample for BatchDeactivateCustomFields", + "file": "admanager_v1_generated_custom_field_service_batch_deactivate_custom_fields_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchActivateCreativeWrappers_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_BatchDeactivateCustomFields_sync", "segments": [ { "end": 52, @@ -8055,28 +9643,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_batch_activate_creative_wrappers_sync.py" + "title": "admanager_v1_generated_custom_field_service_batch_deactivate_custom_fields_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_create_creative_wrappers", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_update_custom_fields", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchCreateCreativeWrappers", + "fullName": "google.ads.admanager.v1.CustomFieldService.BatchUpdateCustomFields", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "BatchCreateCreativeWrappers" + "shortName": "BatchUpdateCustomFields" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCreativeWrappersRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCustomFieldsRequest" }, { "name": "parent", @@ -8084,7 +9672,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCreativeWrapperRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomFieldRequest]" }, { "name": "retry", @@ -8099,22 +9687,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCreativeWrappersResponse", - "shortName": "batch_create_creative_wrappers" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomFieldsResponse", + "shortName": "batch_update_custom_fields" }, - "description": "Sample for BatchCreateCreativeWrappers", - "file": "admanager_v1_generated_creative_wrapper_service_batch_create_creative_wrappers_sync.py", + "description": "Sample for BatchUpdateCustomFields", + "file": "admanager_v1_generated_custom_field_service_batch_update_custom_fields_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchCreateCreativeWrappers_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_BatchUpdateCustomFields_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8124,51 +9712,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_batch_create_creative_wrappers_sync.py" + "title": "admanager_v1_generated_custom_field_service_batch_update_custom_fields_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_deactivate_creative_wrappers", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.create_custom_field", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchDeactivateCreativeWrappers", + "fullName": "google.ads.admanager.v1.CustomFieldService.CreateCustomField", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "BatchDeactivateCreativeWrappers" + "shortName": "CreateCustomField" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCreativeWrappersRequest" + "type": "google.ads.admanager_v1.types.CreateCustomFieldRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "custom_field", + "type": "google.ads.admanager_v1.types.CustomField" }, { "name": "retry", @@ -8183,22 +9771,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCreativeWrappersResponse", - "shortName": "batch_deactivate_creative_wrappers" + "resultType": "google.ads.admanager_v1.types.CustomField", + "shortName": "create_custom_field" }, - "description": "Sample for BatchDeactivateCreativeWrappers", - "file": "admanager_v1_generated_creative_wrapper_service_batch_deactivate_creative_wrappers_sync.py", + "description": "Sample for CreateCustomField", + "file": "admanager_v1_generated_custom_field_service_create_custom_field_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchDeactivateCreativeWrappers_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_CreateCustomField_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8208,52 +9796,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_batch_deactivate_creative_wrappers_sync.py" + "title": "admanager_v1_generated_custom_field_service_create_custom_field_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.batch_update_creative_wrappers", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.get_custom_field", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.BatchUpdateCreativeWrappers", + "fullName": "google.ads.admanager.v1.CustomFieldService.GetCustomField", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "BatchUpdateCreativeWrappers" + "shortName": "GetCustomField" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCreativeWrappersRequest" + "type": "google.ads.admanager_v1.types.GetCustomFieldRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCreativeWrapperRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -8267,22 +9851,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCreativeWrappersResponse", - "shortName": "batch_update_creative_wrappers" + "resultType": "google.ads.admanager_v1.types.CustomField", + "shortName": "get_custom_field" }, - "description": "Sample for BatchUpdateCreativeWrappers", - "file": "admanager_v1_generated_creative_wrapper_service_batch_update_creative_wrappers_sync.py", + "description": "Sample for GetCustomField", + "file": "admanager_v1_generated_custom_field_service_get_custom_field_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_BatchUpdateCreativeWrappers_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_GetCustomField_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8292,52 +9876,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_batch_update_creative_wrappers_sync.py" + "title": "admanager_v1_generated_custom_field_service_get_custom_field_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.create_creative_wrapper", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.list_custom_fields", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.CreateCreativeWrapper", + "fullName": "google.ads.admanager.v1.CustomFieldService.ListCustomFields", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "CreateCreativeWrapper" + "shortName": "ListCustomFields" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCreativeWrapperRequest" + "type": "google.ads.admanager_v1.types.ListCustomFieldsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "creative_wrapper", - "type": "google.ads.admanager_v1.types.CreativeWrapper" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -8351,22 +9931,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeWrapper", - "shortName": "create_creative_wrapper" + "resultType": "google.ads.admanager_v1.services.custom_field_service.pagers.ListCustomFieldsPager", + "shortName": "list_custom_fields" }, - "description": "Sample for CreateCreativeWrapper", - "file": "admanager_v1_generated_creative_wrapper_service_create_creative_wrapper_sync.py", + "description": "Sample for ListCustomFields", + "file": "admanager_v1_generated_custom_field_service_list_custom_fields_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_CreateCreativeWrapper_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_ListCustomFields_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -8376,47 +9956,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_create_creative_wrapper_sync.py" + "title": "admanager_v1_generated_custom_field_service_list_custom_fields_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", + "shortName": "CustomFieldServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.get_creative_wrapper", + "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.update_custom_field", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.GetCreativeWrapper", + "fullName": "google.ads.admanager.v1.CustomFieldService.UpdateCustomField", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomFieldService", + "shortName": "CustomFieldService" }, - "shortName": "GetCreativeWrapper" + "shortName": "UpdateCustomField" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCreativeWrapperRequest" + "type": "google.ads.admanager_v1.types.UpdateCustomFieldRequest" }, { - "name": "name", - "type": "str" + "name": "custom_field", + "type": "google.ads.admanager_v1.types.CustomField" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -8431,22 +10015,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeWrapper", - "shortName": "get_creative_wrapper" + "resultType": "google.ads.admanager_v1.types.CustomField", + "shortName": "update_custom_field" }, - "description": "Sample for GetCreativeWrapper", - "file": "admanager_v1_generated_creative_wrapper_service_get_creative_wrapper_sync.py", + "description": "Sample for UpdateCustomField", + "file": "admanager_v1_generated_custom_field_service_update_custom_field_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_GetCreativeWrapper_sync", + "regionTag": "admanager_v1_generated_CustomFieldService_UpdateCustomField_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -8456,48 +10040,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_get_creative_wrapper_sync.py" + "title": "admanager_v1_generated_custom_field_service_update_custom_field_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.list_creative_wrappers", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_activate_custom_targeting_keys", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.ListCreativeWrappers", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchActivateCustomTargetingKeys", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "ListCreativeWrappers" + "shortName": "BatchActivateCustomTargetingKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCreativeWrappersRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCustomTargetingKeysRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -8511,14 +10099,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.creative_wrapper_service.pagers.ListCreativeWrappersPager", - "shortName": "list_creative_wrappers" + "resultType": "google.ads.admanager_v1.types.BatchActivateCustomTargetingKeysResponse", + "shortName": "batch_activate_custom_targeting_keys" }, - "description": "Sample for ListCreativeWrappers", - "file": "admanager_v1_generated_creative_wrapper_service_list_creative_wrappers_sync.py", + "description": "Sample for BatchActivateCustomTargetingKeys", + "file": "admanager_v1_generated_custom_targeting_key_service_batch_activate_custom_targeting_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_ListCreativeWrappers_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchActivateCustomTargetingKeys_sync", "segments": [ { "end": 52, @@ -8536,51 +10124,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_list_creative_wrappers_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_batch_activate_custom_targeting_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient", - "shortName": "CreativeWrapperServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CreativeWrapperServiceClient.update_creative_wrapper", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_create_custom_targeting_keys", "method": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService.UpdateCreativeWrapper", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchCreateCustomTargetingKeys", "service": { - "fullName": "google.ads.admanager.v1.CreativeWrapperService", - "shortName": "CreativeWrapperService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "UpdateCreativeWrapper" + "shortName": "BatchCreateCustomTargetingKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCreativeWrapperRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCustomTargetingKeysRequest" }, { - "name": "creative_wrapper", - "type": "google.ads.admanager_v1.types.CreativeWrapper" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomTargetingKeyRequest]" }, { "name": "retry", @@ -8595,22 +10183,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CreativeWrapper", - "shortName": "update_creative_wrapper" + "resultType": "google.ads.admanager_v1.types.BatchCreateCustomTargetingKeysResponse", + "shortName": "batch_create_custom_targeting_keys" }, - "description": "Sample for UpdateCreativeWrapper", - "file": "admanager_v1_generated_creative_wrapper_service_update_creative_wrapper_sync.py", + "description": "Sample for BatchCreateCustomTargetingKeys", + "file": "admanager_v1_generated_custom_targeting_key_service_batch_create_custom_targeting_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CreativeWrapperService_UpdateCreativeWrapper_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchCreateCustomTargetingKeys_sync", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -8620,43 +10208,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_creative_wrapper_service_update_creative_wrapper_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_batch_create_custom_targeting_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_activate_custom_fields", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_deactivate_custom_targeting_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.BatchActivateCustomFields", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchDeactivateCustomTargetingKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "BatchActivateCustomFields" + "shortName": "BatchDeactivateCustomTargetingKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCustomFieldsRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingKeysRequest" }, { "name": "parent", @@ -8679,14 +10267,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCustomFieldsResponse", - "shortName": "batch_activate_custom_fields" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingKeysResponse", + "shortName": "batch_deactivate_custom_targeting_keys" }, - "description": "Sample for BatchActivateCustomFields", - "file": "admanager_v1_generated_custom_field_service_batch_activate_custom_fields_sync.py", + "description": "Sample for BatchDeactivateCustomTargetingKeys", + "file": "admanager_v1_generated_custom_targeting_key_service_batch_deactivate_custom_targeting_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_BatchActivateCustomFields_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchDeactivateCustomTargetingKeys_sync", "segments": [ { "end": 52, @@ -8719,28 +10307,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_batch_activate_custom_fields_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_batch_deactivate_custom_targeting_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_create_custom_fields", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_update_custom_targeting_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.BatchCreateCustomFields", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchUpdateCustomTargetingKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "BatchCreateCustomFields" + "shortName": "BatchUpdateCustomTargetingKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCustomFieldsRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingKeysRequest" }, { "name": "parent", @@ -8748,7 +10336,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomFieldRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomTargetingKeyRequest]" }, { "name": "retry", @@ -8763,22 +10351,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCustomFieldsResponse", - "shortName": "batch_create_custom_fields" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingKeysResponse", + "shortName": "batch_update_custom_targeting_keys" }, - "description": "Sample for BatchCreateCustomFields", - "file": "admanager_v1_generated_custom_field_service_batch_create_custom_fields_sync.py", + "description": "Sample for BatchUpdateCustomTargetingKeys", + "file": "admanager_v1_generated_custom_targeting_key_service_batch_update_custom_targeting_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_BatchCreateCustomFields_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchUpdateCustomTargetingKeys_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8788,51 +10376,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_batch_create_custom_fields_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_batch_update_custom_targeting_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_deactivate_custom_fields", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.create_custom_targeting_key", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.BatchDeactivateCustomFields", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.CreateCustomTargetingKey", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "BatchDeactivateCustomFields" + "shortName": "CreateCustomTargetingKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCustomFieldsRequest" + "type": "google.ads.admanager_v1.types.CreateCustomTargetingKeyRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "custom_targeting_key", + "type": "google.ads.admanager_v1.types.CustomTargetingKey" }, { "name": "retry", @@ -8847,22 +10435,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomFieldsResponse", - "shortName": "batch_deactivate_custom_fields" + "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", + "shortName": "create_custom_targeting_key" }, - "description": "Sample for BatchDeactivateCustomFields", - "file": "admanager_v1_generated_custom_field_service_batch_deactivate_custom_fields_sync.py", + "description": "Sample for CreateCustomTargetingKey", + "file": "admanager_v1_generated_custom_targeting_key_service_create_custom_targeting_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_BatchDeactivateCustomFields_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_CreateCustomTargetingKey_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -8872,52 +10460,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_batch_deactivate_custom_fields_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_create_custom_targeting_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.batch_update_custom_fields", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.get_custom_targeting_key", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.BatchUpdateCustomFields", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.GetCustomTargetingKey", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "BatchUpdateCustomFields" + "shortName": "GetCustomTargetingKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCustomFieldsRequest" + "type": "google.ads.admanager_v1.types.GetCustomTargetingKeyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomFieldRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -8931,14 +10515,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomFieldsResponse", - "shortName": "batch_update_custom_fields" + "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", + "shortName": "get_custom_targeting_key" }, - "description": "Sample for BatchUpdateCustomFields", - "file": "admanager_v1_generated_custom_field_service_batch_update_custom_fields_sync.py", + "description": "Sample for GetCustomTargetingKey", + "file": "admanager_v1_generated_custom_targeting_key_service_get_custom_targeting_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_BatchUpdateCustomFields_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_GetCustomTargetingKey_sync", "segments": [ { "end": 51, @@ -8971,37 +10555,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_batch_update_custom_fields_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_get_custom_targeting_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.create_custom_field", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.list_custom_targeting_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.CreateCustomField", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.ListCustomTargetingKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "CreateCustomField" + "shortName": "ListCustomTargetingKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCustomFieldRequest" + "type": "google.ads.admanager_v1.types.ListCustomTargetingKeysRequest" }, { "name": "parent", "type": "str" }, - { - "name": "custom_field", - "type": "google.ads.admanager_v1.types.CustomField" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9015,22 +10595,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomField", - "shortName": "create_custom_field" + "resultType": "google.ads.admanager_v1.services.custom_targeting_key_service.pagers.ListCustomTargetingKeysPager", + "shortName": "list_custom_targeting_keys" }, - "description": "Sample for CreateCustomField", - "file": "admanager_v1_generated_custom_field_service_create_custom_field_sync.py", + "description": "Sample for ListCustomTargetingKeys", + "file": "admanager_v1_generated_custom_targeting_key_service_list_custom_targeting_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_CreateCustomField_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_ListCustomTargetingKeys_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9050,37 +10630,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_create_custom_field_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_list_custom_targeting_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", + "shortName": "CustomTargetingKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.get_custom_field", + "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.update_custom_targeting_key", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.GetCustomField", + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.UpdateCustomTargetingKey", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", + "shortName": "CustomTargetingKeyService" }, - "shortName": "GetCustomField" + "shortName": "UpdateCustomTargetingKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCustomFieldRequest" + "type": "google.ads.admanager_v1.types.UpdateCustomTargetingKeyRequest" }, { - "name": "name", - "type": "str" + "name": "custom_targeting_key", + "type": "google.ads.admanager_v1.types.CustomTargetingKey" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9095,22 +10679,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomField", - "shortName": "get_custom_field" + "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", + "shortName": "update_custom_targeting_key" }, - "description": "Sample for GetCustomField", - "file": "admanager_v1_generated_custom_field_service_get_custom_field_sync.py", + "description": "Sample for UpdateCustomTargetingKey", + "file": "admanager_v1_generated_custom_targeting_key_service_update_custom_targeting_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_GetCustomField_sync", + "regionTag": "admanager_v1_generated_CustomTargetingKeyService_UpdateCustomTargetingKey_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -9120,48 +10704,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_get_custom_field_sync.py" + "title": "admanager_v1_generated_custom_targeting_key_service_update_custom_targeting_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.list_custom_fields", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_activate_custom_targeting_values", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.ListCustomFields", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchActivateCustomTargetingValues", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "ListCustomFields" + "shortName": "BatchActivateCustomTargetingValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCustomFieldsRequest" + "type": "google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.ActivateCustomTargetingValueRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9175,22 +10763,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.custom_field_service.pagers.ListCustomFieldsPager", - "shortName": "list_custom_fields" + "resultType": "google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesResponse", + "shortName": "batch_activate_custom_targeting_values" }, - "description": "Sample for ListCustomFields", - "file": "admanager_v1_generated_custom_field_service_list_custom_fields_sync.py", + "description": "Sample for BatchActivateCustomTargetingValues", + "file": "admanager_v1_generated_custom_targeting_value_service_batch_activate_custom_targeting_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_ListCustomFields_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchActivateCustomTargetingValues_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9200,51 +10788,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_list_custom_fields_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_batch_activate_custom_targeting_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient", - "shortName": "CustomFieldServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomFieldServiceClient.update_custom_field", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_create_custom_targeting_values", "method": { - "fullName": "google.ads.admanager.v1.CustomFieldService.UpdateCustomField", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchCreateCustomTargetingValues", "service": { - "fullName": "google.ads.admanager.v1.CustomFieldService", - "shortName": "CustomFieldService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "UpdateCustomField" + "shortName": "BatchCreateCustomTargetingValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCustomFieldRequest" + "type": "google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesRequest" }, { - "name": "custom_field", - "type": "google.ads.admanager_v1.types.CustomField" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomTargetingValueRequest]" }, { "name": "retry", @@ -9259,22 +10847,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomField", - "shortName": "update_custom_field" + "resultType": "google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesResponse", + "shortName": "batch_create_custom_targeting_values" }, - "description": "Sample for UpdateCustomField", - "file": "admanager_v1_generated_custom_field_service_update_custom_field_sync.py", + "description": "Sample for BatchCreateCustomTargetingValues", + "file": "admanager_v1_generated_custom_targeting_value_service_batch_create_custom_targeting_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomFieldService_UpdateCustomField_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchCreateCustomTargetingValues_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9284,51 +10872,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_field_service_update_custom_field_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_batch_create_custom_targeting_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_activate_custom_targeting_keys", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_deactivate_custom_targeting_values", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchActivateCustomTargetingKeys", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchDeactivateCustomTargetingValues", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "BatchActivateCustomTargetingKeys" + "shortName": "BatchDeactivateCustomTargetingValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCustomTargetingKeysRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.DeactivateCustomTargetingValueRequest]" }, { "name": "retry", @@ -9343,22 +10931,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCustomTargetingKeysResponse", - "shortName": "batch_activate_custom_targeting_keys" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesResponse", + "shortName": "batch_deactivate_custom_targeting_values" }, - "description": "Sample for BatchActivateCustomTargetingKeys", - "file": "admanager_v1_generated_custom_targeting_key_service_batch_activate_custom_targeting_keys_sync.py", + "description": "Sample for BatchDeactivateCustomTargetingValues", + "file": "admanager_v1_generated_custom_targeting_value_service_batch_deactivate_custom_targeting_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchActivateCustomTargetingKeys_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchDeactivateCustomTargetingValues_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9368,43 +10956,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_batch_activate_custom_targeting_keys_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_batch_deactivate_custom_targeting_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_create_custom_targeting_keys", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_update_custom_targeting_values", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchCreateCustomTargetingKeys", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchUpdateCustomTargetingValues", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "BatchCreateCustomTargetingKeys" + "shortName": "BatchUpdateCustomTargetingValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCustomTargetingKeysRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesRequest" }, { "name": "parent", @@ -9412,7 +11000,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomTargetingKeyRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest]" }, { "name": "retry", @@ -9427,22 +11015,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCustomTargetingKeysResponse", - "shortName": "batch_create_custom_targeting_keys" + "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesResponse", + "shortName": "batch_update_custom_targeting_values" }, - "description": "Sample for BatchCreateCustomTargetingKeys", - "file": "admanager_v1_generated_custom_targeting_key_service_batch_create_custom_targeting_keys_sync.py", + "description": "Sample for BatchUpdateCustomTargetingValues", + "file": "admanager_v1_generated_custom_targeting_value_service_batch_update_custom_targeting_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchCreateCustomTargetingKeys_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchUpdateCustomTargetingValues_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9452,51 +11040,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_batch_create_custom_targeting_keys_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_batch_update_custom_targeting_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_deactivate_custom_targeting_keys", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.create_custom_targeting_value", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchDeactivateCustomTargetingKeys", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.CreateCustomTargetingValue", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "BatchDeactivateCustomTargetingKeys" + "shortName": "CreateCustomTargetingValue" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingKeysRequest" + "type": "google.ads.admanager_v1.types.CreateCustomTargetingValueRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "custom_targeting_value", + "type": "google.ads.admanager_v1.types.CustomTargetingValue" }, { "name": "retry", @@ -9511,22 +11099,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingKeysResponse", - "shortName": "batch_deactivate_custom_targeting_keys" + "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", + "shortName": "create_custom_targeting_value" }, - "description": "Sample for BatchDeactivateCustomTargetingKeys", - "file": "admanager_v1_generated_custom_targeting_key_service_batch_deactivate_custom_targeting_keys_sync.py", + "description": "Sample for CreateCustomTargetingValue", + "file": "admanager_v1_generated_custom_targeting_value_service_create_custom_targeting_value_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchDeactivateCustomTargetingKeys_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_CreateCustomTargetingValue_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -9536,52 +11124,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_batch_deactivate_custom_targeting_keys_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_create_custom_targeting_value_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.batch_update_custom_targeting_keys", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.get_custom_targeting_value", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.BatchUpdateCustomTargetingKeys", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.GetCustomTargetingValue", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "BatchUpdateCustomTargetingKeys" + "shortName": "GetCustomTargetingValue" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingKeysRequest" + "type": "google.ads.admanager_v1.types.GetCustomTargetingValueRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomTargetingKeyRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9595,14 +11179,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingKeysResponse", - "shortName": "batch_update_custom_targeting_keys" + "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", + "shortName": "get_custom_targeting_value" }, - "description": "Sample for BatchUpdateCustomTargetingKeys", - "file": "admanager_v1_generated_custom_targeting_key_service_batch_update_custom_targeting_keys_sync.py", + "description": "Sample for GetCustomTargetingValue", + "file": "admanager_v1_generated_custom_targeting_value_service_get_custom_targeting_value_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_BatchUpdateCustomTargetingKeys_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_GetCustomTargetingValue_sync", "segments": [ { "end": 51, @@ -9635,37 +11219,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_batch_update_custom_targeting_keys_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_get_custom_targeting_value_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.create_custom_targeting_key", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.list_custom_targeting_values", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.CreateCustomTargetingKey", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.ListCustomTargetingValues", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "CreateCustomTargetingKey" + "shortName": "ListCustomTargetingValues" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCustomTargetingKeyRequest" + "type": "google.ads.admanager_v1.types.ListCustomTargetingValuesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "custom_targeting_key", - "type": "google.ads.admanager_v1.types.CustomTargetingKey" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9679,22 +11259,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", - "shortName": "create_custom_targeting_key" + "resultType": "google.ads.admanager_v1.services.custom_targeting_value_service.pagers.ListCustomTargetingValuesPager", + "shortName": "list_custom_targeting_values" }, - "description": "Sample for CreateCustomTargetingKey", - "file": "admanager_v1_generated_custom_targeting_key_service_create_custom_targeting_key_sync.py", + "description": "Sample for ListCustomTargetingValues", + "file": "admanager_v1_generated_custom_targeting_value_service_list_custom_targeting_values_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_CreateCustomTargetingKey_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_ListCustomTargetingValues_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -9714,37 +11294,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_create_custom_targeting_key_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_list_custom_targeting_values_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", + "shortName": "CustomTargetingValueServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.get_custom_targeting_key", + "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.update_custom_targeting_value", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.GetCustomTargetingKey", + "fullName": "google.ads.admanager.v1.CustomTargetingValueService.UpdateCustomTargetingValue", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.CustomTargetingValueService", + "shortName": "CustomTargetingValueService" }, - "shortName": "GetCustomTargetingKey" + "shortName": "UpdateCustomTargetingValue" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCustomTargetingKeyRequest" + "type": "google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest" }, { - "name": "name", - "type": "str" + "name": "custom_targeting_value", + "type": "google.ads.admanager_v1.types.CustomTargetingValue" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -9759,22 +11343,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", - "shortName": "get_custom_targeting_key" + "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", + "shortName": "update_custom_targeting_value" }, - "description": "Sample for GetCustomTargetingKey", - "file": "admanager_v1_generated_custom_targeting_key_service_get_custom_targeting_key_sync.py", + "description": "Sample for UpdateCustomTargetingValue", + "file": "admanager_v1_generated_custom_targeting_value_service_update_custom_targeting_value_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_GetCustomTargetingKey_sync", + "regionTag": "admanager_v1_generated_CustomTargetingValueService_UpdateCustomTargetingValue_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -9784,48 +11368,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_get_custom_targeting_key_sync.py" + "title": "admanager_v1_generated_custom_targeting_value_service_update_custom_targeting_value_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.list_custom_targeting_keys", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_activate_dai_authentication_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.ListCustomTargetingKeys", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchActivateDaiAuthenticationKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "ListCustomTargetingKeys" + "shortName": "BatchActivateDaiAuthenticationKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCustomTargetingKeysRequest" + "type": "google.ads.admanager_v1.types.BatchActivateDaiAuthenticationKeysRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -9839,14 +11427,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.custom_targeting_key_service.pagers.ListCustomTargetingKeysPager", - "shortName": "list_custom_targeting_keys" + "resultType": "google.ads.admanager_v1.types.BatchActivateDaiAuthenticationKeysResponse", + "shortName": "batch_activate_dai_authentication_keys" }, - "description": "Sample for ListCustomTargetingKeys", - "file": "admanager_v1_generated_custom_targeting_key_service_list_custom_targeting_keys_sync.py", + "description": "Sample for BatchActivateDaiAuthenticationKeys", + "file": "admanager_v1_generated_dai_authentication_key_service_batch_activate_dai_authentication_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_ListCustomTargetingKeys_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchActivateDaiAuthenticationKeys_sync", "segments": [ { "end": 52, @@ -9864,51 +11452,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_list_custom_targeting_keys_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_batch_activate_dai_authentication_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient", - "shortName": "CustomTargetingKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingKeyServiceClient.update_custom_targeting_key", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_create_dai_authentication_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService.UpdateCustomTargetingKey", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchCreateDaiAuthenticationKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingKeyService", - "shortName": "CustomTargetingKeyService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "UpdateCustomTargetingKey" + "shortName": "BatchCreateDaiAuthenticationKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCustomTargetingKeyRequest" + "type": "google.ads.admanager_v1.types.BatchCreateDaiAuthenticationKeysRequest" }, { - "name": "custom_targeting_key", - "type": "google.ads.admanager_v1.types.CustomTargetingKey" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateDaiAuthenticationKeyRequest]" }, { "name": "retry", @@ -9923,22 +11511,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingKey", - "shortName": "update_custom_targeting_key" + "resultType": "google.ads.admanager_v1.types.BatchCreateDaiAuthenticationKeysResponse", + "shortName": "batch_create_dai_authentication_keys" }, - "description": "Sample for UpdateCustomTargetingKey", - "file": "admanager_v1_generated_custom_targeting_key_service_update_custom_targeting_key_sync.py", + "description": "Sample for BatchCreateDaiAuthenticationKeys", + "file": "admanager_v1_generated_dai_authentication_key_service_batch_create_dai_authentication_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingKeyService_UpdateCustomTargetingKey_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchCreateDaiAuthenticationKeys_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -9948,51 +11536,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_key_service_update_custom_targeting_key_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_batch_create_dai_authentication_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_activate_custom_targeting_values", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_deactivate_dai_authentication_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchActivateCustomTargetingValues", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchDeactivateDaiAuthenticationKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "BatchActivateCustomTargetingValues" + "shortName": "BatchDeactivateDaiAuthenticationKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateDaiAuthenticationKeysRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.ActivateCustomTargetingValueRequest]" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -10007,22 +11595,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateCustomTargetingValuesResponse", - "shortName": "batch_activate_custom_targeting_values" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateDaiAuthenticationKeysResponse", + "shortName": "batch_deactivate_dai_authentication_keys" }, - "description": "Sample for BatchActivateCustomTargetingValues", - "file": "admanager_v1_generated_custom_targeting_value_service_batch_activate_custom_targeting_values_sync.py", + "description": "Sample for BatchDeactivateDaiAuthenticationKeys", + "file": "admanager_v1_generated_dai_authentication_key_service_batch_deactivate_dai_authentication_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchActivateCustomTargetingValues_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchDeactivateDaiAuthenticationKeys_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10032,43 +11620,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_batch_activate_custom_targeting_values_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_batch_deactivate_dai_authentication_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_create_custom_targeting_values", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_update_dai_authentication_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchCreateCustomTargetingValues", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchUpdateDaiAuthenticationKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "BatchCreateCustomTargetingValues" + "shortName": "BatchUpdateDaiAuthenticationKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateDaiAuthenticationKeysRequest" }, { "name": "parent", @@ -10076,7 +11664,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateCustomTargetingValueRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateDaiAuthenticationKeyRequest]" }, { "name": "retry", @@ -10091,22 +11679,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateCustomTargetingValuesResponse", - "shortName": "batch_create_custom_targeting_values" + "resultType": "google.ads.admanager_v1.types.BatchUpdateDaiAuthenticationKeysResponse", + "shortName": "batch_update_dai_authentication_keys" }, - "description": "Sample for BatchCreateCustomTargetingValues", - "file": "admanager_v1_generated_custom_targeting_value_service_batch_create_custom_targeting_values_sync.py", + "description": "Sample for BatchUpdateDaiAuthenticationKeys", + "file": "admanager_v1_generated_dai_authentication_key_service_batch_update_dai_authentication_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchCreateCustomTargetingValues_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchUpdateDaiAuthenticationKeys_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10116,51 +11704,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_batch_create_custom_targeting_values_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_batch_update_dai_authentication_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_deactivate_custom_targeting_values", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.create_dai_authentication_key", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchDeactivateCustomTargetingValues", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.CreateDaiAuthenticationKey", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "BatchDeactivateCustomTargetingValues" + "shortName": "CreateDaiAuthenticationKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesRequest" + "type": "google.ads.admanager_v1.types.CreateDaiAuthenticationKeyRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.DeactivateCustomTargetingValueRequest]" + "name": "dai_authentication_key", + "type": "google.ads.admanager_v1.types.DaiAuthenticationKey" }, { "name": "retry", @@ -10175,22 +11763,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateCustomTargetingValuesResponse", - "shortName": "batch_deactivate_custom_targeting_values" + "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", + "shortName": "create_dai_authentication_key" }, - "description": "Sample for BatchDeactivateCustomTargetingValues", - "file": "admanager_v1_generated_custom_targeting_value_service_batch_deactivate_custom_targeting_values_sync.py", + "description": "Sample for CreateDaiAuthenticationKey", + "file": "admanager_v1_generated_dai_authentication_key_service_create_dai_authentication_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchDeactivateCustomTargetingValues_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_CreateDaiAuthenticationKey_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10200,52 +11788,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_batch_deactivate_custom_targeting_values_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_create_dai_authentication_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.batch_update_custom_targeting_values", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.get_dai_authentication_key", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.BatchUpdateCustomTargetingValues", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.GetDaiAuthenticationKey", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "BatchUpdateCustomTargetingValues" + "shortName": "GetDaiAuthenticationKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesRequest" + "type": "google.ads.admanager_v1.types.GetDaiAuthenticationKeyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10259,14 +11843,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateCustomTargetingValuesResponse", - "shortName": "batch_update_custom_targeting_values" + "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", + "shortName": "get_dai_authentication_key" }, - "description": "Sample for BatchUpdateCustomTargetingValues", - "file": "admanager_v1_generated_custom_targeting_value_service_batch_update_custom_targeting_values_sync.py", + "description": "Sample for GetDaiAuthenticationKey", + "file": "admanager_v1_generated_dai_authentication_key_service_get_dai_authentication_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_BatchUpdateCustomTargetingValues_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_GetDaiAuthenticationKey_sync", "segments": [ { "end": 51, @@ -10299,37 +11883,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_batch_update_custom_targeting_values_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_get_dai_authentication_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.create_custom_targeting_value", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.list_dai_authentication_keys", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.CreateCustomTargetingValue", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.ListDaiAuthenticationKeys", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "CreateCustomTargetingValue" + "shortName": "ListDaiAuthenticationKeys" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateCustomTargetingValueRequest" + "type": "google.ads.admanager_v1.types.ListDaiAuthenticationKeysRequest" }, { "name": "parent", "type": "str" }, - { - "name": "custom_targeting_value", - "type": "google.ads.admanager_v1.types.CustomTargetingValue" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10343,22 +11923,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", - "shortName": "create_custom_targeting_value" + "resultType": "google.ads.admanager_v1.services.dai_authentication_key_service.pagers.ListDaiAuthenticationKeysPager", + "shortName": "list_dai_authentication_keys" }, - "description": "Sample for CreateCustomTargetingValue", - "file": "admanager_v1_generated_custom_targeting_value_service_create_custom_targeting_value_sync.py", + "description": "Sample for ListDaiAuthenticationKeys", + "file": "admanager_v1_generated_dai_authentication_key_service_list_dai_authentication_keys_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_CreateCustomTargetingValue_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_ListDaiAuthenticationKeys_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -10378,37 +11958,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_create_custom_targeting_value_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_list_dai_authentication_keys_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", + "shortName": "DaiAuthenticationKeyServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.get_custom_targeting_value", + "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.update_dai_authentication_key", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.GetCustomTargetingValue", + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.UpdateDaiAuthenticationKey", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", + "shortName": "DaiAuthenticationKeyService" }, - "shortName": "GetCustomTargetingValue" + "shortName": "UpdateDaiAuthenticationKey" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetCustomTargetingValueRequest" + "type": "google.ads.admanager_v1.types.UpdateDaiAuthenticationKeyRequest" }, { - "name": "name", - "type": "str" + "name": "dai_authentication_key", + "type": "google.ads.admanager_v1.types.DaiAuthenticationKey" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -10423,22 +12007,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", - "shortName": "get_custom_targeting_value" + "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", + "shortName": "update_dai_authentication_key" }, - "description": "Sample for GetCustomTargetingValue", - "file": "admanager_v1_generated_custom_targeting_value_service_get_custom_targeting_value_sync.py", + "description": "Sample for UpdateDaiAuthenticationKey", + "file": "admanager_v1_generated_dai_authentication_key_service_update_dai_authentication_key_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_GetCustomTargetingValue_sync", + "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_UpdateDaiAuthenticationKey_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -10448,48 +12032,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_get_custom_targeting_value_sync.py" + "title": "admanager_v1_generated_dai_authentication_key_service_update_dai_authentication_key_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.list_custom_targeting_values", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_activate_dai_encoding_profiles", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.ListCustomTargetingValues", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchActivateDaiEncodingProfiles", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "ListCustomTargetingValues" + "shortName": "BatchActivateDaiEncodingProfiles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListCustomTargetingValuesRequest" + "type": "google.ads.admanager_v1.types.BatchActivateDaiEncodingProfilesRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.ActivateDaiEncodingProfileRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10503,22 +12091,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.custom_targeting_value_service.pagers.ListCustomTargetingValuesPager", - "shortName": "list_custom_targeting_values" + "resultType": "google.ads.admanager_v1.types.BatchActivateDaiEncodingProfilesResponse", + "shortName": "batch_activate_dai_encoding_profiles" }, - "description": "Sample for ListCustomTargetingValues", - "file": "admanager_v1_generated_custom_targeting_value_service_list_custom_targeting_values_sync.py", + "description": "Sample for BatchActivateDaiEncodingProfiles", + "file": "admanager_v1_generated_dai_encoding_profile_service_batch_activate_dai_encoding_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_ListCustomTargetingValues_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchActivateDaiEncodingProfiles_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10528,51 +12116,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_list_custom_targeting_values_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_batch_activate_dai_encoding_profiles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient", - "shortName": "CustomTargetingValueServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.CustomTargetingValueServiceClient.update_custom_targeting_value", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_archive_dai_encoding_profiles", "method": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService.UpdateCustomTargetingValue", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchArchiveDaiEncodingProfiles", "service": { - "fullName": "google.ads.admanager.v1.CustomTargetingValueService", - "shortName": "CustomTargetingValueService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "UpdateCustomTargetingValue" + "shortName": "BatchArchiveDaiEncodingProfiles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateCustomTargetingValueRequest" + "type": "google.ads.admanager_v1.types.BatchArchiveDaiEncodingProfilesRequest" }, { - "name": "custom_targeting_value", - "type": "google.ads.admanager_v1.types.CustomTargetingValue" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.ArchiveDaiEncodingProfileRequest]" }, { "name": "retry", @@ -10587,22 +12175,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.CustomTargetingValue", - "shortName": "update_custom_targeting_value" + "resultType": "google.ads.admanager_v1.types.BatchArchiveDaiEncodingProfilesResponse", + "shortName": "batch_archive_dai_encoding_profiles" }, - "description": "Sample for UpdateCustomTargetingValue", - "file": "admanager_v1_generated_custom_targeting_value_service_update_custom_targeting_value_sync.py", + "description": "Sample for BatchArchiveDaiEncodingProfiles", + "file": "admanager_v1_generated_dai_encoding_profile_service_batch_archive_dai_encoding_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_CustomTargetingValueService_UpdateCustomTargetingValue_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchArchiveDaiEncodingProfiles_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10612,51 +12200,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_custom_targeting_value_service_update_custom_targeting_value_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_batch_archive_dai_encoding_profiles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_activate_dai_authentication_keys", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_create_dai_encoding_profiles", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchActivateDaiAuthenticationKeys", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchCreateDaiEncodingProfiles", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "BatchActivateDaiAuthenticationKeys" + "shortName": "BatchCreateDaiEncodingProfiles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateDaiAuthenticationKeysRequest" + "type": "google.ads.admanager_v1.types.BatchCreateDaiEncodingProfilesRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateDaiEncodingProfileRequest]" }, { "name": "retry", @@ -10671,22 +12259,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateDaiAuthenticationKeysResponse", - "shortName": "batch_activate_dai_authentication_keys" + "resultType": "google.ads.admanager_v1.types.BatchCreateDaiEncodingProfilesResponse", + "shortName": "batch_create_dai_encoding_profiles" }, - "description": "Sample for BatchActivateDaiAuthenticationKeys", - "file": "admanager_v1_generated_dai_authentication_key_service_batch_activate_dai_authentication_keys_sync.py", + "description": "Sample for BatchCreateDaiEncodingProfiles", + "file": "admanager_v1_generated_dai_encoding_profile_service_batch_create_dai_encoding_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchActivateDaiAuthenticationKeys_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchCreateDaiEncodingProfiles_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -10696,43 +12284,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_batch_activate_dai_authentication_keys_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_batch_create_dai_encoding_profiles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_create_dai_authentication_keys", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_update_dai_encoding_profiles", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchCreateDaiAuthenticationKeys", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchUpdateDaiEncodingProfiles", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "BatchCreateDaiAuthenticationKeys" + "shortName": "BatchUpdateDaiEncodingProfiles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateDaiAuthenticationKeysRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateDaiEncodingProfilesRequest" }, { "name": "parent", @@ -10740,7 +12328,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateDaiAuthenticationKeyRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateDaiEncodingProfileRequest]" }, { "name": "retry", @@ -10755,22 +12343,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateDaiAuthenticationKeysResponse", - "shortName": "batch_create_dai_authentication_keys" + "resultType": "google.ads.admanager_v1.types.BatchUpdateDaiEncodingProfilesResponse", + "shortName": "batch_update_dai_encoding_profiles" }, - "description": "Sample for BatchCreateDaiAuthenticationKeys", - "file": "admanager_v1_generated_dai_authentication_key_service_batch_create_dai_authentication_keys_sync.py", + "description": "Sample for BatchUpdateDaiEncodingProfiles", + "file": "admanager_v1_generated_dai_encoding_profile_service_batch_update_dai_encoding_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchCreateDaiAuthenticationKeys_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchUpdateDaiEncodingProfiles_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10780,51 +12368,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_batch_create_dai_authentication_keys_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_batch_update_dai_encoding_profiles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_deactivate_dai_authentication_keys", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.create_dai_encoding_profile", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchDeactivateDaiAuthenticationKeys", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.CreateDaiEncodingProfile", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "BatchDeactivateDaiAuthenticationKeys" + "shortName": "CreateDaiEncodingProfile" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateDaiAuthenticationKeysRequest" + "type": "google.ads.admanager_v1.types.CreateDaiEncodingProfileRequest" }, { "name": "parent", "type": "str" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "dai_encoding_profile", + "type": "google.ads.admanager_v1.types.DaiEncodingProfile" }, { "name": "retry", @@ -10839,22 +12427,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateDaiAuthenticationKeysResponse", - "shortName": "batch_deactivate_dai_authentication_keys" + "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", + "shortName": "create_dai_encoding_profile" }, - "description": "Sample for BatchDeactivateDaiAuthenticationKeys", - "file": "admanager_v1_generated_dai_authentication_key_service_batch_deactivate_dai_authentication_keys_sync.py", + "description": "Sample for CreateDaiEncodingProfile", + "file": "admanager_v1_generated_dai_encoding_profile_service_create_dai_encoding_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchDeactivateDaiAuthenticationKeys_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_CreateDaiEncodingProfile_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -10864,52 +12452,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_batch_deactivate_dai_authentication_keys_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_create_dai_encoding_profile_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.batch_update_dai_authentication_keys", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.get_dai_encoding_profile", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.BatchUpdateDaiAuthenticationKeys", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.GetDaiEncodingProfile", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "BatchUpdateDaiAuthenticationKeys" + "shortName": "GetDaiEncodingProfile" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateDaiAuthenticationKeysRequest" + "type": "google.ads.admanager_v1.types.GetDaiEncodingProfileRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateDaiAuthenticationKeyRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -10923,14 +12507,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateDaiAuthenticationKeysResponse", - "shortName": "batch_update_dai_authentication_keys" + "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", + "shortName": "get_dai_encoding_profile" }, - "description": "Sample for BatchUpdateDaiAuthenticationKeys", - "file": "admanager_v1_generated_dai_authentication_key_service_batch_update_dai_authentication_keys_sync.py", + "description": "Sample for GetDaiEncodingProfile", + "file": "admanager_v1_generated_dai_encoding_profile_service_get_dai_encoding_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_BatchUpdateDaiAuthenticationKeys_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_GetDaiEncodingProfile_sync", "segments": [ { "end": 51, @@ -10963,37 +12547,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_batch_update_dai_authentication_keys_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_get_dai_encoding_profile_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.create_dai_authentication_key", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.list_dai_encoding_profiles", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.CreateDaiAuthenticationKey", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.ListDaiEncodingProfiles", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "CreateDaiAuthenticationKey" + "shortName": "ListDaiEncodingProfiles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateDaiAuthenticationKeyRequest" + "type": "google.ads.admanager_v1.types.ListDaiEncodingProfilesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "dai_authentication_key", - "type": "google.ads.admanager_v1.types.DaiAuthenticationKey" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11007,22 +12587,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", - "shortName": "create_dai_authentication_key" + "resultType": "google.ads.admanager_v1.services.dai_encoding_profile_service.pagers.ListDaiEncodingProfilesPager", + "shortName": "list_dai_encoding_profiles" }, - "description": "Sample for CreateDaiAuthenticationKey", - "file": "admanager_v1_generated_dai_authentication_key_service_create_dai_authentication_key_sync.py", + "description": "Sample for ListDaiEncodingProfiles", + "file": "admanager_v1_generated_dai_encoding_profile_service_list_dai_encoding_profiles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_CreateDaiAuthenticationKey_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_ListDaiEncodingProfiles_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11042,37 +12622,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_create_dai_authentication_key_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_list_dai_encoding_profiles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", + "shortName": "DaiEncodingProfileServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.get_dai_authentication_key", + "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.update_dai_encoding_profile", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.GetDaiAuthenticationKey", + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.UpdateDaiEncodingProfile", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", + "shortName": "DaiEncodingProfileService" }, - "shortName": "GetDaiAuthenticationKey" + "shortName": "UpdateDaiEncodingProfile" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetDaiAuthenticationKeyRequest" + "type": "google.ads.admanager_v1.types.UpdateDaiEncodingProfileRequest" }, { - "name": "name", - "type": "str" + "name": "dai_encoding_profile", + "type": "google.ads.admanager_v1.types.DaiEncodingProfile" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -11087,22 +12671,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", - "shortName": "get_dai_authentication_key" + "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", + "shortName": "update_dai_encoding_profile" }, - "description": "Sample for GetDaiAuthenticationKey", - "file": "admanager_v1_generated_dai_authentication_key_service_get_dai_authentication_key_sync.py", + "description": "Sample for UpdateDaiEncodingProfile", + "file": "admanager_v1_generated_dai_encoding_profile_service_update_dai_encoding_profile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_GetDaiAuthenticationKey_sync", + "regionTag": "admanager_v1_generated_DaiEncodingProfileService_UpdateDaiEncodingProfile_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -11112,46 +12696,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_get_dai_authentication_key_sync.py" + "title": "admanager_v1_generated_dai_encoding_profile_service_update_dai_encoding_profile_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient", + "shortName": "DeviceCapabilityServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.list_dai_authentication_keys", + "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient.get_device_capability", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.ListDaiAuthenticationKeys", + "fullName": "google.ads.admanager.v1.DeviceCapabilityService.GetDeviceCapability", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DeviceCapabilityService", + "shortName": "DeviceCapabilityService" }, - "shortName": "ListDaiAuthenticationKeys" + "shortName": "GetDeviceCapability" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListDaiAuthenticationKeysRequest" + "type": "google.ads.admanager_v1.types.GetDeviceCapabilityRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -11167,22 +12751,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.dai_authentication_key_service.pagers.ListDaiAuthenticationKeysPager", - "shortName": "list_dai_authentication_keys" + "resultType": "google.ads.admanager_v1.types.DeviceCapability", + "shortName": "get_device_capability" }, - "description": "Sample for ListDaiAuthenticationKeys", - "file": "admanager_v1_generated_dai_authentication_key_service_list_dai_authentication_keys_sync.py", + "description": "Sample for GetDeviceCapability", + "file": "admanager_v1_generated_device_capability_service_get_device_capability_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_ListDaiAuthenticationKeys_sync", + "regionTag": "admanager_v1_generated_DeviceCapabilityService_GetDeviceCapability_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11202,41 +12786,37 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_list_dai_authentication_keys_sync.py" + "title": "admanager_v1_generated_device_capability_service_get_device_capability_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient", - "shortName": "DaiAuthenticationKeyServiceClient" + "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient", + "shortName": "DeviceCapabilityServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiAuthenticationKeyServiceClient.update_dai_authentication_key", + "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient.list_device_capabilities", "method": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService.UpdateDaiAuthenticationKey", + "fullName": "google.ads.admanager.v1.DeviceCapabilityService.ListDeviceCapabilities", "service": { - "fullName": "google.ads.admanager.v1.DaiAuthenticationKeyService", - "shortName": "DaiAuthenticationKeyService" + "fullName": "google.ads.admanager.v1.DeviceCapabilityService", + "shortName": "DeviceCapabilityService" }, - "shortName": "UpdateDaiAuthenticationKey" + "shortName": "ListDeviceCapabilities" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateDaiAuthenticationKeyRequest" - }, - { - "name": "dai_authentication_key", - "type": "google.ads.admanager_v1.types.DaiAuthenticationKey" + "type": "google.ads.admanager_v1.types.ListDeviceCapabilitiesRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -11251,22 +12831,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiAuthenticationKey", - "shortName": "update_dai_authentication_key" + "resultType": "google.ads.admanager_v1.services.device_capability_service.pagers.ListDeviceCapabilitiesPager", + "shortName": "list_device_capabilities" }, - "description": "Sample for UpdateDaiAuthenticationKey", - "file": "admanager_v1_generated_dai_authentication_key_service_update_dai_authentication_key_sync.py", + "description": "Sample for ListDeviceCapabilities", + "file": "admanager_v1_generated_device_capability_service_list_device_capabilities_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiAuthenticationKeyService_UpdateDaiAuthenticationKey_sync", + "regionTag": "admanager_v1_generated_DeviceCapabilityService_ListDeviceCapabilities_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11276,52 +12856,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_authentication_key_service_update_dai_authentication_key_sync.py" + "title": "admanager_v1_generated_device_capability_service_list_device_capabilities_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient", + "shortName": "DeviceCategoryServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_activate_dai_encoding_profiles", + "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient.get_device_category", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchActivateDaiEncodingProfiles", + "fullName": "google.ads.admanager.v1.DeviceCategoryService.GetDeviceCategory", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.DeviceCategoryService", + "shortName": "DeviceCategoryService" }, - "shortName": "BatchActivateDaiEncodingProfiles" + "shortName": "GetDeviceCategory" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateDaiEncodingProfilesRequest" + "type": "google.ads.admanager_v1.types.GetDeviceCategoryRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.ActivateDaiEncodingProfileRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11335,22 +12911,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateDaiEncodingProfilesResponse", - "shortName": "batch_activate_dai_encoding_profiles" + "resultType": "google.ads.admanager_v1.types.DeviceCategory", + "shortName": "get_device_category" }, - "description": "Sample for BatchActivateDaiEncodingProfiles", - "file": "admanager_v1_generated_dai_encoding_profile_service_batch_activate_dai_encoding_profiles_sync.py", + "description": "Sample for GetDeviceCategory", + "file": "admanager_v1_generated_device_category_service_get_device_category_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchActivateDaiEncodingProfiles_sync", + "regionTag": "admanager_v1_generated_DeviceCategoryService_GetDeviceCategory_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11360,52 +12936,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_batch_activate_dai_encoding_profiles_sync.py" + "title": "admanager_v1_generated_device_category_service_get_device_category_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient", + "shortName": "DeviceCategoryServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_archive_dai_encoding_profiles", + "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient.list_device_categories", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchArchiveDaiEncodingProfiles", + "fullName": "google.ads.admanager.v1.DeviceCategoryService.ListDeviceCategories", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.DeviceCategoryService", + "shortName": "DeviceCategoryService" }, - "shortName": "BatchArchiveDaiEncodingProfiles" + "shortName": "ListDeviceCategories" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchArchiveDaiEncodingProfilesRequest" + "type": "google.ads.admanager_v1.types.ListDeviceCategoriesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.ArchiveDaiEncodingProfileRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11419,22 +12991,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchArchiveDaiEncodingProfilesResponse", - "shortName": "batch_archive_dai_encoding_profiles" + "resultType": "google.ads.admanager_v1.services.device_category_service.pagers.ListDeviceCategoriesPager", + "shortName": "list_device_categories" }, - "description": "Sample for BatchArchiveDaiEncodingProfiles", - "file": "admanager_v1_generated_dai_encoding_profile_service_batch_archive_dai_encoding_profiles_sync.py", + "description": "Sample for ListDeviceCategories", + "file": "admanager_v1_generated_device_category_service_list_device_categories_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchArchiveDaiEncodingProfiles_sync", + "regionTag": "admanager_v1_generated_DeviceCategoryService_ListDeviceCategories_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11444,52 +13016,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_batch_archive_dai_encoding_profiles_sync.py" + "title": "admanager_v1_generated_device_category_service_list_device_categories_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient", + "shortName": "DeviceManufacturerServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_create_dai_encoding_profiles", + "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient.get_device_manufacturer", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchCreateDaiEncodingProfiles", + "fullName": "google.ads.admanager.v1.DeviceManufacturerService.GetDeviceManufacturer", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.DeviceManufacturerService", + "shortName": "DeviceManufacturerService" }, - "shortName": "BatchCreateDaiEncodingProfiles" + "shortName": "GetDeviceManufacturer" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateDaiEncodingProfilesRequest" + "type": "google.ads.admanager_v1.types.GetDeviceManufacturerRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateDaiEncodingProfileRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11503,22 +13071,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateDaiEncodingProfilesResponse", - "shortName": "batch_create_dai_encoding_profiles" + "resultType": "google.ads.admanager_v1.types.DeviceManufacturer", + "shortName": "get_device_manufacturer" }, - "description": "Sample for BatchCreateDaiEncodingProfiles", - "file": "admanager_v1_generated_dai_encoding_profile_service_batch_create_dai_encoding_profiles_sync.py", + "description": "Sample for GetDeviceManufacturer", + "file": "admanager_v1_generated_device_manufacturer_service_get_device_manufacturer_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchCreateDaiEncodingProfiles_sync", + "regionTag": "admanager_v1_generated_DeviceManufacturerService_GetDeviceManufacturer_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11528,52 +13096,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_batch_create_dai_encoding_profiles_sync.py" + "title": "admanager_v1_generated_device_manufacturer_service_get_device_manufacturer_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient", + "shortName": "DeviceManufacturerServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.batch_update_dai_encoding_profiles", + "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient.list_device_manufacturers", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.BatchUpdateDaiEncodingProfiles", + "fullName": "google.ads.admanager.v1.DeviceManufacturerService.ListDeviceManufacturers", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.DeviceManufacturerService", + "shortName": "DeviceManufacturerService" }, - "shortName": "BatchUpdateDaiEncodingProfiles" + "shortName": "ListDeviceManufacturers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateDaiEncodingProfilesRequest" + "type": "google.ads.admanager_v1.types.ListDeviceManufacturersRequest" }, { "name": "parent", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateDaiEncodingProfileRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11587,22 +13151,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateDaiEncodingProfilesResponse", - "shortName": "batch_update_dai_encoding_profiles" + "resultType": "google.ads.admanager_v1.services.device_manufacturer_service.pagers.ListDeviceManufacturersPager", + "shortName": "list_device_manufacturers" }, - "description": "Sample for BatchUpdateDaiEncodingProfiles", - "file": "admanager_v1_generated_dai_encoding_profile_service_batch_update_dai_encoding_profiles_sync.py", + "description": "Sample for ListDeviceManufacturers", + "file": "admanager_v1_generated_device_manufacturer_service_list_device_manufacturers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_BatchUpdateDaiEncodingProfiles_sync", + "regionTag": "admanager_v1_generated_DeviceManufacturerService_ListDeviceManufacturers_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -11622,41 +13186,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_batch_update_dai_encoding_profiles_sync.py" + "title": "admanager_v1_generated_device_manufacturer_service_list_device_manufacturers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.create_dai_encoding_profile", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.batch_create_entity_signals_mappings", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.CreateDaiEncodingProfile", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.BatchCreateEntitySignalsMappings", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "CreateDaiEncodingProfile" + "shortName": "BatchCreateEntitySignalsMappings" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateDaiEncodingProfileRequest" + "type": "google.ads.admanager_v1.types.BatchCreateEntitySignalsMappingsRequest" }, { "name": "parent", "type": "str" }, { - "name": "dai_encoding_profile", - "type": "google.ads.admanager_v1.types.DaiEncodingProfile" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateEntitySignalsMappingRequest]" }, { "name": "retry", @@ -11671,22 +13235,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", - "shortName": "create_dai_encoding_profile" + "resultType": "google.ads.admanager_v1.types.BatchCreateEntitySignalsMappingsResponse", + "shortName": "batch_create_entity_signals_mappings" }, - "description": "Sample for CreateDaiEncodingProfile", - "file": "admanager_v1_generated_dai_encoding_profile_service_create_dai_encoding_profile_sync.py", + "description": "Sample for BatchCreateEntitySignalsMappings", + "file": "admanager_v1_generated_entity_signals_mapping_service_batch_create_entity_signals_mappings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_CreateDaiEncodingProfile_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_BatchCreateEntitySignalsMappings_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -11696,48 +13260,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_create_dai_encoding_profile_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_batch_create_entity_signals_mappings_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.get_dai_encoding_profile", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.batch_update_entity_signals_mappings", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.GetDaiEncodingProfile", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.BatchUpdateEntitySignalsMappings", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "GetDaiEncodingProfile" + "shortName": "BatchUpdateEntitySignalsMappings" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetDaiEncodingProfileRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateEntitySignalsMappingsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateEntitySignalsMappingRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11751,22 +13319,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", - "shortName": "get_dai_encoding_profile" + "resultType": "google.ads.admanager_v1.types.BatchUpdateEntitySignalsMappingsResponse", + "shortName": "batch_update_entity_signals_mappings" }, - "description": "Sample for GetDaiEncodingProfile", - "file": "admanager_v1_generated_dai_encoding_profile_service_get_dai_encoding_profile_sync.py", + "description": "Sample for BatchUpdateEntitySignalsMappings", + "file": "admanager_v1_generated_entity_signals_mapping_service_batch_update_entity_signals_mappings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_GetDaiEncodingProfile_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_BatchUpdateEntitySignalsMappings_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11776,48 +13344,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_get_dai_encoding_profile_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_batch_update_entity_signals_mappings_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.list_dai_encoding_profiles", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.create_entity_signals_mapping", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.ListDaiEncodingProfiles", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.CreateEntitySignalsMapping", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "ListDaiEncodingProfiles" + "shortName": "CreateEntitySignalsMapping" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListDaiEncodingProfilesRequest" + "type": "google.ads.admanager_v1.types.CreateEntitySignalsMappingRequest" }, { "name": "parent", "type": "str" }, + { + "name": "entity_signals_mapping", + "type": "google.ads.admanager_v1.types.EntitySignalsMapping" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -11831,22 +13403,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.dai_encoding_profile_service.pagers.ListDaiEncodingProfilesPager", - "shortName": "list_dai_encoding_profiles" + "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", + "shortName": "create_entity_signals_mapping" }, - "description": "Sample for ListDaiEncodingProfiles", - "file": "admanager_v1_generated_dai_encoding_profile_service_list_dai_encoding_profiles_sync.py", + "description": "Sample for CreateEntitySignalsMapping", + "file": "admanager_v1_generated_entity_signals_mapping_service_create_entity_signals_mapping_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_ListDaiEncodingProfiles_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_CreateEntitySignalsMapping_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -11856,51 +13428,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_list_dai_encoding_profiles_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_create_entity_signals_mapping_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient", - "shortName": "DaiEncodingProfileServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DaiEncodingProfileServiceClient.update_dai_encoding_profile", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.get_entity_signals_mapping", "method": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService.UpdateDaiEncodingProfile", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.GetEntitySignalsMapping", "service": { - "fullName": "google.ads.admanager.v1.DaiEncodingProfileService", - "shortName": "DaiEncodingProfileService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "UpdateDaiEncodingProfile" + "shortName": "GetEntitySignalsMapping" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateDaiEncodingProfileRequest" - }, - { - "name": "dai_encoding_profile", - "type": "google.ads.admanager_v1.types.DaiEncodingProfile" + "type": "google.ads.admanager_v1.types.GetEntitySignalsMappingRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -11915,22 +13483,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DaiEncodingProfile", - "shortName": "update_dai_encoding_profile" + "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", + "shortName": "get_entity_signals_mapping" }, - "description": "Sample for UpdateDaiEncodingProfile", - "file": "admanager_v1_generated_dai_encoding_profile_service_update_dai_encoding_profile_sync.py", + "description": "Sample for GetEntitySignalsMapping", + "file": "admanager_v1_generated_entity_signals_mapping_service_get_entity_signals_mapping_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DaiEncodingProfileService_UpdateDaiEncodingProfile_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_GetEntitySignalsMapping_sync", "segments": [ { - "end": 50, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 51, "start": 27, "type": "SHORT" }, @@ -11940,46 +13508,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_dai_encoding_profile_service_update_dai_encoding_profile_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_get_entity_signals_mapping_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient", - "shortName": "DeviceCapabilityServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient.get_device_capability", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.list_entity_signals_mappings", "method": { - "fullName": "google.ads.admanager.v1.DeviceCapabilityService.GetDeviceCapability", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.ListEntitySignalsMappings", "service": { - "fullName": "google.ads.admanager.v1.DeviceCapabilityService", - "shortName": "DeviceCapabilityService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "GetDeviceCapability" + "shortName": "ListEntitySignalsMappings" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetDeviceCapabilityRequest" + "type": "google.ads.admanager_v1.types.ListEntitySignalsMappingsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -11995,22 +13563,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DeviceCapability", - "shortName": "get_device_capability" + "resultType": "google.ads.admanager_v1.services.entity_signals_mapping_service.pagers.ListEntitySignalsMappingsPager", + "shortName": "list_entity_signals_mappings" }, - "description": "Sample for GetDeviceCapability", - "file": "admanager_v1_generated_device_capability_service_get_device_capability_sync.py", + "description": "Sample for ListEntitySignalsMappings", + "file": "admanager_v1_generated_entity_signals_mapping_service_list_entity_signals_mappings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceCapabilityService_GetDeviceCapability_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_ListEntitySignalsMappings_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12030,37 +13598,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_capability_service_get_device_capability_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_list_entity_signals_mappings_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient", - "shortName": "DeviceCapabilityServiceClient" + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", + "shortName": "EntitySignalsMappingServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceCapabilityServiceClient.list_device_capabilities", + "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.update_entity_signals_mapping", "method": { - "fullName": "google.ads.admanager.v1.DeviceCapabilityService.ListDeviceCapabilities", + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.UpdateEntitySignalsMapping", "service": { - "fullName": "google.ads.admanager.v1.DeviceCapabilityService", - "shortName": "DeviceCapabilityService" + "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", + "shortName": "EntitySignalsMappingService" }, - "shortName": "ListDeviceCapabilities" + "shortName": "UpdateEntitySignalsMapping" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListDeviceCapabilitiesRequest" + "type": "google.ads.admanager_v1.types.UpdateEntitySignalsMappingRequest" }, { - "name": "parent", - "type": "str" + "name": "entity_signals_mapping", + "type": "google.ads.admanager_v1.types.EntitySignalsMapping" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -12075,22 +13647,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.device_capability_service.pagers.ListDeviceCapabilitiesPager", - "shortName": "list_device_capabilities" + "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", + "shortName": "update_entity_signals_mapping" }, - "description": "Sample for ListDeviceCapabilities", - "file": "admanager_v1_generated_device_capability_service_list_device_capabilities_sync.py", + "description": "Sample for UpdateEntitySignalsMapping", + "file": "admanager_v1_generated_entity_signals_mapping_service_update_entity_signals_mapping_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceCapabilityService_ListDeviceCapabilities_sync", + "regionTag": "admanager_v1_generated_EntitySignalsMappingService_UpdateEntitySignalsMapping_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -12100,43 +13672,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_capability_service_list_device_capabilities_sync.py" + "title": "admanager_v1_generated_entity_signals_mapping_service_update_entity_signals_mapping_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient", - "shortName": "DeviceCategoryServiceClient" + "fullName": "google.ads.admanager_v1.GeoTargetServiceClient", + "shortName": "GeoTargetServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient.get_device_category", + "fullName": "google.ads.admanager_v1.GeoTargetServiceClient.get_geo_target", "method": { - "fullName": "google.ads.admanager.v1.DeviceCategoryService.GetDeviceCategory", + "fullName": "google.ads.admanager.v1.GeoTargetService.GetGeoTarget", "service": { - "fullName": "google.ads.admanager.v1.DeviceCategoryService", - "shortName": "DeviceCategoryService" + "fullName": "google.ads.admanager.v1.GeoTargetService", + "shortName": "GeoTargetService" }, - "shortName": "GetDeviceCategory" + "shortName": "GetGeoTarget" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetDeviceCategoryRequest" + "type": "google.ads.admanager_v1.types.GetGeoTargetRequest" }, { "name": "name", @@ -12155,14 +13727,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DeviceCategory", - "shortName": "get_device_category" + "resultType": "google.ads.admanager_v1.types.GeoTarget", + "shortName": "get_geo_target" }, - "description": "Sample for GetDeviceCategory", - "file": "admanager_v1_generated_device_category_service_get_device_category_sync.py", + "description": "Sample for GetGeoTarget", + "file": "admanager_v1_generated_geo_target_service_get_geo_target_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceCategoryService_GetDeviceCategory_sync", + "regionTag": "admanager_v1_generated_GeoTargetService_GetGeoTarget_sync", "segments": [ { "end": 51, @@ -12195,28 +13767,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_category_service_get_device_category_sync.py" + "title": "admanager_v1_generated_geo_target_service_get_geo_target_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient", - "shortName": "DeviceCategoryServiceClient" + "fullName": "google.ads.admanager_v1.GeoTargetServiceClient", + "shortName": "GeoTargetServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceCategoryServiceClient.list_device_categories", + "fullName": "google.ads.admanager_v1.GeoTargetServiceClient.list_geo_targets", "method": { - "fullName": "google.ads.admanager.v1.DeviceCategoryService.ListDeviceCategories", + "fullName": "google.ads.admanager.v1.GeoTargetService.ListGeoTargets", "service": { - "fullName": "google.ads.admanager.v1.DeviceCategoryService", - "shortName": "DeviceCategoryService" + "fullName": "google.ads.admanager.v1.GeoTargetService", + "shortName": "GeoTargetService" }, - "shortName": "ListDeviceCategories" + "shortName": "ListGeoTargets" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListDeviceCategoriesRequest" + "type": "google.ads.admanager_v1.types.ListGeoTargetsRequest" }, { "name": "parent", @@ -12235,14 +13807,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.device_category_service.pagers.ListDeviceCategoriesPager", - "shortName": "list_device_categories" + "resultType": "google.ads.admanager_v1.services.geo_target_service.pagers.ListGeoTargetsPager", + "shortName": "list_geo_targets" }, - "description": "Sample for ListDeviceCategories", - "file": "admanager_v1_generated_device_category_service_list_device_categories_sync.py", + "description": "Sample for ListGeoTargets", + "file": "admanager_v1_generated_geo_target_service_list_geo_targets_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceCategoryService_ListDeviceCategories_sync", + "regionTag": "admanager_v1_generated_GeoTargetService_ListGeoTargets_sync", "segments": [ { "end": 52, @@ -12275,33 +13847,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_category_service_list_device_categories_sync.py" + "title": "admanager_v1_generated_geo_target_service_list_geo_targets_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient", - "shortName": "DeviceManufacturerServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient.get_device_manufacturer", + "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_activate_labels", "method": { - "fullName": "google.ads.admanager.v1.DeviceManufacturerService.GetDeviceManufacturer", + "fullName": "google.ads.admanager.v1.LabelService.BatchActivateLabels", "service": { - "fullName": "google.ads.admanager.v1.DeviceManufacturerService", - "shortName": "DeviceManufacturerService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "GetDeviceManufacturer" + "shortName": "BatchActivateLabels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetDeviceManufacturerRequest" + "type": "google.ads.admanager_v1.types.BatchActivateLabelsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -12315,22 +13891,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.DeviceManufacturer", - "shortName": "get_device_manufacturer" + "resultType": "google.ads.admanager_v1.types.BatchActivateLabelsResponse", + "shortName": "batch_activate_labels" }, - "description": "Sample for GetDeviceManufacturer", - "file": "admanager_v1_generated_device_manufacturer_service_get_device_manufacturer_sync.py", + "description": "Sample for BatchActivateLabels", + "file": "admanager_v1_generated_label_service_batch_activate_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceManufacturerService_GetDeviceManufacturer_sync", + "regionTag": "admanager_v1_generated_LabelService_BatchActivateLabels_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12340,48 +13916,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_manufacturer_service_get_device_manufacturer_sync.py" + "title": "admanager_v1_generated_label_service_batch_activate_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient", - "shortName": "DeviceManufacturerServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.DeviceManufacturerServiceClient.list_device_manufacturers", + "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_create_labels", "method": { - "fullName": "google.ads.admanager.v1.DeviceManufacturerService.ListDeviceManufacturers", + "fullName": "google.ads.admanager.v1.LabelService.BatchCreateLabels", "service": { - "fullName": "google.ads.admanager.v1.DeviceManufacturerService", - "shortName": "DeviceManufacturerService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "ListDeviceManufacturers" + "shortName": "BatchCreateLabels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListDeviceManufacturersRequest" + "type": "google.ads.admanager_v1.types.BatchCreateLabelsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateLabelRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -12395,22 +13975,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.device_manufacturer_service.pagers.ListDeviceManufacturersPager", - "shortName": "list_device_manufacturers" + "resultType": "google.ads.admanager_v1.types.BatchCreateLabelsResponse", + "shortName": "batch_create_labels" }, - "description": "Sample for ListDeviceManufacturers", - "file": "admanager_v1_generated_device_manufacturer_service_list_device_manufacturers_sync.py", + "description": "Sample for BatchCreateLabels", + "file": "admanager_v1_generated_label_service_batch_create_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_DeviceManufacturerService_ListDeviceManufacturers_sync", + "regionTag": "admanager_v1_generated_LabelService_BatchCreateLabels_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -12420,51 +14000,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_device_manufacturer_service_list_device_manufacturers_sync.py" + "title": "admanager_v1_generated_label_service_batch_create_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.batch_create_entity_signals_mappings", + "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_deactivate_labels", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.BatchCreateEntitySignalsMappings", + "fullName": "google.ads.admanager.v1.LabelService.BatchDeactivateLabels", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "BatchCreateEntitySignalsMappings" + "shortName": "BatchDeactivateLabels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateEntitySignalsMappingsRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateLabelsRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateEntitySignalsMappingRequest]" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -12479,22 +14059,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateEntitySignalsMappingsResponse", - "shortName": "batch_create_entity_signals_mappings" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateLabelsResponse", + "shortName": "batch_deactivate_labels" }, - "description": "Sample for BatchCreateEntitySignalsMappings", - "file": "admanager_v1_generated_entity_signals_mapping_service_batch_create_entity_signals_mappings_sync.py", + "description": "Sample for BatchDeactivateLabels", + "file": "admanager_v1_generated_label_service_batch_deactivate_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_BatchCreateEntitySignalsMappings_sync", + "regionTag": "admanager_v1_generated_LabelService_BatchDeactivateLabels_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -12504,43 +14084,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_batch_create_entity_signals_mappings_sync.py" + "title": "admanager_v1_generated_label_service_batch_deactivate_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.batch_update_entity_signals_mappings", + "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_update_labels", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.BatchUpdateEntitySignalsMappings", + "fullName": "google.ads.admanager.v1.LabelService.BatchUpdateLabels", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "BatchUpdateEntitySignalsMappings" + "shortName": "BatchUpdateLabels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateEntitySignalsMappingsRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateLabelsRequest" }, { "name": "parent", @@ -12548,7 +14128,7 @@ }, { "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateEntitySignalsMappingRequest]" + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateLabelRequest]" }, { "name": "retry", @@ -12563,14 +14143,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateEntitySignalsMappingsResponse", - "shortName": "batch_update_entity_signals_mappings" + "resultType": "google.ads.admanager_v1.types.BatchUpdateLabelsResponse", + "shortName": "batch_update_labels" }, - "description": "Sample for BatchUpdateEntitySignalsMappings", - "file": "admanager_v1_generated_entity_signals_mapping_service_batch_update_entity_signals_mappings_sync.py", + "description": "Sample for BatchUpdateLabels", + "file": "admanager_v1_generated_label_service_batch_update_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_BatchUpdateEntitySignalsMappings_sync", + "regionTag": "admanager_v1_generated_LabelService_BatchUpdateLabels_sync", "segments": [ { "end": 55, @@ -12603,36 +14183,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_batch_update_entity_signals_mappings_sync.py" + "title": "admanager_v1_generated_label_service_batch_update_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.create_entity_signals_mapping", + "fullName": "google.ads.admanager_v1.LabelServiceClient.create_label", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.CreateEntitySignalsMapping", + "fullName": "google.ads.admanager.v1.LabelService.CreateLabel", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "CreateEntitySignalsMapping" + "shortName": "CreateLabel" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateEntitySignalsMappingRequest" + "type": "google.ads.admanager_v1.types.CreateLabelRequest" }, { "name": "parent", "type": "str" }, { - "name": "entity_signals_mapping", - "type": "google.ads.admanager_v1.types.EntitySignalsMapping" + "name": "label", + "type": "google.ads.admanager_v1.types.Label" }, { "name": "retry", @@ -12647,14 +14227,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", - "shortName": "create_entity_signals_mapping" + "resultType": "google.ads.admanager_v1.types.Label", + "shortName": "create_label" }, - "description": "Sample for CreateEntitySignalsMapping", - "file": "admanager_v1_generated_entity_signals_mapping_service_create_entity_signals_mapping_sync.py", + "description": "Sample for CreateLabel", + "file": "admanager_v1_generated_label_service_create_label_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_CreateEntitySignalsMapping_sync", + "regionTag": "admanager_v1_generated_LabelService_CreateLabel_sync", "segments": [ { "end": 55, @@ -12687,28 +14267,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_create_entity_signals_mapping_sync.py" + "title": "admanager_v1_generated_label_service_create_label_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.get_entity_signals_mapping", + "fullName": "google.ads.admanager_v1.LabelServiceClient.get_label", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.GetEntitySignalsMapping", + "fullName": "google.ads.admanager.v1.LabelService.GetLabel", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "GetEntitySignalsMapping" + "shortName": "GetLabel" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetEntitySignalsMappingRequest" + "type": "google.ads.admanager_v1.types.GetLabelRequest" }, { "name": "name", @@ -12727,14 +14307,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", - "shortName": "get_entity_signals_mapping" + "resultType": "google.ads.admanager_v1.types.Label", + "shortName": "get_label" }, - "description": "Sample for GetEntitySignalsMapping", - "file": "admanager_v1_generated_entity_signals_mapping_service_get_entity_signals_mapping_sync.py", + "description": "Sample for GetLabel", + "file": "admanager_v1_generated_label_service_get_label_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_GetEntitySignalsMapping_sync", + "regionTag": "admanager_v1_generated_LabelService_GetLabel_sync", "segments": [ { "end": 51, @@ -12767,28 +14347,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_get_entity_signals_mapping_sync.py" + "title": "admanager_v1_generated_label_service_get_label_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.list_entity_signals_mappings", + "fullName": "google.ads.admanager_v1.LabelServiceClient.list_labels", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.ListEntitySignalsMappings", + "fullName": "google.ads.admanager.v1.LabelService.ListLabels", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "ListEntitySignalsMappings" + "shortName": "ListLabels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListEntitySignalsMappingsRequest" + "type": "google.ads.admanager_v1.types.ListLabelsRequest" }, { "name": "parent", @@ -12807,14 +14387,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.entity_signals_mapping_service.pagers.ListEntitySignalsMappingsPager", - "shortName": "list_entity_signals_mappings" + "resultType": "google.ads.admanager_v1.services.label_service.pagers.ListLabelsPager", + "shortName": "list_labels" }, - "description": "Sample for ListEntitySignalsMappings", - "file": "admanager_v1_generated_entity_signals_mapping_service_list_entity_signals_mappings_sync.py", + "description": "Sample for ListLabels", + "file": "admanager_v1_generated_label_service_list_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_ListEntitySignalsMappings_sync", + "regionTag": "admanager_v1_generated_LabelService_ListLabels_sync", "segments": [ { "end": 52, @@ -12847,32 +14427,32 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_list_entity_signals_mappings_sync.py" + "title": "admanager_v1_generated_label_service_list_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient", - "shortName": "EntitySignalsMappingServiceClient" + "fullName": "google.ads.admanager_v1.LabelServiceClient", + "shortName": "LabelServiceClient" }, - "fullName": "google.ads.admanager_v1.EntitySignalsMappingServiceClient.update_entity_signals_mapping", + "fullName": "google.ads.admanager_v1.LabelServiceClient.update_label", "method": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService.UpdateEntitySignalsMapping", + "fullName": "google.ads.admanager.v1.LabelService.UpdateLabel", "service": { - "fullName": "google.ads.admanager.v1.EntitySignalsMappingService", - "shortName": "EntitySignalsMappingService" + "fullName": "google.ads.admanager.v1.LabelService", + "shortName": "LabelService" }, - "shortName": "UpdateEntitySignalsMapping" + "shortName": "UpdateLabel" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateEntitySignalsMappingRequest" + "type": "google.ads.admanager_v1.types.UpdateLabelRequest" }, { - "name": "entity_signals_mapping", - "type": "google.ads.admanager_v1.types.EntitySignalsMapping" + "name": "label", + "type": "google.ads.admanager_v1.types.Label" }, { "name": "update_mask", @@ -12891,14 +14471,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.EntitySignalsMapping", - "shortName": "update_entity_signals_mapping" + "resultType": "google.ads.admanager_v1.types.Label", + "shortName": "update_label" }, - "description": "Sample for UpdateEntitySignalsMapping", - "file": "admanager_v1_generated_entity_signals_mapping_service_update_entity_signals_mapping_sync.py", + "description": "Sample for UpdateLabel", + "file": "admanager_v1_generated_label_service_update_label_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_EntitySignalsMappingService_UpdateEntitySignalsMapping_sync", + "regionTag": "admanager_v1_generated_LabelService_UpdateLabel_sync", "segments": [ { "end": 54, @@ -12931,28 +14511,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_entity_signals_mapping_service_update_entity_signals_mapping_sync.py" + "title": "admanager_v1_generated_label_service_update_label_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.GeoTargetServiceClient", - "shortName": "GeoTargetServiceClient" + "fullName": "google.ads.admanager_v1.LineItemServiceClient", + "shortName": "LineItemServiceClient" }, - "fullName": "google.ads.admanager_v1.GeoTargetServiceClient.get_geo_target", + "fullName": "google.ads.admanager_v1.LineItemServiceClient.get_line_item", "method": { - "fullName": "google.ads.admanager.v1.GeoTargetService.GetGeoTarget", + "fullName": "google.ads.admanager.v1.LineItemService.GetLineItem", "service": { - "fullName": "google.ads.admanager.v1.GeoTargetService", - "shortName": "GeoTargetService" + "fullName": "google.ads.admanager.v1.LineItemService", + "shortName": "LineItemService" }, - "shortName": "GetGeoTarget" + "shortName": "GetLineItem" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetGeoTargetRequest" + "type": "google.ads.admanager_v1.types.GetLineItemRequest" }, { "name": "name", @@ -12971,14 +14551,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.GeoTarget", - "shortName": "get_geo_target" + "resultType": "google.ads.admanager_v1.types.LineItem", + "shortName": "get_line_item" }, - "description": "Sample for GetGeoTarget", - "file": "admanager_v1_generated_geo_target_service_get_geo_target_sync.py", + "description": "Sample for GetLineItem", + "file": "admanager_v1_generated_line_item_service_get_line_item_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_GeoTargetService_GetGeoTarget_sync", + "regionTag": "admanager_v1_generated_LineItemService_GetLineItem_sync", "segments": [ { "end": 51, @@ -13011,28 +14591,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_geo_target_service_get_geo_target_sync.py" + "title": "admanager_v1_generated_line_item_service_get_line_item_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.GeoTargetServiceClient", - "shortName": "GeoTargetServiceClient" + "fullName": "google.ads.admanager_v1.LineItemServiceClient", + "shortName": "LineItemServiceClient" }, - "fullName": "google.ads.admanager_v1.GeoTargetServiceClient.list_geo_targets", + "fullName": "google.ads.admanager_v1.LineItemServiceClient.list_line_items", "method": { - "fullName": "google.ads.admanager.v1.GeoTargetService.ListGeoTargets", + "fullName": "google.ads.admanager.v1.LineItemService.ListLineItems", "service": { - "fullName": "google.ads.admanager.v1.GeoTargetService", - "shortName": "GeoTargetService" + "fullName": "google.ads.admanager.v1.LineItemService", + "shortName": "LineItemService" }, - "shortName": "ListGeoTargets" + "shortName": "ListLineItems" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListGeoTargetsRequest" + "type": "google.ads.admanager_v1.types.ListLineItemsRequest" }, { "name": "parent", @@ -13051,14 +14631,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.geo_target_service.pagers.ListGeoTargetsPager", - "shortName": "list_geo_targets" + "resultType": "google.ads.admanager_v1.services.line_item_service.pagers.ListLineItemsPager", + "shortName": "list_line_items" }, - "description": "Sample for ListGeoTargets", - "file": "admanager_v1_generated_geo_target_service_list_geo_targets_sync.py", + "description": "Sample for ListLineItems", + "file": "admanager_v1_generated_line_item_service_list_line_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_GeoTargetService_ListGeoTargets_sync", + "regionTag": "admanager_v1_generated_LineItemService_ListLineItems_sync", "segments": [ { "end": 52, @@ -13091,37 +14671,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_geo_target_service_list_geo_targets_sync.py" + "title": "admanager_v1_generated_line_item_service_list_line_items_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient", + "shortName": "LinkedDeviceServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_activate_labels", + "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient.get_linked_device", "method": { - "fullName": "google.ads.admanager.v1.LabelService.BatchActivateLabels", + "fullName": "google.ads.admanager.v1.LinkedDeviceService.GetLinkedDevice", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LinkedDeviceService", + "shortName": "LinkedDeviceService" }, - "shortName": "BatchActivateLabels" + "shortName": "GetLinkedDevice" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateLabelsRequest" + "type": "google.ads.admanager_v1.types.GetLinkedDeviceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13135,22 +14711,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateLabelsResponse", - "shortName": "batch_activate_labels" + "resultType": "google.ads.admanager_v1.types.LinkedDevice", + "shortName": "get_linked_device" }, - "description": "Sample for BatchActivateLabels", - "file": "admanager_v1_generated_label_service_batch_activate_labels_sync.py", + "description": "Sample for GetLinkedDevice", + "file": "admanager_v1_generated_linked_device_service_get_linked_device_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_BatchActivateLabels_sync", + "regionTag": "admanager_v1_generated_LinkedDeviceService_GetLinkedDevice_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -13160,52 +14736,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_batch_activate_labels_sync.py" + "title": "admanager_v1_generated_linked_device_service_get_linked_device_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient", + "shortName": "LinkedDeviceServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_create_labels", + "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient.list_linked_devices", "method": { - "fullName": "google.ads.admanager.v1.LabelService.BatchCreateLabels", + "fullName": "google.ads.admanager.v1.LinkedDeviceService.ListLinkedDevices", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LinkedDeviceService", + "shortName": "LinkedDeviceService" }, - "shortName": "BatchCreateLabels" + "shortName": "ListLinkedDevices" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateLabelsRequest" + "type": "google.ads.admanager_v1.types.ListLinkedDevicesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateLabelRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13219,22 +14791,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateLabelsResponse", - "shortName": "batch_create_labels" + "resultType": "google.ads.admanager_v1.services.linked_device_service.pagers.ListLinkedDevicesPager", + "shortName": "list_linked_devices" }, - "description": "Sample for BatchCreateLabels", - "file": "admanager_v1_generated_label_service_batch_create_labels_sync.py", + "description": "Sample for ListLinkedDevices", + "file": "admanager_v1_generated_linked_device_service_list_linked_devices_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_BatchCreateLabels_sync", + "regionTag": "admanager_v1_generated_LinkedDeviceService_ListLinkedDevices_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13244,43 +14816,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_batch_create_labels_sync.py" + "title": "admanager_v1_generated_linked_device_service_list_linked_devices_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_deactivate_labels", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_activate_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LabelService.BatchDeactivateLabels", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchActivateLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "BatchDeactivateLabels" + "shortName": "BatchActivateLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchDeactivateLabelsRequest" + "type": "google.ads.admanager_v1.types.BatchActivateLiveStreamsRequest" }, { "name": "parent", @@ -13303,14 +14875,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchDeactivateLabelsResponse", - "shortName": "batch_deactivate_labels" + "resultType": "google.ads.admanager_v1.types.BatchActivateLiveStreamsResponse", + "shortName": "batch_activate_live_streams" }, - "description": "Sample for BatchDeactivateLabels", - "file": "admanager_v1_generated_label_service_batch_deactivate_labels_sync.py", + "description": "Sample for BatchActivateLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_activate_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_BatchDeactivateLabels_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchActivateLiveStreams_sync", "segments": [ { "end": 52, @@ -13343,36 +14915,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_batch_deactivate_labels_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_activate_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.batch_update_labels", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_archive_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LabelService.BatchUpdateLabels", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchArchiveLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "BatchUpdateLabels" + "shortName": "BatchArchiveLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateLabelsRequest" + "type": "google.ads.admanager_v1.types.BatchArchiveLiveStreamsRequest" }, { "name": "parent", "type": "str" }, { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateLabelRequest]" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -13387,22 +14959,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateLabelsResponse", - "shortName": "batch_update_labels" + "resultType": "google.ads.admanager_v1.types.BatchArchiveLiveStreamsResponse", + "shortName": "batch_archive_live_streams" }, - "description": "Sample for BatchUpdateLabels", - "file": "admanager_v1_generated_label_service_batch_update_labels_sync.py", + "description": "Sample for BatchArchiveLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_archive_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_BatchUpdateLabels_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchArchiveLiveStreams_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13412,51 +14984,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_batch_update_labels_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_archive_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.create_label", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_create_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LabelService.CreateLabel", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchCreateLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "CreateLabel" + "shortName": "BatchCreateLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateLabelRequest" + "type": "google.ads.admanager_v1.types.BatchCreateLiveStreamsRequest" }, { "name": "parent", "type": "str" }, { - "name": "label", - "type": "google.ads.admanager_v1.types.Label" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateLiveStreamRequest]" }, { "name": "retry", @@ -13471,22 +15043,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Label", - "shortName": "create_label" + "resultType": "google.ads.admanager_v1.types.BatchCreateLiveStreamsResponse", + "shortName": "batch_create_live_streams" }, - "description": "Sample for CreateLabel", - "file": "admanager_v1_generated_label_service_create_label_sync.py", + "description": "Sample for BatchCreateLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_create_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_CreateLabel_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchCreateLiveStreams_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -13496,48 +15068,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_create_label_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_create_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.get_label", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_pause_ads_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LabelService.GetLabel", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchPauseAdsLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "GetLabel" + "shortName": "BatchPauseAdsLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetLabelRequest" + "type": "google.ads.admanager_v1.types.BatchPauseAdsLiveStreamsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13551,22 +15127,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Label", - "shortName": "get_label" + "resultType": "google.ads.admanager_v1.types.BatchPauseAdsLiveStreamsResponse", + "shortName": "batch_pause_ads_live_streams" }, - "description": "Sample for GetLabel", - "file": "admanager_v1_generated_label_service_get_label_sync.py", + "description": "Sample for BatchPauseAdsLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_pause_ads_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_GetLabel_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchPauseAdsLiveStreams_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13576,48 +15152,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_get_label_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_pause_ads_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.list_labels", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_pause_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LabelService.ListLabels", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchPauseLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "ListLabels" + "shortName": "BatchPauseLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListLabelsRequest" + "type": "google.ads.admanager_v1.types.BatchPauseLiveStreamsRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13631,14 +15211,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.label_service.pagers.ListLabelsPager", - "shortName": "list_labels" + "resultType": "google.ads.admanager_v1.types.BatchPauseLiveStreamsResponse", + "shortName": "batch_pause_live_streams" }, - "description": "Sample for ListLabels", - "file": "admanager_v1_generated_label_service_list_labels_sync.py", + "description": "Sample for BatchPauseLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_pause_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_ListLabels_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchPauseLiveStreams_sync", "segments": [ { "end": 52, @@ -13656,51 +15236,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_list_labels_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_pause_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LabelServiceClient", - "shortName": "LabelServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LabelServiceClient.update_label", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_refresh_master_playlists", "method": { - "fullName": "google.ads.admanager.v1.LabelService.UpdateLabel", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchRefreshMasterPlaylists", "service": { - "fullName": "google.ads.admanager.v1.LabelService", - "shortName": "LabelService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "UpdateLabel" + "shortName": "BatchRefreshMasterPlaylists" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateLabelRequest" + "type": "google.ads.admanager_v1.types.BatchRefreshMasterPlaylistsRequest" }, { - "name": "label", - "type": "google.ads.admanager_v1.types.Label" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "names", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -13715,22 +15295,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.Label", - "shortName": "update_label" + "resultType": "google.ads.admanager_v1.types.BatchRefreshMasterPlaylistsResponse", + "shortName": "batch_refresh_master_playlists" }, - "description": "Sample for UpdateLabel", - "file": "admanager_v1_generated_label_service_update_label_sync.py", + "description": "Sample for BatchRefreshMasterPlaylists", + "file": "admanager_v1_generated_live_stream_service_batch_refresh_master_playlists_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LabelService_UpdateLabel_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchRefreshMasterPlaylists_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13740,48 +15320,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_label_service_update_label_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_refresh_master_playlists_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LineItemServiceClient", - "shortName": "LineItemServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LineItemServiceClient.get_line_item", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_update_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LineItemService.GetLineItem", + "fullName": "google.ads.admanager.v1.LiveStreamService.BatchUpdateLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LineItemService", - "shortName": "LineItemService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "GetLineItem" + "shortName": "BatchUpdateLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetLineItemRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateLiveStreamsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateLiveStreamRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13795,22 +15379,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.LineItem", - "shortName": "get_line_item" + "resultType": "google.ads.admanager_v1.types.BatchUpdateLiveStreamsResponse", + "shortName": "batch_update_live_streams" }, - "description": "Sample for GetLineItem", - "file": "admanager_v1_generated_line_item_service_get_line_item_sync.py", + "description": "Sample for BatchUpdateLiveStreams", + "file": "admanager_v1_generated_live_stream_service_batch_update_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LineItemService_GetLineItem_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_BatchUpdateLiveStreams_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -13820,48 +15404,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_line_item_service_get_line_item_sync.py" + "title": "admanager_v1_generated_live_stream_service_batch_update_live_streams_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LineItemServiceClient", - "shortName": "LineItemServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LineItemServiceClient.list_line_items", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.create_live_stream", "method": { - "fullName": "google.ads.admanager.v1.LineItemService.ListLineItems", + "fullName": "google.ads.admanager.v1.LiveStreamService.CreateLiveStream", "service": { - "fullName": "google.ads.admanager.v1.LineItemService", - "shortName": "LineItemService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "ListLineItems" + "shortName": "CreateLiveStream" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListLineItemsRequest" + "type": "google.ads.admanager_v1.types.CreateLiveStreamRequest" }, { "name": "parent", "type": "str" }, + { + "name": "live_stream", + "type": "google.ads.admanager_v1.types.LiveStream" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13875,22 +15463,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.line_item_service.pagers.ListLineItemsPager", - "shortName": "list_line_items" + "resultType": "google.ads.admanager_v1.types.LiveStream", + "shortName": "create_live_stream" }, - "description": "Sample for ListLineItems", - "file": "admanager_v1_generated_line_item_service_list_line_items_sync.py", + "description": "Sample for CreateLiveStream", + "file": "admanager_v1_generated_live_stream_service_create_live_stream_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LineItemService_ListLineItems_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_CreateLiveStream_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -13900,43 +15488,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_line_item_service_list_line_items_sync.py" + "title": "admanager_v1_generated_live_stream_service_create_live_stream_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient", - "shortName": "LinkedDeviceServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient.get_linked_device", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.get_live_stream", "method": { - "fullName": "google.ads.admanager.v1.LinkedDeviceService.GetLinkedDevice", + "fullName": "google.ads.admanager.v1.LiveStreamService.GetLiveStream", "service": { - "fullName": "google.ads.admanager.v1.LinkedDeviceService", - "shortName": "LinkedDeviceService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "GetLinkedDevice" + "shortName": "GetLiveStream" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetLinkedDeviceRequest" + "type": "google.ads.admanager_v1.types.GetLiveStreamRequest" }, { "name": "name", @@ -13955,14 +15543,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.LinkedDevice", - "shortName": "get_linked_device" + "resultType": "google.ads.admanager_v1.types.LiveStream", + "shortName": "get_live_stream" }, - "description": "Sample for GetLinkedDevice", - "file": "admanager_v1_generated_linked_device_service_get_linked_device_sync.py", + "description": "Sample for GetLiveStream", + "file": "admanager_v1_generated_live_stream_service_get_live_stream_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LinkedDeviceService_GetLinkedDevice_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_GetLiveStream_sync", "segments": [ { "end": 51, @@ -13995,28 +15583,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_linked_device_service_get_linked_device_sync.py" + "title": "admanager_v1_generated_live_stream_service_get_live_stream_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient", - "shortName": "LinkedDeviceServiceClient" + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", + "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LinkedDeviceServiceClient.list_linked_devices", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.list_live_streams", "method": { - "fullName": "google.ads.admanager.v1.LinkedDeviceService.ListLinkedDevices", + "fullName": "google.ads.admanager.v1.LiveStreamService.ListLiveStreams", "service": { - "fullName": "google.ads.admanager.v1.LinkedDeviceService", - "shortName": "LinkedDeviceService" + "fullName": "google.ads.admanager.v1.LiveStreamService", + "shortName": "LiveStreamService" }, - "shortName": "ListLinkedDevices" + "shortName": "ListLiveStreams" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListLinkedDevicesRequest" + "type": "google.ads.admanager_v1.types.ListLiveStreamsRequest" }, { "name": "parent", @@ -14035,14 +15623,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.linked_device_service.pagers.ListLinkedDevicesPager", - "shortName": "list_linked_devices" + "resultType": "google.ads.admanager_v1.services.live_stream_service.pagers.ListLiveStreamsPager", + "shortName": "list_live_streams" }, - "description": "Sample for ListLinkedDevices", - "file": "admanager_v1_generated_linked_device_service_list_linked_devices_sync.py", + "description": "Sample for ListLiveStreams", + "file": "admanager_v1_generated_live_stream_service_list_live_streams_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LinkedDeviceService_ListLinkedDevices_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_ListLiveStreams_sync", "segments": [ { "end": 52, @@ -14075,7 +15663,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_linked_device_service_list_linked_devices_sync.py" + "title": "admanager_v1_generated_live_stream_service_list_live_streams_sync.py" }, { "canonical": true, @@ -14084,27 +15672,27 @@ "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", "shortName": "LiveStreamServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_activate_live_streams", + "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.update_live_stream", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchActivateLiveStreams", + "fullName": "google.ads.admanager.v1.LiveStreamService.UpdateLiveStream", "service": { "fullName": "google.ads.admanager.v1.LiveStreamService", "shortName": "LiveStreamService" }, - "shortName": "BatchActivateLiveStreams" + "shortName": "UpdateLiveStream" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchActivateLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.UpdateLiveStreamRequest" }, { - "name": "parent", - "type": "str" + "name": "live_stream", + "type": "google.ads.admanager_v1.types.LiveStream" }, { - "name": "names", - "type": "MutableSequence[str]" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -14119,22 +15707,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchActivateLiveStreamsResponse", - "shortName": "batch_activate_live_streams" + "resultType": "google.ads.admanager_v1.types.LiveStream", + "shortName": "update_live_stream" }, - "description": "Sample for BatchActivateLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_activate_live_streams_sync.py", + "description": "Sample for UpdateLiveStream", + "file": "admanager_v1_generated_live_stream_service_update_live_stream_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchActivateLiveStreams_sync", + "regionTag": "admanager_v1_generated_LiveStreamService_UpdateLiveStream_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -14144,52 +15732,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_activate_live_streams_sync.py" + "title": "admanager_v1_generated_live_stream_service_update_live_stream_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.McmEarningsServiceClient", + "shortName": "McmEarningsServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_archive_live_streams", + "fullName": "google.ads.admanager_v1.McmEarningsServiceClient.fetch_mcm_earnings", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchArchiveLiveStreams", + "fullName": "google.ads.admanager.v1.McmEarningsService.FetchMcmEarnings", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.McmEarningsService", + "shortName": "McmEarningsService" }, - "shortName": "BatchArchiveLiveStreams" + "shortName": "FetchMcmEarnings" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchArchiveLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.FetchMcmEarningsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14203,14 +15787,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchArchiveLiveStreamsResponse", - "shortName": "batch_archive_live_streams" + "resultType": "google.ads.admanager_v1.services.mcm_earnings_service.pagers.FetchMcmEarningsPager", + "shortName": "fetch_mcm_earnings" }, - "description": "Sample for BatchArchiveLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_archive_live_streams_sync.py", + "description": "Sample for FetchMcmEarnings", + "file": "admanager_v1_generated_mcm_earnings_service_fetch_mcm_earnings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchArchiveLiveStreams_sync", + "regionTag": "admanager_v1_generated_McmEarningsService_FetchMcmEarnings_sync", "segments": [ { "end": 52, @@ -14228,52 +15812,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_archive_live_streams_sync.py" + "title": "admanager_v1_generated_mcm_earnings_service_fetch_mcm_earnings_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient", + "shortName": "MobileCarrierServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_create_live_streams", + "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient.get_mobile_carrier", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchCreateLiveStreams", + "fullName": "google.ads.admanager.v1.MobileCarrierService.GetMobileCarrier", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileCarrierService", + "shortName": "MobileCarrierService" }, - "shortName": "BatchCreateLiveStreams" + "shortName": "GetMobileCarrier" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchCreateLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.GetMobileCarrierRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.CreateLiveStreamRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14287,22 +15867,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchCreateLiveStreamsResponse", - "shortName": "batch_create_live_streams" + "resultType": "google.ads.admanager_v1.types.MobileCarrier", + "shortName": "get_mobile_carrier" }, - "description": "Sample for BatchCreateLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_create_live_streams_sync.py", + "description": "Sample for GetMobileCarrier", + "file": "admanager_v1_generated_mobile_carrier_service_get_mobile_carrier_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchCreateLiveStreams_sync", + "regionTag": "admanager_v1_generated_MobileCarrierService_GetMobileCarrier_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14312,52 +15892,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_create_live_streams_sync.py" + "title": "admanager_v1_generated_mobile_carrier_service_get_mobile_carrier_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient", + "shortName": "MobileCarrierServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_pause_ads_live_streams", + "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient.list_mobile_carriers", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchPauseAdsLiveStreams", + "fullName": "google.ads.admanager.v1.MobileCarrierService.ListMobileCarriers", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileCarrierService", + "shortName": "MobileCarrierService" }, - "shortName": "BatchPauseAdsLiveStreams" + "shortName": "ListMobileCarriers" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchPauseAdsLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.ListMobileCarriersRequest" }, { "name": "parent", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14371,14 +15947,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchPauseAdsLiveStreamsResponse", - "shortName": "batch_pause_ads_live_streams" + "resultType": "google.ads.admanager_v1.services.mobile_carrier_service.pagers.ListMobileCarriersPager", + "shortName": "list_mobile_carriers" }, - "description": "Sample for BatchPauseAdsLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_pause_ads_live_streams_sync.py", + "description": "Sample for ListMobileCarriers", + "file": "admanager_v1_generated_mobile_carrier_service_list_mobile_carriers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchPauseAdsLiveStreams_sync", + "regionTag": "admanager_v1_generated_MobileCarrierService_ListMobileCarriers_sync", "segments": [ { "end": 52, @@ -14396,52 +15972,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_pause_ads_live_streams_sync.py" + "title": "admanager_v1_generated_mobile_carrier_service_list_mobile_carriers_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient", + "shortName": "MobileDeviceServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_pause_live_streams", + "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient.get_mobile_device", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchPauseLiveStreams", + "fullName": "google.ads.admanager.v1.MobileDeviceService.GetMobileDevice", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileDeviceService", + "shortName": "MobileDeviceService" }, - "shortName": "BatchPauseLiveStreams" + "shortName": "GetMobileDevice" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchPauseLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.GetMobileDeviceRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14455,22 +16027,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchPauseLiveStreamsResponse", - "shortName": "batch_pause_live_streams" + "resultType": "google.ads.admanager_v1.types.MobileDevice", + "shortName": "get_mobile_device" }, - "description": "Sample for BatchPauseLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_pause_live_streams_sync.py", + "description": "Sample for GetMobileDevice", + "file": "admanager_v1_generated_mobile_device_service_get_mobile_device_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchPauseLiveStreams_sync", + "regionTag": "admanager_v1_generated_MobileDeviceService_GetMobileDevice_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14480,52 +16052,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_pause_live_streams_sync.py" + "title": "admanager_v1_generated_mobile_device_service_get_mobile_device_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient", + "shortName": "MobileDeviceServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_refresh_master_playlists", + "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient.list_mobile_devices", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchRefreshMasterPlaylists", + "fullName": "google.ads.admanager.v1.MobileDeviceService.ListMobileDevices", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileDeviceService", + "shortName": "MobileDeviceService" }, - "shortName": "BatchRefreshMasterPlaylists" + "shortName": "ListMobileDevices" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchRefreshMasterPlaylistsRequest" + "type": "google.ads.admanager_v1.types.ListMobileDevicesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "names", - "type": "MutableSequence[str]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14539,14 +16107,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchRefreshMasterPlaylistsResponse", - "shortName": "batch_refresh_master_playlists" + "resultType": "google.ads.admanager_v1.services.mobile_device_service.pagers.ListMobileDevicesPager", + "shortName": "list_mobile_devices" }, - "description": "Sample for BatchRefreshMasterPlaylists", - "file": "admanager_v1_generated_live_stream_service_batch_refresh_master_playlists_sync.py", + "description": "Sample for ListMobileDevices", + "file": "admanager_v1_generated_mobile_device_service_list_mobile_devices_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchRefreshMasterPlaylists_sync", + "regionTag": "admanager_v1_generated_MobileDeviceService_ListMobileDevices_sync", "segments": [ { "end": 52, @@ -14564,52 +16132,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_refresh_master_playlists_sync.py" + "title": "admanager_v1_generated_mobile_device_service_list_mobile_devices_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient", + "shortName": "MobileDeviceSubmodelServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.batch_update_live_streams", + "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient.get_mobile_device_submodel", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.BatchUpdateLiveStreams", + "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService.GetMobileDeviceSubmodel", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService", + "shortName": "MobileDeviceSubmodelService" }, - "shortName": "BatchUpdateLiveStreams" + "shortName": "GetMobileDeviceSubmodel" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.BatchUpdateLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.GetMobileDeviceSubmodelRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "requests", - "type": "MutableSequence[google.ads.admanager_v1.types.UpdateLiveStreamRequest]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14623,22 +16187,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.BatchUpdateLiveStreamsResponse", - "shortName": "batch_update_live_streams" + "resultType": "google.ads.admanager_v1.types.MobileDeviceSubmodel", + "shortName": "get_mobile_device_submodel" }, - "description": "Sample for BatchUpdateLiveStreams", - "file": "admanager_v1_generated_live_stream_service_batch_update_live_streams_sync.py", + "description": "Sample for GetMobileDeviceSubmodel", + "file": "admanager_v1_generated_mobile_device_submodel_service_get_mobile_device_submodel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_BatchUpdateLiveStreams_sync", + "regionTag": "admanager_v1_generated_MobileDeviceSubmodelService_GetMobileDeviceSubmodel_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14648,52 +16212,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_batch_update_live_streams_sync.py" + "title": "admanager_v1_generated_mobile_device_submodel_service_get_mobile_device_submodel_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient", + "shortName": "MobileDeviceSubmodelServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.create_live_stream", + "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient.list_mobile_device_submodels", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.CreateLiveStream", + "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService.ListMobileDeviceSubmodels", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService", + "shortName": "MobileDeviceSubmodelService" }, - "shortName": "CreateLiveStream" + "shortName": "ListMobileDeviceSubmodels" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.CreateLiveStreamRequest" + "type": "google.ads.admanager_v1.types.ListMobileDeviceSubmodelsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "live_stream", - "type": "google.ads.admanager_v1.types.LiveStream" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14707,22 +16267,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.LiveStream", - "shortName": "create_live_stream" + "resultType": "google.ads.admanager_v1.services.mobile_device_submodel_service.pagers.ListMobileDeviceSubmodelsPager", + "shortName": "list_mobile_device_submodels" }, - "description": "Sample for CreateLiveStream", - "file": "admanager_v1_generated_live_stream_service_create_live_stream_sync.py", + "description": "Sample for ListMobileDeviceSubmodels", + "file": "admanager_v1_generated_mobile_device_submodel_service_list_mobile_device_submodels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_CreateLiveStream_sync", + "regionTag": "admanager_v1_generated_MobileDeviceSubmodelService_ListMobileDeviceSubmodels_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -14732,48 +16292,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_create_live_stream_sync.py" + "title": "admanager_v1_generated_mobile_device_submodel_service_list_mobile_device_submodels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.get_live_stream", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.batch_activate_native_styles", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.GetLiveStream", + "fullName": "google.ads.admanager.v1.NativeStyleService.BatchActivateNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "GetLiveStream" + "shortName": "BatchActivateNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetLiveStreamRequest" + "type": "google.ads.admanager_v1.types.BatchActivateNativeStylesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14787,22 +16351,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.LiveStream", - "shortName": "get_live_stream" + "resultType": "google.ads.admanager_v1.types.BatchActivateNativeStylesResponse", + "shortName": "batch_activate_native_styles" }, - "description": "Sample for GetLiveStream", - "file": "admanager_v1_generated_live_stream_service_get_live_stream_sync.py", + "description": "Sample for BatchActivateNativeStyles", + "file": "admanager_v1_generated_native_style_service_batch_activate_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_GetLiveStream_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_BatchActivateNativeStyles_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -14812,48 +16376,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_get_live_stream_sync.py" + "title": "admanager_v1_generated_native_style_service_batch_activate_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.list_live_streams", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.batch_archive_native_styles", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.ListLiveStreams", + "fullName": "google.ads.admanager.v1.NativeStyleService.BatchArchiveNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "ListLiveStreams" + "shortName": "BatchArchiveNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListLiveStreamsRequest" + "type": "google.ads.admanager_v1.types.BatchArchiveNativeStylesRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14867,14 +16435,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.live_stream_service.pagers.ListLiveStreamsPager", - "shortName": "list_live_streams" + "resultType": "google.ads.admanager_v1.types.BatchArchiveNativeStylesResponse", + "shortName": "batch_archive_native_styles" }, - "description": "Sample for ListLiveStreams", - "file": "admanager_v1_generated_live_stream_service_list_live_streams_sync.py", + "description": "Sample for BatchArchiveNativeStyles", + "file": "admanager_v1_generated_native_style_service_batch_archive_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_ListLiveStreams_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_BatchArchiveNativeStyles_sync", "segments": [ { "end": 52, @@ -14892,51 +16460,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_list_live_streams_sync.py" + "title": "admanager_v1_generated_native_style_service_batch_archive_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient", - "shortName": "LiveStreamServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.LiveStreamServiceClient.update_live_stream", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.batch_create_native_styles", "method": { - "fullName": "google.ads.admanager.v1.LiveStreamService.UpdateLiveStream", + "fullName": "google.ads.admanager.v1.NativeStyleService.BatchCreateNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.LiveStreamService", - "shortName": "LiveStreamService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "UpdateLiveStream" + "shortName": "BatchCreateNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.UpdateLiveStreamRequest" + "type": "google.ads.admanager_v1.types.BatchCreateNativeStylesRequest" }, { - "name": "live_stream", - "type": "google.ads.admanager_v1.types.LiveStream" + "name": "parent", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.CreateNativeStyleRequest]" }, { "name": "retry", @@ -14951,22 +16519,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.LiveStream", - "shortName": "update_live_stream" + "resultType": "google.ads.admanager_v1.types.BatchCreateNativeStylesResponse", + "shortName": "batch_create_native_styles" }, - "description": "Sample for UpdateLiveStream", - "file": "admanager_v1_generated_live_stream_service_update_live_stream_sync.py", + "description": "Sample for BatchCreateNativeStyles", + "file": "admanager_v1_generated_native_style_service_batch_create_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_LiveStreamService_UpdateLiveStream_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_BatchCreateNativeStyles_sync", "segments": [ { - "end": 55, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 58, "start": 27, "type": "SHORT" }, @@ -14976,48 +16544,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_live_stream_service_update_live_stream_sync.py" + "title": "admanager_v1_generated_native_style_service_batch_create_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.McmEarningsServiceClient", - "shortName": "McmEarningsServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.McmEarningsServiceClient.fetch_mcm_earnings", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.batch_deactivate_native_styles", "method": { - "fullName": "google.ads.admanager.v1.McmEarningsService.FetchMcmEarnings", + "fullName": "google.ads.admanager.v1.NativeStyleService.BatchDeactivateNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.McmEarningsService", - "shortName": "McmEarningsService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "FetchMcmEarnings" + "shortName": "BatchDeactivateNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.FetchMcmEarningsRequest" + "type": "google.ads.admanager_v1.types.BatchDeactivateNativeStylesRequest" }, { "name": "parent", "type": "str" }, + { + "name": "names", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15031,14 +16603,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.mcm_earnings_service.pagers.FetchMcmEarningsPager", - "shortName": "fetch_mcm_earnings" + "resultType": "google.ads.admanager_v1.types.BatchDeactivateNativeStylesResponse", + "shortName": "batch_deactivate_native_styles" }, - "description": "Sample for FetchMcmEarnings", - "file": "admanager_v1_generated_mcm_earnings_service_fetch_mcm_earnings_sync.py", + "description": "Sample for BatchDeactivateNativeStyles", + "file": "admanager_v1_generated_native_style_service_batch_deactivate_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_McmEarningsService_FetchMcmEarnings_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_BatchDeactivateNativeStyles_sync", "segments": [ { "end": 52, @@ -15056,48 +16628,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mcm_earnings_service_fetch_mcm_earnings_sync.py" + "title": "admanager_v1_generated_native_style_service_batch_deactivate_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient", - "shortName": "MobileCarrierServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient.get_mobile_carrier", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.batch_update_native_styles", "method": { - "fullName": "google.ads.admanager.v1.MobileCarrierService.GetMobileCarrier", + "fullName": "google.ads.admanager.v1.NativeStyleService.BatchUpdateNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.MobileCarrierService", - "shortName": "MobileCarrierService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "GetMobileCarrier" + "shortName": "BatchUpdateNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetMobileCarrierRequest" + "type": "google.ads.admanager_v1.types.BatchUpdateNativeStylesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "requests", + "type": "MutableSequence[google.ads.admanager_v1.types.UpdateNativeStyleRequest]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15111,22 +16687,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.MobileCarrier", - "shortName": "get_mobile_carrier" + "resultType": "google.ads.admanager_v1.types.BatchUpdateNativeStylesResponse", + "shortName": "batch_update_native_styles" }, - "description": "Sample for GetMobileCarrier", - "file": "admanager_v1_generated_mobile_carrier_service_get_mobile_carrier_sync.py", + "description": "Sample for BatchUpdateNativeStyles", + "file": "admanager_v1_generated_native_style_service_batch_update_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileCarrierService_GetMobileCarrier_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_BatchUpdateNativeStyles_sync", "segments": [ { - "end": 51, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 57, "start": 27, "type": "SHORT" }, @@ -15136,46 +16712,46 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_carrier_service_get_mobile_carrier_sync.py" + "title": "admanager_v1_generated_native_style_service_batch_update_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient", - "shortName": "MobileCarrierServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileCarrierServiceClient.list_mobile_carriers", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.get_native_style", "method": { - "fullName": "google.ads.admanager.v1.MobileCarrierService.ListMobileCarriers", + "fullName": "google.ads.admanager.v1.NativeStyleService.GetNativeStyle", "service": { - "fullName": "google.ads.admanager.v1.MobileCarrierService", - "shortName": "MobileCarrierService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "ListMobileCarriers" + "shortName": "GetNativeStyle" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListMobileCarriersRequest" + "type": "google.ads.admanager_v1.types.GetNativeStyleRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15191,22 +16767,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.mobile_carrier_service.pagers.ListMobileCarriersPager", - "shortName": "list_mobile_carriers" + "resultType": "google.ads.admanager_v1.types.NativeStyle", + "shortName": "get_native_style" }, - "description": "Sample for ListMobileCarriers", - "file": "admanager_v1_generated_mobile_carrier_service_list_mobile_carriers_sync.py", + "description": "Sample for GetNativeStyle", + "file": "admanager_v1_generated_native_style_service_get_native_style_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileCarrierService_ListMobileCarriers_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_GetNativeStyle_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15226,36 +16802,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_carrier_service_list_mobile_carriers_sync.py" + "title": "admanager_v1_generated_native_style_service_get_native_style_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient", - "shortName": "MobileDeviceServiceClient" + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient", + "shortName": "NativeStyleServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient.get_mobile_device", + "fullName": "google.ads.admanager_v1.NativeStyleServiceClient.list_native_styles", "method": { - "fullName": "google.ads.admanager.v1.MobileDeviceService.GetMobileDevice", + "fullName": "google.ads.admanager.v1.NativeStyleService.ListNativeStyles", "service": { - "fullName": "google.ads.admanager.v1.MobileDeviceService", - "shortName": "MobileDeviceService" + "fullName": "google.ads.admanager.v1.NativeStyleService", + "shortName": "NativeStyleService" }, - "shortName": "GetMobileDevice" + "shortName": "ListNativeStyles" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetMobileDeviceRequest" + "type": "google.ads.admanager_v1.types.ListNativeStylesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -15271,22 +16847,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.MobileDevice", - "shortName": "get_mobile_device" + "resultType": "google.ads.admanager_v1.services.native_style_service.pagers.ListNativeStylesPager", + "shortName": "list_native_styles" }, - "description": "Sample for GetMobileDevice", - "file": "admanager_v1_generated_mobile_device_service_get_mobile_device_sync.py", + "description": "Sample for ListNativeStyles", + "file": "admanager_v1_generated_native_style_service_list_native_styles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileDeviceService_GetMobileDevice_sync", + "regionTag": "admanager_v1_generated_NativeStyleService_ListNativeStyles_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -15306,36 +16882,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_device_service_get_mobile_device_sync.py" + "title": "admanager_v1_generated_native_style_service_list_native_styles_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient", - "shortName": "MobileDeviceServiceClient" + "fullName": "google.ads.admanager_v1.NetworkServiceClient", + "shortName": "NetworkServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileDeviceServiceClient.list_mobile_devices", + "fullName": "google.ads.admanager_v1.NetworkServiceClient.get_default_third_party_data_declaration", "method": { - "fullName": "google.ads.admanager.v1.MobileDeviceService.ListMobileDevices", + "fullName": "google.ads.admanager.v1.NetworkService.GetDefaultThirdPartyDataDeclaration", "service": { - "fullName": "google.ads.admanager.v1.MobileDeviceService", - "shortName": "MobileDeviceService" + "fullName": "google.ads.admanager.v1.NetworkService", + "shortName": "NetworkService" }, - "shortName": "ListMobileDevices" + "shortName": "GetDefaultThirdPartyDataDeclaration" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListMobileDevicesRequest" + "type": "google.ads.admanager_v1.types.GetDefaultThirdPartyDataDeclarationRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -15351,22 +16927,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.mobile_device_service.pagers.ListMobileDevicesPager", - "shortName": "list_mobile_devices" + "resultType": "google.ads.admanager_v1.types.DefaultThirdPartyDataDeclaration", + "shortName": "get_default_third_party_data_declaration" }, - "description": "Sample for ListMobileDevices", - "file": "admanager_v1_generated_mobile_device_service_list_mobile_devices_sync.py", + "description": "Sample for GetDefaultThirdPartyDataDeclaration", + "file": "admanager_v1_generated_network_service_get_default_third_party_data_declaration_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileDeviceService_ListMobileDevices_sync", + "regionTag": "admanager_v1_generated_NetworkService_GetDefaultThirdPartyDataDeclaration_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15386,33 +16962,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_device_service_list_mobile_devices_sync.py" + "title": "admanager_v1_generated_network_service_get_default_third_party_data_declaration_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient", - "shortName": "MobileDeviceSubmodelServiceClient" + "fullName": "google.ads.admanager_v1.NetworkServiceClient", + "shortName": "NetworkServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient.get_mobile_device_submodel", + "fullName": "google.ads.admanager_v1.NetworkServiceClient.get_network", "method": { - "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService.GetMobileDeviceSubmodel", + "fullName": "google.ads.admanager.v1.NetworkService.GetNetwork", "service": { - "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService", - "shortName": "MobileDeviceSubmodelService" + "fullName": "google.ads.admanager.v1.NetworkService", + "shortName": "NetworkService" }, - "shortName": "GetMobileDeviceSubmodel" + "shortName": "GetNetwork" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetMobileDeviceSubmodelRequest" + "type": "google.ads.admanager_v1.types.GetNetworkRequest" }, { "name": "name", @@ -15431,14 +17007,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.types.MobileDeviceSubmodel", - "shortName": "get_mobile_device_submodel" + "resultType": "google.ads.admanager_v1.types.Network", + "shortName": "get_network" }, - "description": "Sample for GetMobileDeviceSubmodel", - "file": "admanager_v1_generated_mobile_device_submodel_service_get_mobile_device_submodel_sync.py", + "description": "Sample for GetNetwork", + "file": "admanager_v1_generated_network_service_get_network_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileDeviceSubmodelService_GetMobileDeviceSubmodel_sync", + "regionTag": "admanager_v1_generated_NetworkService_GetNetwork_sync", "segments": [ { "end": 51, @@ -15471,32 +17047,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_device_submodel_service_get_mobile_device_submodel_sync.py" + "title": "admanager_v1_generated_network_service_get_network_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient", - "shortName": "MobileDeviceSubmodelServiceClient" + "fullName": "google.ads.admanager_v1.NetworkServiceClient", + "shortName": "NetworkServiceClient" }, - "fullName": "google.ads.admanager_v1.MobileDeviceSubmodelServiceClient.list_mobile_device_submodels", + "fullName": "google.ads.admanager_v1.NetworkServiceClient.list_networks", "method": { - "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService.ListMobileDeviceSubmodels", + "fullName": "google.ads.admanager.v1.NetworkService.ListNetworks", "service": { - "fullName": "google.ads.admanager.v1.MobileDeviceSubmodelService", - "shortName": "MobileDeviceSubmodelService" + "fullName": "google.ads.admanager.v1.NetworkService", + "shortName": "NetworkService" }, - "shortName": "ListMobileDeviceSubmodels" + "shortName": "ListNetworks" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListMobileDeviceSubmodelsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.ads.admanager_v1.types.ListNetworksRequest" }, { "name": "retry", @@ -15511,22 +17083,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.mobile_device_submodel_service.pagers.ListMobileDeviceSubmodelsPager", - "shortName": "list_mobile_device_submodels" + "resultType": "google.ads.admanager_v1.services.network_service.pagers.ListNetworksPager", + "shortName": "list_networks" }, - "description": "Sample for ListMobileDeviceSubmodels", - "file": "admanager_v1_generated_mobile_device_submodel_service_list_mobile_device_submodels_sync.py", + "description": "Sample for ListNetworks", + "file": "admanager_v1_generated_network_service_list_networks_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_MobileDeviceSubmodelService_ListMobileDeviceSubmodels_sync", + "regionTag": "admanager_v1_generated_NetworkService_ListNetworks_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15536,22 +17108,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_mobile_device_submodel_service_list_mobile_device_submodels_sync.py" + "title": "admanager_v1_generated_network_service_list_networks_sync.py" }, { "canonical": true, @@ -15560,23 +17132,19 @@ "fullName": "google.ads.admanager_v1.NetworkServiceClient", "shortName": "NetworkServiceClient" }, - "fullName": "google.ads.admanager_v1.NetworkServiceClient.get_network", + "fullName": "google.ads.admanager_v1.NetworkServiceClient.provision_test_network", "method": { - "fullName": "google.ads.admanager.v1.NetworkService.GetNetwork", + "fullName": "google.ads.admanager.v1.NetworkService.ProvisionTestNetwork", "service": { "fullName": "google.ads.admanager.v1.NetworkService", "shortName": "NetworkService" }, - "shortName": "GetNetwork" + "shortName": "ProvisionTestNetwork" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.GetNetworkRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.ads.admanager_v1.types.ProvisionTestNetworkRequest" }, { "name": "retry", @@ -15592,21 +17160,21 @@ } ], "resultType": "google.ads.admanager_v1.types.Network", - "shortName": "get_network" + "shortName": "provision_test_network" }, - "description": "Sample for GetNetwork", - "file": "admanager_v1_generated_network_service_get_network_sync.py", + "description": "Sample for ProvisionTestNetwork", + "file": "admanager_v1_generated_network_service_provision_test_network_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_NetworkService_GetNetwork_sync", + "regionTag": "admanager_v1_generated_NetworkService_ProvisionTestNetwork_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -15616,22 +17184,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_network_service_get_network_sync.py" + "title": "admanager_v1_generated_network_service_provision_test_network_sync.py" }, { "canonical": true, @@ -15640,19 +17208,27 @@ "fullName": "google.ads.admanager_v1.NetworkServiceClient", "shortName": "NetworkServiceClient" }, - "fullName": "google.ads.admanager_v1.NetworkServiceClient.list_networks", + "fullName": "google.ads.admanager_v1.NetworkServiceClient.update_network", "method": { - "fullName": "google.ads.admanager.v1.NetworkService.ListNetworks", + "fullName": "google.ads.admanager.v1.NetworkService.UpdateNetwork", "service": { "fullName": "google.ads.admanager.v1.NetworkService", "shortName": "NetworkService" }, - "shortName": "ListNetworks" + "shortName": "UpdateNetwork" }, "parameters": [ { "name": "request", - "type": "google.ads.admanager_v1.types.ListNetworksRequest" + "type": "google.ads.admanager_v1.types.UpdateNetworkRequest" + }, + { + "name": "network", + "type": "google.ads.admanager_v1.types.Network" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -15667,22 +17243,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.ads.admanager_v1.services.network_service.pagers.ListNetworksPager", - "shortName": "list_networks" + "resultType": "google.ads.admanager_v1.types.Network", + "shortName": "update_network" }, - "description": "Sample for ListNetworks", - "file": "admanager_v1_generated_network_service_list_networks_sync.py", + "description": "Sample for UpdateNetwork", + "file": "admanager_v1_generated_network_service_update_network_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "admanager_v1_generated_NetworkService_ListNetworks_sync", + "regionTag": "admanager_v1_generated_NetworkService_UpdateNetwork_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -15702,12 +17278,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 51, "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "admanager_v1_generated_network_service_list_networks_sync.py" + "title": "admanager_v1_generated_network_service_update_network_sync.py" }, { "canonical": true, diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_audience_segment_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_audience_segment_service.py index df081c1ad3ba..4d248cf6de6f 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_audience_segment_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_audience_segment_service.py @@ -59,6 +59,7 @@ transports, ) from google.ads.admanager_v1.types import ( + audience_segment_enums, audience_segment_messages, audience_segment_service, ) @@ -1681,96 +1682,1887 @@ def test_list_audience_segments_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AudienceSegmentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_batch_activate_audience_segments_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 = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.AudienceSegmentServiceRestTransport( + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_activate_audience_segments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_activate_audience_segments + ] = mock_rpc + + request = {} + client.batch_activate_audience_segments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_activate_audience_segments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_activate_audience_segments_rest_required_fields( + request_type=audience_segment_service.BatchActivateAudienceSegmentsRequest, +): + transport_class = transports.AudienceSegmentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_activate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_activate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = AudienceSegmentServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + request = request_type(**request_init) - # It is an error to provide an api_key and a transport instance. + # Designate an appropriate value for the returned response. + return_value = audience_segment_service.BatchActivateAudienceSegmentsResponse() + # 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 = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_activate_audience_segments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_activate_audience_segments_rest_unset_required_fields(): transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.batch_activate_audience_segments._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_activate_audience_segments_rest_flattened(): + client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AudienceSegmentServiceClient( - client_options=options, - 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 = audience_segment_service.BatchActivateAudienceSegmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_value"], ) + mock_args.update(sample_request) - # 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 = AudienceSegmentServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse.pb( + return_value + ) ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - # It is an error to provide scopes and a transport instance. - transport = transports.AudienceSegmentServiceRestTransport( + client.batch_activate_audience_segments(**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=networks/*}/audienceSegments:batchActivate" + % client.transport._host, + args[1], + ) + + +def test_batch_activate_audience_segments_rest_flattened_error(transport: str = "rest"): + client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): + client.batch_activate_audience_segments( + audience_segment_service.BatchActivateAudienceSegmentsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_deactivate_audience_segments_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 = AudienceSegmentServiceClient( - 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.AudienceSegmentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Ensure method has been cached + assert ( + client._transport.batch_deactivate_audience_segments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_deactivate_audience_segments + ] = mock_rpc + + request = {} + client.batch_deactivate_audience_segments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_deactivate_audience_segments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_deactivate_audience_segments_rest_required_fields( + request_type=audience_segment_service.BatchDeactivateAudienceSegmentsRequest, +): + transport_class = transports.AudienceSegmentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + 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) ) - client = AudienceSegmentServiceClient(transport=transport) - assert client.transport is transport + # verify fields with default values are dropped -@pytest.mark.parametrize( - "transport_class", - [ - transports.AudienceSegmentServiceRestTransport, - ], -) -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() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_deactivate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_deactivate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = audience_segment_service.BatchDeactivateAudienceSegmentsResponse() + # 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 = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_deactivate_audience_segments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_deactivate_audience_segments_rest_unset_required_fields(): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.batch_deactivate_audience_segments._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_deactivate_audience_segments_rest_flattened(): + client = AudienceSegmentServiceClient( + 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 = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_deactivate_audience_segments(**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=networks/*}/audienceSegments:batchDeactivate" + % client.transport._host, + args[1], + ) + + +def test_batch_deactivate_audience_segments_rest_flattened_error( + transport: str = "rest", +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_deactivate_audience_segments( + audience_segment_service.BatchDeactivateAudienceSegmentsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_approve_audience_segments_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 = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_approve_audience_segments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_approve_audience_segments + ] = mock_rpc + + request = {} + client.batch_approve_audience_segments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_approve_audience_segments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_approve_audience_segments_rest_required_fields( + request_type=audience_segment_service.BatchApproveAudienceSegmentsRequest, +): + transport_class = transports.AudienceSegmentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_approve_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_approve_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = audience_segment_service.BatchApproveAudienceSegmentsResponse() + # 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 = ( + audience_segment_service.BatchApproveAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_approve_audience_segments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_approve_audience_segments_rest_unset_required_fields(): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_approve_audience_segments._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_approve_audience_segments_rest_flattened(): + client = AudienceSegmentServiceClient( + 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 = audience_segment_service.BatchApproveAudienceSegmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = audience_segment_service.BatchApproveAudienceSegmentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_approve_audience_segments(**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=networks/*}/audienceSegments:batchApprove" + % client.transport._host, + args[1], + ) + + +def test_batch_approve_audience_segments_rest_flattened_error(transport: str = "rest"): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_approve_audience_segments( + audience_segment_service.BatchApproveAudienceSegmentsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_reject_audience_segments_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 = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_reject_audience_segments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_reject_audience_segments + ] = mock_rpc + + request = {} + client.batch_reject_audience_segments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_reject_audience_segments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_reject_audience_segments_rest_required_fields( + request_type=audience_segment_service.BatchRejectAudienceSegmentsRequest, +): + transport_class = transports.AudienceSegmentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_reject_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_reject_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = audience_segment_service.BatchRejectAudienceSegmentsResponse() + # 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 = ( + audience_segment_service.BatchRejectAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_reject_audience_segments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_reject_audience_segments_rest_unset_required_fields(): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_reject_audience_segments._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_reject_audience_segments_rest_flattened(): + client = AudienceSegmentServiceClient( + 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 = audience_segment_service.BatchRejectAudienceSegmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = audience_segment_service.BatchRejectAudienceSegmentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_reject_audience_segments(**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=networks/*}/audienceSegments:batchReject" + % client.transport._host, + args[1], + ) + + +def test_batch_reject_audience_segments_rest_flattened_error(transport: str = "rest"): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_reject_audience_segments( + audience_segment_service.BatchRejectAudienceSegmentsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_populate_audience_segments_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 = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_populate_audience_segments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_populate_audience_segments + ] = mock_rpc + + request = {} + client.batch_populate_audience_segments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_populate_audience_segments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_populate_audience_segments_rest_required_fields( + request_type=audience_segment_service.BatchPopulateAudienceSegmentsRequest, +): + transport_class = transports.AudienceSegmentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_populate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_populate_audience_segments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = audience_segment_service.BatchPopulateAudienceSegmentsResponse() + # 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 = ( + audience_segment_service.BatchPopulateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_populate_audience_segments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_populate_audience_segments_rest_unset_required_fields(): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.batch_populate_audience_segments._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_populate_audience_segments_rest_flattened(): + client = AudienceSegmentServiceClient( + 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 = audience_segment_service.BatchPopulateAudienceSegmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = ( + audience_segment_service.BatchPopulateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_populate_audience_segments(**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=networks/*}/audienceSegments:batchPopulate" + % client.transport._host, + args[1], + ) + + +def test_batch_populate_audience_segments_rest_flattened_error(transport: str = "rest"): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_populate_audience_segments( + audience_segment_service.BatchPopulateAudienceSegmentsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AudienceSegmentServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AudienceSegmentServiceClient( + 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 = AudienceSegmentServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AudienceSegmentServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AudienceSegmentServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AudienceSegmentServiceRestTransport, + ], +) +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_rest(): + transport = AudienceSegmentServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_audience_segment_rest_bad_request( + request_type=audience_segment_service.GetAudienceSegmentRequest, +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/audienceSegments/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.get_audience_segment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + audience_segment_service.GetAudienceSegmentRequest, + dict, + ], +) +def test_get_audience_segment_rest_call_success(request_type): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/audienceSegments/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 = audience_segment_messages.AudienceSegment( + name="name_value", + shared_id=931, + display_name="display_name_value", + category_ids=[1277], + description="description_value", + status=audience_segment_enums.AudienceSegmentStatusEnum.AudienceSegmentStatus.ACTIVE, + size=443, + mobile_web_size=1583, + idfa_size=942, + ad_id_size=1035, + ppid_size=967, + data_provider_display_name="data_provider_display_name_value", + segment_type=audience_segment_enums.AudienceSegmentTypeEnum.AudienceSegmentType.FIRST_PARTY, + ) + + # 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 = audience_segment_messages.AudienceSegment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_audience_segment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, audience_segment_messages.AudienceSegment) + assert response.name == "name_value" + assert response.shared_id == 931 + assert response.display_name == "display_name_value" + assert response.category_ids == [1277] + assert response.description == "description_value" + assert ( + response.status + == audience_segment_enums.AudienceSegmentStatusEnum.AudienceSegmentStatus.ACTIVE + ) + assert response.size == 443 + assert response.mobile_web_size == 1583 + assert response.idfa_size == 942 + assert response.ad_id_size == 1035 + assert response.ppid_size == 967 + assert response.data_provider_display_name == "data_provider_display_name_value" + assert ( + response.segment_type + == audience_segment_enums.AudienceSegmentTypeEnum.AudienceSegmentType.FIRST_PARTY + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_audience_segment_rest_interceptors(null_interceptor): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AudienceSegmentServiceRestInterceptor(), + ) + client = AudienceSegmentServiceClient(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.AudienceSegmentServiceRestInterceptor, + "post_get_audience_segment", + ) as post, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "post_get_audience_segment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, "pre_get_audience_segment" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = audience_segment_service.GetAudienceSegmentRequest.pb( + audience_segment_service.GetAudienceSegmentRequest() + ) + 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 = audience_segment_messages.AudienceSegment.to_json( + audience_segment_messages.AudienceSegment() + ) + req.return_value.content = return_value + + request = audience_segment_service.GetAudienceSegmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = audience_segment_messages.AudienceSegment() + post_with_metadata.return_value = ( + audience_segment_messages.AudienceSegment(), + metadata, + ) + + client.get_audience_segment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_audience_segments_rest_bad_request( + request_type=audience_segment_service.ListAudienceSegmentsRequest, +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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_audience_segments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + audience_segment_service.ListAudienceSegmentsRequest, + dict, + ], +) +def test_list_audience_segments_rest_call_success(request_type): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = audience_segment_service.ListAudienceSegmentsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # 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 = audience_segment_service.ListAudienceSegmentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_audience_segments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAudienceSegmentsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_audience_segments_rest_interceptors(null_interceptor): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AudienceSegmentServiceRestInterceptor(), + ) + client = AudienceSegmentServiceClient(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.AudienceSegmentServiceRestInterceptor, + "post_list_audience_segments", + ) as post, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "post_list_audience_segments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "pre_list_audience_segments", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = audience_segment_service.ListAudienceSegmentsRequest.pb( + audience_segment_service.ListAudienceSegmentsRequest() + ) + 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 = audience_segment_service.ListAudienceSegmentsResponse.to_json( + audience_segment_service.ListAudienceSegmentsResponse() + ) + req.return_value.content = return_value + + request = audience_segment_service.ListAudienceSegmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = audience_segment_service.ListAudienceSegmentsResponse() + post_with_metadata.return_value = ( + audience_segment_service.ListAudienceSegmentsResponse(), + metadata, + ) + + client.list_audience_segments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_activate_audience_segments_rest_bad_request( + request_type=audience_segment_service.BatchActivateAudienceSegmentsRequest, +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_activate_audience_segments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + audience_segment_service.BatchActivateAudienceSegmentsRequest, + dict, + ], +) +def test_batch_activate_audience_segments_rest_call_success(request_type): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = audience_segment_service.BatchActivateAudienceSegmentsResponse( + change_count=1262, + ) + + # 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 = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_activate_audience_segments(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, audience_segment_service.BatchActivateAudienceSegmentsResponse + ) + assert response.change_count == 1262 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_activate_audience_segments_rest_interceptors(null_interceptor): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AudienceSegmentServiceRestInterceptor(), + ) + client = AudienceSegmentServiceClient(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.AudienceSegmentServiceRestInterceptor, + "post_batch_activate_audience_segments", + ) as post, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "post_batch_activate_audience_segments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "pre_batch_activate_audience_segments", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = audience_segment_service.BatchActivateAudienceSegmentsRequest.pb( + audience_segment_service.BatchActivateAudienceSegmentsRequest() + ) + 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 = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse.to_json( + audience_segment_service.BatchActivateAudienceSegmentsResponse() + ) + ) + req.return_value.content = return_value + + request = audience_segment_service.BatchActivateAudienceSegmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse() + ) + post_with_metadata.return_value = ( + audience_segment_service.BatchActivateAudienceSegmentsResponse(), + metadata, + ) + + client.batch_activate_audience_segments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_deactivate_audience_segments_rest_bad_request( + request_type=audience_segment_service.BatchDeactivateAudienceSegmentsRequest, +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_deactivate_audience_segments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + audience_segment_service.BatchDeactivateAudienceSegmentsRequest, + dict, + ], +) +def test_batch_deactivate_audience_segments_rest_call_success(request_type): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = audience_segment_service.BatchDeactivateAudienceSegmentsResponse( + change_count=1262, + ) + + # 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 = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_deactivate_audience_segments(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, audience_segment_service.BatchDeactivateAudienceSegmentsResponse + ) + assert response.change_count == 1262 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_deactivate_audience_segments_rest_interceptors(null_interceptor): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AudienceSegmentServiceRestInterceptor(), + ) + client = AudienceSegmentServiceClient(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.AudienceSegmentServiceRestInterceptor, + "post_batch_deactivate_audience_segments", + ) as post, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "post_batch_deactivate_audience_segments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "pre_batch_deactivate_audience_segments", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = audience_segment_service.BatchDeactivateAudienceSegmentsRequest.pb( + audience_segment_service.BatchDeactivateAudienceSegmentsRequest() + ) + 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 = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse.to_json( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse() + ) + ) + req.return_value.content = return_value + + request = audience_segment_service.BatchDeactivateAudienceSegmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse() + ) + post_with_metadata.return_value = ( + audience_segment_service.BatchDeactivateAudienceSegmentsResponse(), + metadata, + ) + + client.batch_deactivate_audience_segments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_approve_audience_segments_rest_bad_request( + request_type=audience_segment_service.BatchApproveAudienceSegmentsRequest, +): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_approve_audience_segments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + audience_segment_service.BatchApproveAudienceSegmentsRequest, + dict, + ], +) +def test_batch_approve_audience_segments_rest_call_success(request_type): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = audience_segment_service.BatchApproveAudienceSegmentsResponse( + change_count=1262, + ) + + # 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 = audience_segment_service.BatchApproveAudienceSegmentsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_approve_audience_segments(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, audience_segment_service.BatchApproveAudienceSegmentsResponse + ) + assert response.change_count == 1262 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_approve_audience_segments_rest_interceptors(null_interceptor): + transport = transports.AudienceSegmentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AudienceSegmentServiceRestInterceptor(), + ) + client = AudienceSegmentServiceClient(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.AudienceSegmentServiceRestInterceptor, + "post_batch_approve_audience_segments", + ) as post, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "post_batch_approve_audience_segments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.AudienceSegmentServiceRestInterceptor, + "pre_batch_approve_audience_segments", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = audience_segment_service.BatchApproveAudienceSegmentsRequest.pb( + audience_segment_service.BatchApproveAudienceSegmentsRequest() + ) + 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 = ( + audience_segment_service.BatchApproveAudienceSegmentsResponse.to_json( + audience_segment_service.BatchApproveAudienceSegmentsResponse() + ) + ) + req.return_value.content = return_value + request = audience_segment_service.BatchApproveAudienceSegmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + audience_segment_service.BatchApproveAudienceSegmentsResponse() + ) + post_with_metadata.return_value = ( + audience_segment_service.BatchApproveAudienceSegmentsResponse(), + metadata, + ) -def test_transport_kind_rest(): - transport = AudienceSegmentServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.batch_approve_audience_segments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_get_audience_segment_rest_bad_request( - request_type=audience_segment_service.GetAudienceSegmentRequest, + +def test_batch_reject_audience_segments_rest_bad_request( + request_type=audience_segment_service.BatchRejectAudienceSegmentsRequest, ): client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1/audienceSegments/sample2"} + request_init = {"parent": "networks/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -1786,31 +3578,30 @@ def test_get_audience_segment_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_audience_segment(request) + client.batch_reject_audience_segments(request) @pytest.mark.parametrize( "request_type", [ - audience_segment_service.GetAudienceSegmentRequest, + audience_segment_service.BatchRejectAudienceSegmentsRequest, dict, ], ) -def test_get_audience_segment_rest_call_success(request_type): +def test_batch_reject_audience_segments_rest_call_success(request_type): client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1/audienceSegments/sample2"} + request_init = {"parent": "networks/sample1"} 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 = audience_segment_messages.AudienceSegment( - name="name_value", - display_name="display_name_value", + return_value = audience_segment_service.BatchRejectAudienceSegmentsResponse( + change_count=1262, ) # Wrap the value into a proper Response obj @@ -1818,21 +3609,24 @@ def test_get_audience_segment_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = audience_segment_messages.AudienceSegment.pb(return_value) + return_value = audience_segment_service.BatchRejectAudienceSegmentsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_audience_segment(request) + response = client.batch_reject_audience_segments(request) # Establish that the response is the type that we expect. - assert isinstance(response, audience_segment_messages.AudienceSegment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert isinstance( + response, audience_segment_service.BatchRejectAudienceSegmentsResponse + ) + assert response.change_count == 1262 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_audience_segment_rest_interceptors(null_interceptor): +def test_batch_reject_audience_segments_rest_interceptors(null_interceptor): transport = transports.AudienceSegmentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1846,21 +3640,22 @@ def test_get_audience_segment_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.AudienceSegmentServiceRestInterceptor, - "post_get_audience_segment", + "post_batch_reject_audience_segments", ) as post, mock.patch.object( transports.AudienceSegmentServiceRestInterceptor, - "post_get_audience_segment_with_metadata", + "post_batch_reject_audience_segments_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.AudienceSegmentServiceRestInterceptor, "pre_get_audience_segment" + transports.AudienceSegmentServiceRestInterceptor, + "pre_batch_reject_audience_segments", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = audience_segment_service.GetAudienceSegmentRequest.pb( - audience_segment_service.GetAudienceSegmentRequest() + pb_message = audience_segment_service.BatchRejectAudienceSegmentsRequest.pb( + audience_segment_service.BatchRejectAudienceSegmentsRequest() ) transcode.return_value = { "method": "post", @@ -1872,24 +3667,28 @@ def test_get_audience_segment_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 = audience_segment_messages.AudienceSegment.to_json( - audience_segment_messages.AudienceSegment() + return_value = ( + audience_segment_service.BatchRejectAudienceSegmentsResponse.to_json( + audience_segment_service.BatchRejectAudienceSegmentsResponse() + ) ) req.return_value.content = return_value - request = audience_segment_service.GetAudienceSegmentRequest() + request = audience_segment_service.BatchRejectAudienceSegmentsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = audience_segment_messages.AudienceSegment() + post.return_value = ( + audience_segment_service.BatchRejectAudienceSegmentsResponse() + ) post_with_metadata.return_value = ( - audience_segment_messages.AudienceSegment(), + audience_segment_service.BatchRejectAudienceSegmentsResponse(), metadata, ) - client.get_audience_segment( + client.batch_reject_audience_segments( request, metadata=[ ("key", "val"), @@ -1902,8 +3701,8 @@ def test_get_audience_segment_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_audience_segments_rest_bad_request( - request_type=audience_segment_service.ListAudienceSegmentsRequest, +def test_batch_populate_audience_segments_rest_bad_request( + request_type=audience_segment_service.BatchPopulateAudienceSegmentsRequest, ): client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -1925,17 +3724,17 @@ def test_list_audience_segments_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_audience_segments(request) + client.batch_populate_audience_segments(request) @pytest.mark.parametrize( "request_type", [ - audience_segment_service.ListAudienceSegmentsRequest, + audience_segment_service.BatchPopulateAudienceSegmentsRequest, dict, ], ) -def test_list_audience_segments_rest_call_success(request_type): +def test_batch_populate_audience_segments_rest_call_success(request_type): client = AudienceSegmentServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -1947,9 +3746,8 @@ def test_list_audience_segments_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 = audience_segment_service.ListAudienceSegmentsResponse( - next_page_token="next_page_token_value", - total_size=1086, + return_value = audience_segment_service.BatchPopulateAudienceSegmentsResponse( + change_count=1262, ) # Wrap the value into a proper Response obj @@ -1957,23 +3755,26 @@ def test_list_audience_segments_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = audience_segment_service.ListAudienceSegmentsResponse.pb( - return_value + return_value = ( + audience_segment_service.BatchPopulateAudienceSegmentsResponse.pb( + return_value + ) ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_audience_segments(request) + response = client.batch_populate_audience_segments(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAudienceSegmentsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance( + response, audience_segment_service.BatchPopulateAudienceSegmentsResponse + ) + assert response.change_count == 1262 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_audience_segments_rest_interceptors(null_interceptor): +def test_batch_populate_audience_segments_rest_interceptors(null_interceptor): transport = transports.AudienceSegmentServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1987,22 +3788,22 @@ def test_list_audience_segments_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.AudienceSegmentServiceRestInterceptor, - "post_list_audience_segments", + "post_batch_populate_audience_segments", ) as post, mock.patch.object( transports.AudienceSegmentServiceRestInterceptor, - "post_list_audience_segments_with_metadata", + "post_batch_populate_audience_segments_with_metadata", ) as post_with_metadata, mock.patch.object( transports.AudienceSegmentServiceRestInterceptor, - "pre_list_audience_segments", + "pre_batch_populate_audience_segments", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = audience_segment_service.ListAudienceSegmentsRequest.pb( - audience_segment_service.ListAudienceSegmentsRequest() + pb_message = audience_segment_service.BatchPopulateAudienceSegmentsRequest.pb( + audience_segment_service.BatchPopulateAudienceSegmentsRequest() ) transcode.return_value = { "method": "post", @@ -2014,24 +3815,28 @@ def test_list_audience_segments_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 = audience_segment_service.ListAudienceSegmentsResponse.to_json( - audience_segment_service.ListAudienceSegmentsResponse() + return_value = ( + audience_segment_service.BatchPopulateAudienceSegmentsResponse.to_json( + audience_segment_service.BatchPopulateAudienceSegmentsResponse() + ) ) req.return_value.content = return_value - request = audience_segment_service.ListAudienceSegmentsRequest() + request = audience_segment_service.BatchPopulateAudienceSegmentsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = audience_segment_service.ListAudienceSegmentsResponse() + post.return_value = ( + audience_segment_service.BatchPopulateAudienceSegmentsResponse() + ) post_with_metadata.return_value = ( - audience_segment_service.ListAudienceSegmentsResponse(), + audience_segment_service.BatchPopulateAudienceSegmentsResponse(), metadata, ) - client.list_audience_segments( + client.batch_populate_audience_segments( request, metadata=[ ("key", "val"), @@ -2219,6 +4024,111 @@ def test_list_audience_segments_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_batch_activate_audience_segments_empty_call_rest(): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_activate_audience_segments), "__call__" + ) as call: + client.batch_activate_audience_segments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = audience_segment_service.BatchActivateAudienceSegmentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_deactivate_audience_segments_empty_call_rest(): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_deactivate_audience_segments), "__call__" + ) as call: + client.batch_deactivate_audience_segments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = audience_segment_service.BatchDeactivateAudienceSegmentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_approve_audience_segments_empty_call_rest(): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_approve_audience_segments), "__call__" + ) as call: + client.batch_approve_audience_segments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = audience_segment_service.BatchApproveAudienceSegmentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_reject_audience_segments_empty_call_rest(): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_reject_audience_segments), "__call__" + ) as call: + client.batch_reject_audience_segments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = audience_segment_service.BatchRejectAudienceSegmentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_populate_audience_segments_empty_call_rest(): + client = AudienceSegmentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_populate_audience_segments), "__call__" + ) as call: + client.batch_populate_audience_segments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = audience_segment_service.BatchPopulateAudienceSegmentsRequest() + assert args[0] == request_msg + + def test_audience_segment_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -2243,6 +4153,11 @@ def test_audience_segment_service_base_transport(): methods = ( "get_audience_segment", "list_audience_segments", + "batch_activate_audience_segments", + "batch_deactivate_audience_segments", + "batch_approve_audience_segments", + "batch_reject_audience_segments", + "batch_populate_audience_segments", "get_operation", "cancel_operation", ) @@ -2394,11 +4309,49 @@ def test_audience_segment_service_client_transport_session_collision(transport_n session1 = client1.transport.list_audience_segments._session session2 = client2.transport.list_audience_segments._session assert session1 != session2 + session1 = client1.transport.batch_activate_audience_segments._session + session2 = client2.transport.batch_activate_audience_segments._session + assert session1 != session2 + session1 = client1.transport.batch_deactivate_audience_segments._session + session2 = client2.transport.batch_deactivate_audience_segments._session + assert session1 != session2 + session1 = client1.transport.batch_approve_audience_segments._session + session2 = client2.transport.batch_approve_audience_segments._session + assert session1 != session2 + session1 = client1.transport.batch_reject_audience_segments._session + session2 = client2.transport.batch_reject_audience_segments._session + assert session1 != session2 + session1 = client1.transport.batch_populate_audience_segments._session + session2 = client2.transport.batch_populate_audience_segments._session + assert session1 != session2 -def test_audience_segment_path(): +def test_ad_unit_path(): network_code = "squid" - audience_segment = "clam" + ad_unit = "clam" + expected = "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + actual = AudienceSegmentServiceClient.ad_unit_path(network_code, ad_unit) + assert expected == actual + + +def test_parse_ad_unit_path(): + expected = { + "network_code": "whelk", + "ad_unit": "octopus", + } + path = AudienceSegmentServiceClient.ad_unit_path(**expected) + + # Check that the path construction is reversible. + actual = AudienceSegmentServiceClient.parse_ad_unit_path(path) + assert expected == actual + + +def test_audience_segment_path(): + network_code = "oyster" + audience_segment = "nudibranch" expected = "networks/{network_code}/audienceSegments/{audience_segment}".format( network_code=network_code, audience_segment=audience_segment, @@ -2411,8 +4364,8 @@ def test_audience_segment_path(): def test_parse_audience_segment_path(): expected = { - "network_code": "whelk", - "audience_segment": "octopus", + "network_code": "cuttlefish", + "audience_segment": "mussel", } path = AudienceSegmentServiceClient.audience_segment_path(**expected) @@ -2421,8 +4374,87 @@ def test_parse_audience_segment_path(): assert expected == actual -def test_network_path(): +def test_cms_metadata_value_path(): + network_code = "winkle" + cms_metadata_value = "nautilus" + expected = "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + actual = AudienceSegmentServiceClient.cms_metadata_value_path( + network_code, cms_metadata_value + ) + assert expected == actual + + +def test_parse_cms_metadata_value_path(): + expected = { + "network_code": "scallop", + "cms_metadata_value": "abalone", + } + path = AudienceSegmentServiceClient.cms_metadata_value_path(**expected) + + # Check that the path construction is reversible. + actual = AudienceSegmentServiceClient.parse_cms_metadata_value_path(path) + assert expected == actual + + +def test_custom_targeting_key_path(): + network_code = "squid" + custom_targeting_key = "clam" + expected = ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + actual = AudienceSegmentServiceClient.custom_targeting_key_path( + network_code, custom_targeting_key + ) + assert expected == actual + + +def test_parse_custom_targeting_key_path(): + expected = { + "network_code": "whelk", + "custom_targeting_key": "octopus", + } + path = AudienceSegmentServiceClient.custom_targeting_key_path(**expected) + + # Check that the path construction is reversible. + actual = AudienceSegmentServiceClient.parse_custom_targeting_key_path(path) + assert expected == actual + + +def test_custom_targeting_value_path(): network_code = "oyster" + custom_targeting_value = "nudibranch" + expected = ( + "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + ) + actual = AudienceSegmentServiceClient.custom_targeting_value_path( + network_code, custom_targeting_value + ) + assert expected == actual + + +def test_parse_custom_targeting_value_path(): + expected = { + "network_code": "cuttlefish", + "custom_targeting_value": "mussel", + } + path = AudienceSegmentServiceClient.custom_targeting_value_path(**expected) + + # Check that the path construction is reversible. + actual = AudienceSegmentServiceClient.parse_custom_targeting_value_path(path) + assert expected == actual + + +def test_network_path(): + network_code = "winkle" expected = "networks/{network_code}".format( network_code=network_code, ) @@ -2432,7 +4464,7 @@ def test_network_path(): def test_parse_network_path(): expected = { - "network_code": "nudibranch", + "network_code": "nautilus", } path = AudienceSegmentServiceClient.network_path(**expected) @@ -2441,8 +4473,31 @@ def test_parse_network_path(): assert expected == actual +def test_placement_path(): + network_code = "scallop" + placement = "abalone" + expected = "networks/{network_code}/placements/{placement}".format( + network_code=network_code, + placement=placement, + ) + actual = AudienceSegmentServiceClient.placement_path(network_code, placement) + assert expected == actual + + +def test_parse_placement_path(): + expected = { + "network_code": "squid", + "placement": "clam", + } + path = AudienceSegmentServiceClient.placement_path(**expected) + + # Check that the path construction is reversible. + actual = AudienceSegmentServiceClient.parse_placement_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2452,7 +4507,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "octopus", } path = AudienceSegmentServiceClient.common_billing_account_path(**expected) @@ -2462,7 +4517,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "oyster" expected = "folders/{folder}".format( folder=folder, ) @@ -2472,7 +4527,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "nudibranch", } path = AudienceSegmentServiceClient.common_folder_path(**expected) @@ -2482,7 +4537,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "cuttlefish" expected = "organizations/{organization}".format( organization=organization, ) @@ -2492,7 +4547,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "mussel", } path = AudienceSegmentServiceClient.common_organization_path(**expected) @@ -2502,7 +4557,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "winkle" expected = "projects/{project}".format( project=project, ) @@ -2512,7 +4567,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nautilus", } path = AudienceSegmentServiceClient.common_project_path(**expected) @@ -2522,8 +4577,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -2534,8 +4589,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "squid", + "location": "clam", } path = AudienceSegmentServiceClient.common_location_path(**expected) diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_child_publisher_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_child_publisher_service.py index 0cd9c9708a3c..15b3a51a56c9 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_child_publisher_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_child_publisher_service.py @@ -2481,96 +2481,1692 @@ def test_batch_update_child_publishers_rest_flattened_error(transport: str = "re ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. +def test_batch_resend_child_publisher_invitation_emails_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 = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_resend_child_publisher_invitation_emails + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_resend_child_publisher_invitation_emails + ] = mock_rpc + + request = {} + client.batch_resend_child_publisher_invitation_emails(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_resend_child_publisher_invitation_emails(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_resend_child_publisher_invitation_emails_rest_required_fields( + request_type=child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, +): + transport_class = transports.ChildPublisherServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_resend_child_publisher_invitation_emails._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_resend_child_publisher_invitation_emails._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() + ) + # 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 = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_resend_child_publisher_invitation_emails(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_resend_child_publisher_invitation_emails_rest_unset_required_fields(): transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_resend_child_publisher_invitation_emails._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_resend_child_publisher_invitation_emails_rest_flattened(): + client = ChildPublisherServiceClient( 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 = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_resend_child_publisher_invitation_emails(**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=networks/*}/childPublishers:batchResendInvitationEmails" + % client.transport._host, + args[1], + ) + + +def test_batch_resend_child_publisher_invitation_emails_rest_flattened_error( + transport: str = "rest", +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): + client.batch_resend_child_publisher_invitation_emails( + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_renegotiate_child_publisher_agreements_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 = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_renegotiate_child_publisher_agreements + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.batch_renegotiate_child_publisher_agreements + ] = mock_rpc + + request = {} + client.batch_renegotiate_child_publisher_agreements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_renegotiate_child_publisher_agreements(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_renegotiate_child_publisher_agreements_rest_required_fields( + request_type=child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, +): + transport_class = transports.ChildPublisherServiceRestTransport + + 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() + ).batch_renegotiate_child_publisher_agreements._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() + ).batch_renegotiate_child_publisher_agreements._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 = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + ) + # 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 = child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_renegotiate_child_publisher_agreements(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_renegotiate_child_publisher_agreements_rest_unset_required_fields(): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_renegotiate_child_publisher_agreements._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +def test_batch_renegotiate_child_publisher_agreements_rest_flattened(): + client = ChildPublisherServiceClient( + 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 = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + requests=[ + child_publisher_service.RenegotiateChildPublisherAgreementRequest( + 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 = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_renegotiate_child_publisher_agreements(**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=networks/*}/childPublishers:batchRenegotiateAgreements" + % client.transport._host, + args[1], + ) + + +def test_batch_renegotiate_child_publisher_agreements_rest_flattened_error( + transport: str = "rest", +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_renegotiate_child_publisher_agreements( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest(), + parent="parent_value", + requests=[ + child_publisher_service.RenegotiateChildPublisherAgreementRequest( + name="name_value" + ) + ], + ) + + +def test_batch_reject_child_publishers_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 = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_reject_child_publishers + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_reject_child_publishers + ] = mock_rpc + + request = {} + client.batch_reject_child_publishers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_reject_child_publishers(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_reject_child_publishers_rest_required_fields( + request_type=child_publisher_service.BatchRejectChildPublishersRequest, +): + transport_class = transports.ChildPublisherServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_reject_child_publishers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_reject_child_publishers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = child_publisher_service.BatchRejectChildPublishersResponse() + # 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 = ( + child_publisher_service.BatchRejectChildPublishersResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_reject_child_publishers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_reject_child_publishers_rest_unset_required_fields(): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_reject_child_publishers._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_reject_child_publishers_rest_flattened(): + client = ChildPublisherServiceClient( + 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 = child_publisher_service.BatchRejectChildPublishersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = child_publisher_service.BatchRejectChildPublishersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_reject_child_publishers(**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=networks/*}/childPublishers:batchReject" + % client.transport._host, + args[1], + ) + + +def test_batch_reject_child_publishers_rest_flattened_error(transport: str = "rest"): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_reject_child_publishers( + child_publisher_service.BatchRejectChildPublishersRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_withdraw_child_publishers_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 = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_withdraw_child_publishers + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_withdraw_child_publishers + ] = mock_rpc + + request = {} + client.batch_withdraw_child_publishers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_withdraw_child_publishers(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_withdraw_child_publishers_rest_required_fields( + request_type=child_publisher_service.BatchWithdrawChildPublishersRequest, +): + transport_class = transports.ChildPublisherServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_withdraw_child_publishers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_withdraw_child_publishers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = child_publisher_service.BatchWithdrawChildPublishersResponse() + # 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 = ( + child_publisher_service.BatchWithdrawChildPublishersResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_withdraw_child_publishers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_withdraw_child_publishers_rest_unset_required_fields(): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_withdraw_child_publishers._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_withdraw_child_publishers_rest_flattened(): + client = ChildPublisherServiceClient( + 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 = child_publisher_service.BatchWithdrawChildPublishersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = child_publisher_service.BatchWithdrawChildPublishersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_withdraw_child_publishers(**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=networks/*}/childPublishers:batchWithdraw" + % client.transport._host, + args[1], + ) + + +def test_batch_withdraw_child_publishers_rest_flattened_error(transport: str = "rest"): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_withdraw_child_publishers( + child_publisher_service.BatchWithdrawChildPublishersRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChildPublisherServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ChildPublisherServiceClient( + 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 = ChildPublisherServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChildPublisherServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChildPublisherServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChildPublisherServiceRestTransport, + ], +) +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_rest(): + transport = ChildPublisherServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_child_publisher_rest_bad_request( + request_type=child_publisher_service.GetChildPublisherRequest, +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/childPublishers/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.get_child_publisher(request) + + +@pytest.mark.parametrize( + "request_type", + [ + child_publisher_service.GetChildPublisherRequest, + dict, + ], +) +def test_get_child_publisher_rest_call_success(request_type): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/childPublishers/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 = child_publisher_messages.ChildPublisher( + name="name_value", + display_name="display_name_value", + email="email_value", + child_network="child_network_value", + delegation_type=mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT, + parent_revenue_share_millipercent=3516, + seller_id="seller_id_value", + readiness_status=mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE, + invitation_status=mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED, + approval_status=mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED, + identity_verification_status=mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT, + address_verification_status=mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT, + pending_onboarding_tasks=[ + mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION + ], + account_status=mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED, + approved_manage_account_revenue_share_millipercent=5287, + ) + + # 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 = child_publisher_messages.ChildPublisher.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_child_publisher(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, child_publisher_messages.ChildPublisher) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.email == "email_value" + assert response.child_network == "child_network_value" + assert ( + response.delegation_type + == mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT + ) + assert response.parent_revenue_share_millipercent == 3516 + assert response.seller_id == "seller_id_value" + assert ( + response.readiness_status + == mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE + ) + assert ( + response.invitation_status + == mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED + ) + assert ( + response.approval_status + == mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED + ) + assert ( + response.identity_verification_status + == mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT + ) + assert ( + response.address_verification_status + == mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT + ) + assert response.pending_onboarding_tasks == [ + mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION + ] + assert ( + response.account_status + == mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED + ) + assert response.approved_manage_account_revenue_share_millipercent == 5287 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_child_publisher_rest_interceptors(null_interceptor): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChildPublisherServiceRestInterceptor(), + ) + client = ChildPublisherServiceClient(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.ChildPublisherServiceRestInterceptor, "post_get_child_publisher" + ) as post, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_get_child_publisher_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, "pre_get_child_publisher" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = child_publisher_service.GetChildPublisherRequest.pb( + child_publisher_service.GetChildPublisherRequest() + ) + 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 = child_publisher_messages.ChildPublisher.to_json( + child_publisher_messages.ChildPublisher() + ) + req.return_value.content = return_value + + request = child_publisher_service.GetChildPublisherRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = child_publisher_messages.ChildPublisher() + post_with_metadata.return_value = ( + child_publisher_messages.ChildPublisher(), + metadata, + ) + + client.get_child_publisher( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_child_publishers_rest_bad_request( + request_type=child_publisher_service.ListChildPublishersRequest, +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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_child_publishers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + child_publisher_service.ListChildPublishersRequest, + dict, + ], +) +def test_list_child_publishers_rest_call_success(request_type): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = child_publisher_service.ListChildPublishersResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # 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 = child_publisher_service.ListChildPublishersResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_child_publishers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChildPublishersPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_child_publishers_rest_interceptors(null_interceptor): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChildPublisherServiceRestInterceptor(), + ) + client = ChildPublisherServiceClient(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.ChildPublisherServiceRestInterceptor, + "post_list_child_publishers", + ) as post, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_list_child_publishers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, "pre_list_child_publishers" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = child_publisher_service.ListChildPublishersRequest.pb( + child_publisher_service.ListChildPublishersRequest() + ) + 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 = child_publisher_service.ListChildPublishersResponse.to_json( + child_publisher_service.ListChildPublishersResponse() + ) + req.return_value.content = return_value + + request = child_publisher_service.ListChildPublishersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = child_publisher_service.ListChildPublishersResponse() + post_with_metadata.return_value = ( + child_publisher_service.ListChildPublishersResponse(), + metadata, + ) + + client.list_child_publishers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_child_publisher_rest_bad_request( + request_type=child_publisher_service.CreateChildPublisherRequest, +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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_child_publisher(request) + + +@pytest.mark.parametrize( + "request_type", + [ + child_publisher_service.CreateChildPublisherRequest, + dict, + ], +) +def test_create_child_publisher_rest_call_success(request_type): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request_init["child_publisher"] = { + "name": "name_value", + "display_name": "display_name_value", + "email": "email_value", + "child_network": "child_network_value", + "delegation_type": 1, + "parent_revenue_share_millipercent": 3516, + "seller_id": "seller_id_value", + "readiness_status": 1, + "invitation_status": 1, + "approval_status": 1, + "identity_verification_status": 1, + "address_verification_status": 1, + "pending_onboarding_tasks": [1], + "account_status": 1, + "approved_manage_account_revenue_share_millipercent": 5287, + } + # 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 = child_publisher_service.CreateChildPublisherRequest.meta.fields[ + "child_publisher" + ] + + 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["child_publisher"].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["child_publisher"][field])): + del request_init["child_publisher"][field][i][subfield] + else: + del request_init["child_publisher"][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 = child_publisher_messages.ChildPublisher( + name="name_value", + display_name="display_name_value", + email="email_value", + child_network="child_network_value", + delegation_type=mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT, + parent_revenue_share_millipercent=3516, + seller_id="seller_id_value", + readiness_status=mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE, + invitation_status=mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED, + approval_status=mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED, + identity_verification_status=mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT, + address_verification_status=mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT, + pending_onboarding_tasks=[ + mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION + ], + account_status=mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED, + approved_manage_account_revenue_share_millipercent=5287, + ) + + # 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 = child_publisher_messages.ChildPublisher.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_child_publisher(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, child_publisher_messages.ChildPublisher) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.email == "email_value" + assert response.child_network == "child_network_value" + assert ( + response.delegation_type + == mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT + ) + assert response.parent_revenue_share_millipercent == 3516 + assert response.seller_id == "seller_id_value" + assert ( + response.readiness_status + == mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE + ) + assert ( + response.invitation_status + == mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED + ) + assert ( + response.approval_status + == mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED + ) + assert ( + response.identity_verification_status + == mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT + ) + assert ( + response.address_verification_status + == mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT + ) + assert response.pending_onboarding_tasks == [ + mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION + ] + assert ( + response.account_status + == mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED + ) + assert response.approved_manage_account_revenue_share_millipercent == 5287 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_child_publisher_rest_interceptors(null_interceptor): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChildPublisherServiceRestInterceptor(), + ) + client = ChildPublisherServiceClient(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.ChildPublisherServiceRestInterceptor, + "post_create_child_publisher", + ) as post, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_create_child_publisher_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "pre_create_child_publisher", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = child_publisher_service.CreateChildPublisherRequest.pb( + child_publisher_service.CreateChildPublisherRequest() + ) + 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 = child_publisher_messages.ChildPublisher.to_json( + child_publisher_messages.ChildPublisher() + ) + req.return_value.content = return_value + + request = child_publisher_service.CreateChildPublisherRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = child_publisher_messages.ChildPublisher() + post_with_metadata.return_value = ( + child_publisher_messages.ChildPublisher(), + metadata, + ) + + client.create_child_publisher( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_create_child_publishers_rest_bad_request( + request_type=child_publisher_service.BatchCreateChildPublishersRequest, +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_create_child_publishers(request) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ChildPublisherServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ChildPublisherServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ChildPublisherServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.parametrize( + "request_type", + [ + child_publisher_service.BatchCreateChildPublishersRequest, + dict, + ], +) +def test_batch_create_child_publishers_rest_call_success(request_type): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ChildPublisherServiceClient( - 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 = ChildPublisherServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = child_publisher_service.BatchCreateChildPublishersResponse() + + # 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 = child_publisher_service.BatchCreateChildPublishersResponse.pb( + return_value ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_child_publishers(request) - # It is an error to provide scopes and a transport instance. - transport = transports.ChildPublisherServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Establish that the response is the type that we expect. + assert isinstance( + response, child_publisher_service.BatchCreateChildPublishersResponse ) - with pytest.raises(ValueError): - client = ChildPublisherServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_child_publishers_rest_interceptors(null_interceptor): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChildPublisherServiceRestInterceptor(), ) client = ChildPublisherServiceClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_batch_create_child_publishers", + ) as post, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_batch_create_child_publishers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "pre_batch_create_child_publishers", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = child_publisher_service.BatchCreateChildPublishersRequest.pb( + child_publisher_service.BatchCreateChildPublishersRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } -@pytest.mark.parametrize( - "transport_class", - [ - transports.ChildPublisherServiceRestTransport, - ], -) -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() + 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 = ( + child_publisher_service.BatchCreateChildPublishersResponse.to_json( + child_publisher_service.BatchCreateChildPublishersResponse() + ) + ) + req.return_value.content = return_value + + request = child_publisher_service.BatchCreateChildPublishersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = child_publisher_service.BatchCreateChildPublishersResponse() + post_with_metadata.return_value = ( + child_publisher_service.BatchCreateChildPublishersResponse(), + metadata, + ) + client.batch_create_child_publishers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = ChildPublisherServiceClient.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_get_child_publisher_rest_bad_request( - request_type=child_publisher_service.GetChildPublisherRequest, +def test_update_child_publisher_rest_bad_request( + request_type=child_publisher_service.UpdateChildPublisherRequest, ): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1/childPublishers/sample2"} + request_init = { + "child_publisher": {"name": "networks/sample1/childPublishers/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2586,23 +4182,111 @@ def test_get_child_publisher_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_child_publisher(request) + client.update_child_publisher(request) @pytest.mark.parametrize( "request_type", [ - child_publisher_service.GetChildPublisherRequest, + child_publisher_service.UpdateChildPublisherRequest, dict, ], ) -def test_get_child_publisher_rest_call_success(request_type): +def test_update_child_publisher_rest_call_success(request_type): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1/childPublishers/sample2"} + request_init = { + "child_publisher": {"name": "networks/sample1/childPublishers/sample2"} + } + request_init["child_publisher"] = { + "name": "networks/sample1/childPublishers/sample2", + "display_name": "display_name_value", + "email": "email_value", + "child_network": "child_network_value", + "delegation_type": 1, + "parent_revenue_share_millipercent": 3516, + "seller_id": "seller_id_value", + "readiness_status": 1, + "invitation_status": 1, + "approval_status": 1, + "identity_verification_status": 1, + "address_verification_status": 1, + "pending_onboarding_tasks": [1], + "account_status": 1, + "approved_manage_account_revenue_share_millipercent": 5287, + } + # 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 = child_publisher_service.UpdateChildPublisherRequest.meta.fields[ + "child_publisher" + ] + + 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["child_publisher"].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["child_publisher"][field])): + del request_init["child_publisher"][field][i][subfield] + else: + del request_init["child_publisher"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -2638,7 +4322,7 @@ def test_get_child_publisher_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_child_publisher(request) + response = client.update_child_publisher(request) # Establish that the response is the type that we expect. assert isinstance(response, child_publisher_messages.ChildPublisher) @@ -2683,7 +4367,7 @@ def test_get_child_publisher_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_child_publisher_rest_interceptors(null_interceptor): +def test_update_child_publisher_rest_interceptors(null_interceptor): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2696,21 +4380,23 @@ def test_get_child_publisher_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.ChildPublisherServiceRestInterceptor, "post_get_child_publisher" + transports.ChildPublisherServiceRestInterceptor, + "post_update_child_publisher", ) as post, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_get_child_publisher_with_metadata", + "post_update_child_publisher_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ChildPublisherServiceRestInterceptor, "pre_get_child_publisher" + transports.ChildPublisherServiceRestInterceptor, + "pre_update_child_publisher", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = child_publisher_service.GetChildPublisherRequest.pb( - child_publisher_service.GetChildPublisherRequest() + pb_message = child_publisher_service.UpdateChildPublisherRequest.pb( + child_publisher_service.UpdateChildPublisherRequest() ) transcode.return_value = { "method": "post", @@ -2727,7 +4413,7 @@ def test_get_child_publisher_rest_interceptors(null_interceptor): ) req.return_value.content = return_value - request = child_publisher_service.GetChildPublisherRequest() + request = child_publisher_service.UpdateChildPublisherRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2739,148 +4425,7 @@ def test_get_child_publisher_rest_interceptors(null_interceptor): metadata, ) - client.get_child_publisher( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_child_publishers_rest_bad_request( - request_type=child_publisher_service.ListChildPublishersRequest, -): - client = ChildPublisherServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "networks/sample1"} - 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_child_publishers(request) - - -@pytest.mark.parametrize( - "request_type", - [ - child_publisher_service.ListChildPublishersRequest, - dict, - ], -) -def test_list_child_publishers_rest_call_success(request_type): - client = ChildPublisherServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "networks/sample1"} - 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 = child_publisher_service.ListChildPublishersResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - - # 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 = child_publisher_service.ListChildPublishersResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_child_publishers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChildPublishersPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_child_publishers_rest_interceptors(null_interceptor): - transport = transports.ChildPublisherServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.ChildPublisherServiceRestInterceptor(), - ) - client = ChildPublisherServiceClient(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.ChildPublisherServiceRestInterceptor, - "post_list_child_publishers", - ) as post, - mock.patch.object( - transports.ChildPublisherServiceRestInterceptor, - "post_list_child_publishers_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.ChildPublisherServiceRestInterceptor, "pre_list_child_publishers" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = child_publisher_service.ListChildPublishersRequest.pb( - child_publisher_service.ListChildPublishersRequest() - ) - 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 = child_publisher_service.ListChildPublishersResponse.to_json( - child_publisher_service.ListChildPublishersResponse() - ) - req.return_value.content = return_value - - request = child_publisher_service.ListChildPublishersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = child_publisher_service.ListChildPublishersResponse() - post_with_metadata.return_value = ( - child_publisher_service.ListChildPublishersResponse(), - metadata, - ) - - client.list_child_publishers( + client.update_child_publisher( request, metadata=[ ("key", "val"), @@ -2893,8 +4438,8 @@ def test_list_child_publishers_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_child_publisher_rest_bad_request( - request_type=child_publisher_service.CreateChildPublisherRequest, +def test_batch_update_child_publishers_rest_bad_request( + request_type=child_publisher_service.BatchUpdateChildPublishersRequest, ): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2916,190 +4461,52 @@ def test_create_child_publisher_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_child_publisher(request) + client.batch_update_child_publishers(request) @pytest.mark.parametrize( "request_type", [ - child_publisher_service.CreateChildPublisherRequest, + child_publisher_service.BatchUpdateChildPublishersRequest, dict, ], ) -def test_create_child_publisher_rest_call_success(request_type): +def test_batch_update_child_publishers_rest_call_success(request_type): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"parent": "networks/sample1"} - request_init["child_publisher"] = { - "name": "name_value", - "display_name": "display_name_value", - "email": "email_value", - "child_network": "child_network_value", - "delegation_type": 1, - "parent_revenue_share_millipercent": 3516, - "seller_id": "seller_id_value", - "readiness_status": 1, - "invitation_status": 1, - "approval_status": 1, - "identity_verification_status": 1, - "address_verification_status": 1, - "pending_onboarding_tasks": [1], - "account_status": 1, - "approved_manage_account_revenue_share_millipercent": 5287, - } - # 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 = child_publisher_service.CreateChildPublisherRequest.meta.fields[ - "child_publisher" - ] - - 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["child_publisher"].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["child_publisher"][field])): - del request_init["child_publisher"][field][i][subfield] - else: - del request_init["child_publisher"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} 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 = child_publisher_messages.ChildPublisher( - name="name_value", - display_name="display_name_value", - email="email_value", - child_network="child_network_value", - delegation_type=mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT, - parent_revenue_share_millipercent=3516, - seller_id="seller_id_value", - readiness_status=mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE, - invitation_status=mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED, - approval_status=mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED, - identity_verification_status=mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT, - address_verification_status=mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT, - pending_onboarding_tasks=[ - mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION - ], - account_status=mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED, - approved_manage_account_revenue_share_millipercent=5287, - ) + return_value = child_publisher_service.BatchUpdateChildPublishersResponse() # 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 = child_publisher_messages.ChildPublisher.pb(return_value) + return_value = child_publisher_service.BatchUpdateChildPublishersResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_child_publisher(request) + response = client.batch_update_child_publishers(request) # Establish that the response is the type that we expect. - assert isinstance(response, child_publisher_messages.ChildPublisher) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.email == "email_value" - assert response.child_network == "child_network_value" - assert ( - response.delegation_type - == mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT - ) - assert response.parent_revenue_share_millipercent == 3516 - assert response.seller_id == "seller_id_value" - assert ( - response.readiness_status - == mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE - ) - assert ( - response.invitation_status - == mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED - ) - assert ( - response.approval_status - == mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED - ) - assert ( - response.identity_verification_status - == mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT - ) - assert ( - response.address_verification_status - == mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT - ) - assert response.pending_onboarding_tasks == [ - mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION - ] - assert ( - response.account_status - == mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED + assert isinstance( + response, child_publisher_service.BatchUpdateChildPublishersResponse ) - assert response.approved_manage_account_revenue_share_millipercent == 5287 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_child_publisher_rest_interceptors(null_interceptor): +def test_batch_update_child_publishers_rest_interceptors(null_interceptor): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3113,22 +4520,22 @@ def test_create_child_publisher_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_create_child_publisher", + "post_batch_update_child_publishers", ) as post, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_create_child_publisher_with_metadata", + "post_batch_update_child_publishers_with_metadata", ) as post_with_metadata, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "pre_create_child_publisher", + "pre_batch_update_child_publishers", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = child_publisher_service.CreateChildPublisherRequest.pb( - child_publisher_service.CreateChildPublisherRequest() + pb_message = child_publisher_service.BatchUpdateChildPublishersRequest.pb( + child_publisher_service.BatchUpdateChildPublishersRequest() ) transcode.return_value = { "method": "post", @@ -3140,24 +4547,26 @@ def test_create_child_publisher_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 = child_publisher_messages.ChildPublisher.to_json( - child_publisher_messages.ChildPublisher() + return_value = ( + child_publisher_service.BatchUpdateChildPublishersResponse.to_json( + child_publisher_service.BatchUpdateChildPublishersResponse() + ) ) req.return_value.content = return_value - request = child_publisher_service.CreateChildPublisherRequest() + request = child_publisher_service.BatchUpdateChildPublishersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = child_publisher_messages.ChildPublisher() + post.return_value = child_publisher_service.BatchUpdateChildPublishersResponse() post_with_metadata.return_value = ( - child_publisher_messages.ChildPublisher(), + child_publisher_service.BatchUpdateChildPublishersResponse(), metadata, ) - client.create_child_publisher( + client.batch_update_child_publishers( request, metadata=[ ("key", "val"), @@ -3170,8 +4579,8 @@ def test_create_child_publisher_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_batch_create_child_publishers_rest_bad_request( - request_type=child_publisher_service.BatchCreateChildPublishersRequest, +def test_batch_resend_child_publisher_invitation_emails_rest_bad_request( + request_type=child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, ): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -3193,17 +4602,17 @@ def test_batch_create_child_publishers_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.batch_create_child_publishers(request) + client.batch_resend_child_publisher_invitation_emails(request) @pytest.mark.parametrize( "request_type", [ - child_publisher_service.BatchCreateChildPublishersRequest, + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest, dict, ], ) -def test_batch_create_child_publishers_rest_call_success(request_type): +def test_batch_resend_child_publisher_invitation_emails_rest_call_success(request_type): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3215,30 +4624,35 @@ def test_batch_create_child_publishers_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 = child_publisher_service.BatchCreateChildPublishersResponse() + return_value = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() + ) # 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 = child_publisher_service.BatchCreateChildPublishersResponse.pb( + return_value = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_create_child_publishers(request) + response = client.batch_resend_child_publisher_invitation_emails(request) # Establish that the response is the type that we expect. assert isinstance( - response, child_publisher_service.BatchCreateChildPublishersResponse + response, + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse, ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_child_publishers_rest_interceptors(null_interceptor): +def test_batch_resend_child_publisher_invitation_emails_rest_interceptors( + null_interceptor, +): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3252,22 +4666,22 @@ def test_batch_create_child_publishers_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_batch_create_child_publishers", + "post_batch_resend_child_publisher_invitation_emails", ) as post, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_batch_create_child_publishers_with_metadata", + "post_batch_resend_child_publisher_invitation_emails_with_metadata", ) as post_with_metadata, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "pre_batch_create_child_publishers", + "pre_batch_resend_child_publisher_invitation_emails", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = child_publisher_service.BatchCreateChildPublishersRequest.pb( - child_publisher_service.BatchCreateChildPublishersRequest() + pb_message = child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest.pb( + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest() ) transcode.return_value = { "method": "post", @@ -3279,26 +4693,28 @@ def test_batch_create_child_publishers_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 = ( - child_publisher_service.BatchCreateChildPublishersResponse.to_json( - child_publisher_service.BatchCreateChildPublishersResponse() - ) + return_value = child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse.to_json( + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() ) req.return_value.content = return_value - request = child_publisher_service.BatchCreateChildPublishersRequest() + request = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest() + ) metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = child_publisher_service.BatchCreateChildPublishersResponse() + post.return_value = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse() + ) post_with_metadata.return_value = ( - child_publisher_service.BatchCreateChildPublishersResponse(), + child_publisher_service.BatchResendChildPublisherInvitationEmailsResponse(), metadata, ) - client.batch_create_child_publishers( + client.batch_resend_child_publisher_invitation_emails( request, metadata=[ ("key", "val"), @@ -3311,16 +4727,14 @@ def test_batch_create_child_publishers_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_child_publisher_rest_bad_request( - request_type=child_publisher_service.UpdateChildPublisherRequest, +def test_batch_renegotiate_child_publisher_agreements_rest_bad_request( + request_type=child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, ): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "child_publisher": {"name": "networks/sample1/childPublishers/sample2"} - } + request_init = {"parent": "networks/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3336,192 +4750,202 @@ def test_update_child_publisher_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_child_publisher(request) + client.batch_renegotiate_child_publisher_agreements(request) @pytest.mark.parametrize( "request_type", [ - child_publisher_service.UpdateChildPublisherRequest, + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest, dict, ], ) -def test_update_child_publisher_rest_call_success(request_type): +def test_batch_renegotiate_child_publisher_agreements_rest_call_success(request_type): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "child_publisher": {"name": "networks/sample1/childPublishers/sample2"} - } - request_init["child_publisher"] = { - "name": "networks/sample1/childPublishers/sample2", - "display_name": "display_name_value", - "email": "email_value", - "child_network": "child_network_value", - "delegation_type": 1, - "parent_revenue_share_millipercent": 3516, - "seller_id": "seller_id_value", - "readiness_status": 1, - "invitation_status": 1, - "approval_status": 1, - "identity_verification_status": 1, - "address_verification_status": 1, - "pending_onboarding_tasks": [1], - "account_status": 1, - "approved_manage_account_revenue_share_millipercent": 5287, - } - # 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 + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) - # Determine if the message type is proto-plus or protobuf - test_field = child_publisher_service.UpdateChildPublisherRequest.meta.fields[ - "child_publisher" - ] + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + ) - 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 = [] + # 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 = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_renegotiate_child_publisher_agreements(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse, + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_renegotiate_child_publisher_agreements_rest_interceptors( + null_interceptor, +): + transport = transports.ChildPublisherServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChildPublisherServiceRestInterceptor(), + ) + client = ChildPublisherServiceClient(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.ChildPublisherServiceRestInterceptor, + "post_batch_renegotiate_child_publisher_agreements", + ) as post, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "post_batch_renegotiate_child_publisher_agreements_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ChildPublisherServiceRestInterceptor, + "pre_batch_renegotiate_child_publisher_agreements", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest.pb( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest() + ) + 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 = child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse.to_json( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + ) + req.return_value.content = return_value + + request = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse() + ) + post_with_metadata.return_value = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsResponse(), + metadata, + ) + + client.batch_renegotiate_child_publisher_agreements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() - 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) - ] +def test_batch_reject_child_publishers_rest_bad_request( + request_type=child_publisher_service.BatchRejectChildPublishersRequest, +): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) - subfields_not_in_runtime = [] + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_reject_child_publishers(request) - # 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["child_publisher"].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, - } - ) +@pytest.mark.parametrize( + "request_type", + [ + child_publisher_service.BatchRejectChildPublishersRequest, + dict, + ], +) +def test_batch_reject_child_publishers_rest_call_success(request_type): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # 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["child_publisher"][field])): - del request_init["child_publisher"][field][i][subfield] - else: - del request_init["child_publisher"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} 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 = child_publisher_messages.ChildPublisher( - name="name_value", - display_name="display_name_value", - email="email_value", - child_network="child_network_value", - delegation_type=mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT, - parent_revenue_share_millipercent=3516, - seller_id="seller_id_value", - readiness_status=mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE, - invitation_status=mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED, - approval_status=mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED, - identity_verification_status=mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT, - address_verification_status=mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT, - pending_onboarding_tasks=[ - mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION - ], - account_status=mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED, - approved_manage_account_revenue_share_millipercent=5287, - ) + return_value = child_publisher_service.BatchRejectChildPublishersResponse() # 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 = child_publisher_messages.ChildPublisher.pb(return_value) + return_value = child_publisher_service.BatchRejectChildPublishersResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_child_publisher(request) + response = client.batch_reject_child_publishers(request) # Establish that the response is the type that we expect. - assert isinstance(response, child_publisher_messages.ChildPublisher) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.email == "email_value" - assert response.child_network == "child_network_value" - assert ( - response.delegation_type - == mcm_enums.DelegationTypeEnum.DelegationType.MANAGE_ACCOUNT - ) - assert response.parent_revenue_share_millipercent == 3516 - assert response.seller_id == "seller_id_value" - assert ( - response.readiness_status - == mcm_enums.McmReadinessStatusEnum.McmReadinessStatus.INACTIVE - ) - assert ( - response.invitation_status - == mcm_enums.DelegationInvitationStatusEnum.DelegationInvitationStatus.ACCEPTED - ) - assert ( - response.approval_status - == mcm_enums.DelegationApprovalStatusEnum.DelegationApprovalStatus.APPROVED - ) - assert ( - response.identity_verification_status - == mcm_enums.ChildPublisherIdentityVerificationStatusEnum.ChildPublisherIdentityVerificationStatus.EXEMPT - ) - assert ( - response.address_verification_status - == mcm_enums.ChildPublisherAddressVerificationStatusEnum.ChildPublisherAddressVerificationStatus.EXEMPT - ) - assert response.pending_onboarding_tasks == [ - mcm_enums.ChildPublisherOnboardingTaskEnum.ChildPublisherOnboardingTask.BILLING_PROFILE_CREATION - ] - assert ( - response.account_status - == mcm_enums.DelegationAccountStatusEnum.DelegationAccountStatus.INVITED + assert isinstance( + response, child_publisher_service.BatchRejectChildPublishersResponse ) - assert response.approved_manage_account_revenue_share_millipercent == 5287 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_child_publisher_rest_interceptors(null_interceptor): +def test_batch_reject_child_publishers_rest_interceptors(null_interceptor): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3535,22 +4959,22 @@ def test_update_child_publisher_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_update_child_publisher", + "post_batch_reject_child_publishers", ) as post, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_update_child_publisher_with_metadata", + "post_batch_reject_child_publishers_with_metadata", ) as post_with_metadata, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "pre_update_child_publisher", + "pre_batch_reject_child_publishers", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = child_publisher_service.UpdateChildPublisherRequest.pb( - child_publisher_service.UpdateChildPublisherRequest() + pb_message = child_publisher_service.BatchRejectChildPublishersRequest.pb( + child_publisher_service.BatchRejectChildPublishersRequest() ) transcode.return_value = { "method": "post", @@ -3562,24 +4986,26 @@ def test_update_child_publisher_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 = child_publisher_messages.ChildPublisher.to_json( - child_publisher_messages.ChildPublisher() + return_value = ( + child_publisher_service.BatchRejectChildPublishersResponse.to_json( + child_publisher_service.BatchRejectChildPublishersResponse() + ) ) req.return_value.content = return_value - request = child_publisher_service.UpdateChildPublisherRequest() + request = child_publisher_service.BatchRejectChildPublishersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = child_publisher_messages.ChildPublisher() + post.return_value = child_publisher_service.BatchRejectChildPublishersResponse() post_with_metadata.return_value = ( - child_publisher_messages.ChildPublisher(), + child_publisher_service.BatchRejectChildPublishersResponse(), metadata, ) - client.update_child_publisher( + client.batch_reject_child_publishers( request, metadata=[ ("key", "val"), @@ -3592,8 +5018,8 @@ def test_update_child_publisher_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_batch_update_child_publishers_rest_bad_request( - request_type=child_publisher_service.BatchUpdateChildPublishersRequest, +def test_batch_withdraw_child_publishers_rest_bad_request( + request_type=child_publisher_service.BatchWithdrawChildPublishersRequest, ): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -3615,17 +5041,17 @@ def test_batch_update_child_publishers_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.batch_update_child_publishers(request) + client.batch_withdraw_child_publishers(request) @pytest.mark.parametrize( "request_type", [ - child_publisher_service.BatchUpdateChildPublishersRequest, + child_publisher_service.BatchWithdrawChildPublishersRequest, dict, ], ) -def test_batch_update_child_publishers_rest_call_success(request_type): +def test_batch_withdraw_child_publishers_rest_call_success(request_type): client = ChildPublisherServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3637,30 +5063,30 @@ def test_batch_update_child_publishers_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 = child_publisher_service.BatchUpdateChildPublishersResponse() + return_value = child_publisher_service.BatchWithdrawChildPublishersResponse() # 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 = child_publisher_service.BatchUpdateChildPublishersResponse.pb( + return_value = child_publisher_service.BatchWithdrawChildPublishersResponse.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.batch_update_child_publishers(request) + response = client.batch_withdraw_child_publishers(request) # Establish that the response is the type that we expect. assert isinstance( - response, child_publisher_service.BatchUpdateChildPublishersResponse + response, child_publisher_service.BatchWithdrawChildPublishersResponse ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_child_publishers_rest_interceptors(null_interceptor): +def test_batch_withdraw_child_publishers_rest_interceptors(null_interceptor): transport = transports.ChildPublisherServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3674,22 +5100,22 @@ def test_batch_update_child_publishers_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_batch_update_child_publishers", + "post_batch_withdraw_child_publishers", ) as post, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "post_batch_update_child_publishers_with_metadata", + "post_batch_withdraw_child_publishers_with_metadata", ) as post_with_metadata, mock.patch.object( transports.ChildPublisherServiceRestInterceptor, - "pre_batch_update_child_publishers", + "pre_batch_withdraw_child_publishers", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = child_publisher_service.BatchUpdateChildPublishersRequest.pb( - child_publisher_service.BatchUpdateChildPublishersRequest() + pb_message = child_publisher_service.BatchWithdrawChildPublishersRequest.pb( + child_publisher_service.BatchWithdrawChildPublishersRequest() ) transcode.return_value = { "method": "post", @@ -3702,25 +5128,27 @@ def test_batch_update_child_publishers_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = ( - child_publisher_service.BatchUpdateChildPublishersResponse.to_json( - child_publisher_service.BatchUpdateChildPublishersResponse() + child_publisher_service.BatchWithdrawChildPublishersResponse.to_json( + child_publisher_service.BatchWithdrawChildPublishersResponse() ) ) req.return_value.content = return_value - request = child_publisher_service.BatchUpdateChildPublishersRequest() + request = child_publisher_service.BatchWithdrawChildPublishersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = child_publisher_service.BatchUpdateChildPublishersResponse() + post.return_value = ( + child_publisher_service.BatchWithdrawChildPublishersResponse() + ) post_with_metadata.return_value = ( - child_publisher_service.BatchUpdateChildPublishersResponse(), + child_publisher_service.BatchWithdrawChildPublishersResponse(), metadata, ) - client.batch_update_child_publishers( + client.batch_withdraw_child_publishers( request, metadata=[ ("key", "val"), @@ -3992,6 +5420,95 @@ def test_batch_update_child_publishers_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_batch_resend_child_publisher_invitation_emails_empty_call_rest(): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_resend_child_publisher_invitation_emails), + "__call__", + ) as call: + client.batch_resend_child_publisher_invitation_emails(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + child_publisher_service.BatchResendChildPublisherInvitationEmailsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_renegotiate_child_publisher_agreements_empty_call_rest(): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_renegotiate_child_publisher_agreements), "__call__" + ) as call: + client.batch_renegotiate_child_publisher_agreements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + child_publisher_service.BatchRenegotiateChildPublisherAgreementsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_reject_child_publishers_empty_call_rest(): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_reject_child_publishers), "__call__" + ) as call: + client.batch_reject_child_publishers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = child_publisher_service.BatchRejectChildPublishersRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_withdraw_child_publishers_empty_call_rest(): + client = ChildPublisherServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_withdraw_child_publishers), "__call__" + ) as call: + client.batch_withdraw_child_publishers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = child_publisher_service.BatchWithdrawChildPublishersRequest() + assert args[0] == request_msg + + def test_child_publisher_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -4020,6 +5537,10 @@ def test_child_publisher_service_base_transport(): "batch_create_child_publishers", "update_child_publisher", "batch_update_child_publishers", + "batch_resend_child_publisher_invitation_emails", + "batch_renegotiate_child_publisher_agreements", + "batch_reject_child_publishers", + "batch_withdraw_child_publishers", "get_operation", "cancel_operation", ) @@ -4183,6 +5704,18 @@ def test_child_publisher_service_client_transport_session_collision(transport_na session1 = client1.transport.batch_update_child_publishers._session session2 = client2.transport.batch_update_child_publishers._session assert session1 != session2 + session1 = client1.transport.batch_resend_child_publisher_invitation_emails._session + session2 = client2.transport.batch_resend_child_publisher_invitation_emails._session + assert session1 != session2 + session1 = client1.transport.batch_renegotiate_child_publisher_agreements._session + session2 = client2.transport.batch_renegotiate_child_publisher_agreements._session + assert session1 != session2 + session1 = client1.transport.batch_reject_child_publishers._session + session2 = client2.transport.batch_reject_child_publishers._session + assert session1 != session2 + session1 = client1.transport.batch_withdraw_child_publishers._session + session2 = client2.transport.batch_withdraw_child_publishers._session + assert session1 != session2 def test_child_publisher_path(): diff --git a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_native_style_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_native_style_service.py new file mode 100644 index 000000000000..aac12661e8e2 --- /dev/null +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_native_style_service.py @@ -0,0 +1,4976 @@ +# -*- 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.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.ads.admanager_v1.services.native_style_service import ( + NativeStyleServiceClient, + pagers, + transports, +) +from google.ads.admanager_v1.types import ( + native_style_enums, + native_style_messages, + native_style_service, + request_platform_enum, + size, + size_type_enum, + targeted_video_bumper_type_enum, + targeting, + video_position_enum, +) + +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 NativeStyleServiceClient._get_default_mtls_endpoint(None) is None + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + NativeStyleServiceClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert NativeStyleServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NativeStyleServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NativeStyleServiceClient._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: + NativeStyleServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert NativeStyleServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert NativeStyleServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NativeStyleServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NativeStyleServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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): + NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._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 NativeStyleServiceClient._get_client_cert_source(None, False) is None + assert ( + NativeStyleServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + NativeStyleServiceClient._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 ( + NativeStyleServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + NativeStyleServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + NativeStyleServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NativeStyleServiceClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NativeStyleServiceClient._DEFAULT_UNIVERSE + default_endpoint = NativeStyleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = NativeStyleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + NativeStyleServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + NativeStyleServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == NativeStyleServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + NativeStyleServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + NativeStyleServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == NativeStyleServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + NativeStyleServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == NativeStyleServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + NativeStyleServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + NativeStyleServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + NativeStyleServiceClient._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 ( + NativeStyleServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + NativeStyleServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + NativeStyleServiceClient._get_universe_domain(None, None) + == NativeStyleServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + NativeStyleServiceClient._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 = NativeStyleServiceClient(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 = NativeStyleServiceClient(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", + [ + (NativeStyleServiceClient, "rest"), + ], +) +def test_native_style_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 == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.NativeStyleServiceRestTransport, "rest"), + ], +) +def test_native_style_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", + [ + (NativeStyleServiceClient, "rest"), + ], +) +def test_native_style_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 == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +def test_native_style_service_client_get_transport_class(): + transport = NativeStyleServiceClient.get_transport_class() + available_transports = [ + transports.NativeStyleServiceRestTransport, + ] + assert transport in available_transports + + transport = NativeStyleServiceClient.get_transport_class("rest") + assert transport == transports.NativeStyleServiceRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (NativeStyleServiceClient, transports.NativeStyleServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + NativeStyleServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NativeStyleServiceClient), +) +def test_native_style_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(NativeStyleServiceClient, "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(NativeStyleServiceClient, "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", + [ + ( + NativeStyleServiceClient, + transports.NativeStyleServiceRestTransport, + "rest", + "true", + ), + ( + NativeStyleServiceClient, + transports.NativeStyleServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + NativeStyleServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NativeStyleServiceClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_native_style_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", [NativeStyleServiceClient]) +@mock.patch.object( + NativeStyleServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(NativeStyleServiceClient), +) +def test_native_style_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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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", [NativeStyleServiceClient]) +@mock.patch.object( + NativeStyleServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(NativeStyleServiceClient), +) +def test_native_style_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NativeStyleServiceClient._DEFAULT_UNIVERSE + default_endpoint = NativeStyleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = NativeStyleServiceClient._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", + [ + (NativeStyleServiceClient, transports.NativeStyleServiceRestTransport, "rest"), + ], +) +def test_native_style_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", + [ + ( + NativeStyleServiceClient, + transports.NativeStyleServiceRestTransport, + "rest", + None, + ), + ], +) +def test_native_style_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_get_native_style_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 = NativeStyleServiceClient( + 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_native_style in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_native_style] = ( + mock_rpc + ) + + request = {} + client.get_native_style(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_native_style(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_native_style_rest_required_fields( + request_type=native_style_service.GetNativeStyleRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + 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_native_style._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_native_style._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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_messages.NativeStyle() + # 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 = native_style_messages.NativeStyle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_native_style(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_native_style_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_native_style._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_native_style_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_messages.NativeStyle() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "networks/sample1/nativeStyles/sample2"} + + # 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 = native_style_messages.NativeStyle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_native_style(**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=networks/*/nativeStyles/*}" % client.transport._host, args[1] + ) + + +def test_get_native_style_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + 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_native_style( + native_style_service.GetNativeStyleRequest(), + name="name_value", + ) + + +def test_list_native_styles_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 = NativeStyleServiceClient( + 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_native_styles in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_native_styles] = ( + mock_rpc + ) + + request = {} + client.list_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_native_styles(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_native_styles_rest_required_fields( + request_type=native_style_service.ListNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + 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_native_styles._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_native_styles._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", + "skip", + ) + ) + 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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.ListNativeStylesResponse() + # 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 = native_style_service.ListNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_native_styles(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_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_native_styles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "skip", + ) + ) + & set(("parent",)) + ) + + +def test_list_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.ListNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # 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 = native_style_service.ListNativeStylesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_native_styles(**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=networks/*}/nativeStyles" % client.transport._host, args[1] + ) + + +def test_list_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + 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_native_styles( + native_style_service.ListNativeStylesRequest(), + parent="parent_value", + ) + + +def test_list_native_styles_rest_pager(transport: str = "rest"): + client = NativeStyleServiceClient( + 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 = ( + native_style_service.ListNativeStylesResponse( + native_styles=[ + native_style_messages.NativeStyle(), + native_style_messages.NativeStyle(), + native_style_messages.NativeStyle(), + ], + next_page_token="abc", + ), + native_style_service.ListNativeStylesResponse( + native_styles=[], + next_page_token="def", + ), + native_style_service.ListNativeStylesResponse( + native_styles=[ + native_style_messages.NativeStyle(), + ], + next_page_token="ghi", + ), + native_style_service.ListNativeStylesResponse( + native_styles=[ + native_style_messages.NativeStyle(), + native_style_messages.NativeStyle(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + native_style_service.ListNativeStylesResponse.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": "networks/sample1"} + + pager = client.list_native_styles(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, native_style_messages.NativeStyle) for i in results) + + pages = list(client.list_native_styles(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_batch_create_native_styles_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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_native_styles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_native_styles + ] = mock_rpc + + request = {} + client.batch_create_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_native_styles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_native_styles_rest_required_fields( + request_type=native_style_service.BatchCreateNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + 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() + ).batch_create_native_styles._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() + ).batch_create_native_styles._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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.BatchCreateNativeStylesResponse() + # 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 = native_style_service.BatchCreateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_native_styles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_create_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_create_native_styles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +def test_batch_create_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.BatchCreateNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + requests=[ + native_style_service.CreateNativeStyleRequest(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 = native_style_service.BatchCreateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_create_native_styles(**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=networks/*}/nativeStyles:batchCreate" + % client.transport._host, + args[1], + ) + + +def test_batch_create_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_native_styles( + native_style_service.BatchCreateNativeStylesRequest(), + parent="parent_value", + requests=[ + native_style_service.CreateNativeStyleRequest(parent="parent_value") + ], + ) + + +def test_batch_update_native_styles_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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_native_styles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_update_native_styles + ] = mock_rpc + + request = {} + client.batch_update_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_native_styles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_update_native_styles_rest_required_fields( + request_type=native_style_service.BatchUpdateNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + 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() + ).batch_update_native_styles._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() + ).batch_update_native_styles._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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.BatchUpdateNativeStylesResponse() + # 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 = native_style_service.BatchUpdateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_update_native_styles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_update_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_update_native_styles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +def test_batch_update_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.BatchUpdateNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + requests=[ + native_style_service.UpdateNativeStyleRequest( + native_style=native_style_messages.NativeStyle(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 = native_style_service.BatchUpdateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_update_native_styles(**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=networks/*}/nativeStyles:batchUpdate" + % client.transport._host, + args[1], + ) + + +def test_batch_update_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_native_styles( + native_style_service.BatchUpdateNativeStylesRequest(), + parent="parent_value", + requests=[ + native_style_service.UpdateNativeStyleRequest( + native_style=native_style_messages.NativeStyle(name="name_value") + ) + ], + ) + + +def test_batch_activate_native_styles_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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_activate_native_styles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_activate_native_styles + ] = mock_rpc + + request = {} + client.batch_activate_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_activate_native_styles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_activate_native_styles_rest_required_fields( + request_type=native_style_service.BatchActivateNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_activate_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_activate_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.BatchActivateNativeStylesResponse() + # 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 = native_style_service.BatchActivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_activate_native_styles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_activate_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_activate_native_styles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_activate_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.BatchActivateNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = native_style_service.BatchActivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_activate_native_styles(**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=networks/*}/nativeStyles:batchActivate" + % client.transport._host, + args[1], + ) + + +def test_batch_activate_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_activate_native_styles( + native_style_service.BatchActivateNativeStylesRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_deactivate_native_styles_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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_deactivate_native_styles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_deactivate_native_styles + ] = mock_rpc + + request = {} + client.batch_deactivate_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_deactivate_native_styles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_deactivate_native_styles_rest_required_fields( + request_type=native_style_service.BatchDeactivateNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_deactivate_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_deactivate_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.BatchDeactivateNativeStylesResponse() + # 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 = native_style_service.BatchDeactivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_deactivate_native_styles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_deactivate_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_deactivate_native_styles._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_deactivate_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.BatchDeactivateNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = native_style_service.BatchDeactivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_deactivate_native_styles(**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=networks/*}/nativeStyles:batchDeactivate" + % client.transport._host, + args[1], + ) + + +def test_batch_deactivate_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_deactivate_native_styles( + native_style_service.BatchDeactivateNativeStylesRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_batch_archive_native_styles_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 = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_archive_native_styles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_archive_native_styles + ] = mock_rpc + + request = {} + client.batch_archive_native_styles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_archive_native_styles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_archive_native_styles_rest_required_fields( + request_type=native_style_service.BatchArchiveNativeStylesRequest, +): + transport_class = transports.NativeStyleServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_archive_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_archive_native_styles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = native_style_service.BatchArchiveNativeStylesResponse() + # 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 = native_style_service.BatchArchiveNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_archive_native_styles(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_archive_native_styles_rest_unset_required_fields(): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_archive_native_styles._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "names", + ) + ) + ) + + +def test_batch_archive_native_styles_rest_flattened(): + client = NativeStyleServiceClient( + 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 = native_style_service.BatchArchiveNativeStylesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "networks/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + names=["names_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 = native_style_service.BatchArchiveNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_archive_native_styles(**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=networks/*}/nativeStyles:batchArchive" + % client.transport._host, + args[1], + ) + + +def test_batch_archive_native_styles_rest_flattened_error(transport: str = "rest"): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_archive_native_styles( + native_style_service.BatchArchiveNativeStylesRequest(), + parent="parent_value", + names=["names_value"], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NativeStyleServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NativeStyleServiceClient( + 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 = NativeStyleServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NativeStyleServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NativeStyleServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NativeStyleServiceRestTransport, + ], +) +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_rest(): + transport = NativeStyleServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_native_style_rest_bad_request( + request_type=native_style_service.GetNativeStyleRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/nativeStyles/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.get_native_style(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.GetNativeStyleRequest, + dict, + ], +) +def test_get_native_style_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/nativeStyles/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 = native_style_messages.NativeStyle( + name="name_value", + creative_template="creative_template_value", + display_name="display_name_value", + html_snippet="html_snippet_value", + css_snippet="css_snippet_value", + status=native_style_enums.NativeStyleStatusEnum.NativeStyleStatus.ACTIVE, + ) + + # 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 = native_style_messages.NativeStyle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_native_style(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, native_style_messages.NativeStyle) + assert response.name == "name_value" + assert response.creative_template == "creative_template_value" + assert response.display_name == "display_name_value" + assert response.html_snippet == "html_snippet_value" + assert response.css_snippet == "css_snippet_value" + assert ( + response.status + == native_style_enums.NativeStyleStatusEnum.NativeStyleStatus.ACTIVE + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_native_style_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, "post_get_native_style" + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_get_native_style_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, "pre_get_native_style" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.GetNativeStyleRequest.pb( + native_style_service.GetNativeStyleRequest() + ) + 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 = native_style_messages.NativeStyle.to_json( + native_style_messages.NativeStyle() + ) + req.return_value.content = return_value + + request = native_style_service.GetNativeStyleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_messages.NativeStyle() + post_with_metadata.return_value = native_style_messages.NativeStyle(), metadata + + client.get_native_style( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_native_styles_rest_bad_request( + request_type=native_style_service.ListNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.ListNativeStylesRequest, + dict, + ], +) +def test_list_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.ListNativeStylesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # 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 = native_style_service.ListNativeStylesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNativeStylesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, "post_list_native_styles" + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_list_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, "pre_list_native_styles" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.ListNativeStylesRequest.pb( + native_style_service.ListNativeStylesRequest() + ) + 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 = native_style_service.ListNativeStylesResponse.to_json( + native_style_service.ListNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.ListNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.ListNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.ListNativeStylesResponse(), + metadata, + ) + + client.list_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_create_native_styles_rest_bad_request( + request_type=native_style_service.BatchCreateNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_create_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.BatchCreateNativeStylesRequest, + dict, + ], +) +def test_batch_create_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.BatchCreateNativeStylesResponse() + + # 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 = native_style_service.BatchCreateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, native_style_service.BatchCreateNativeStylesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, + "post_batch_create_native_styles", + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_batch_create_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "pre_batch_create_native_styles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.BatchCreateNativeStylesRequest.pb( + native_style_service.BatchCreateNativeStylesRequest() + ) + 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 = native_style_service.BatchCreateNativeStylesResponse.to_json( + native_style_service.BatchCreateNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.BatchCreateNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.BatchCreateNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.BatchCreateNativeStylesResponse(), + metadata, + ) + + client.batch_create_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_update_native_styles_rest_bad_request( + request_type=native_style_service.BatchUpdateNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_update_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.BatchUpdateNativeStylesRequest, + dict, + ], +) +def test_batch_update_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.BatchUpdateNativeStylesResponse() + + # 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 = native_style_service.BatchUpdateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_update_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, native_style_service.BatchUpdateNativeStylesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, + "post_batch_update_native_styles", + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_batch_update_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "pre_batch_update_native_styles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.BatchUpdateNativeStylesRequest.pb( + native_style_service.BatchUpdateNativeStylesRequest() + ) + 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 = native_style_service.BatchUpdateNativeStylesResponse.to_json( + native_style_service.BatchUpdateNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.BatchUpdateNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.BatchUpdateNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.BatchUpdateNativeStylesResponse(), + metadata, + ) + + client.batch_update_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_activate_native_styles_rest_bad_request( + request_type=native_style_service.BatchActivateNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_activate_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.BatchActivateNativeStylesRequest, + dict, + ], +) +def test_batch_activate_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.BatchActivateNativeStylesResponse() + + # 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 = native_style_service.BatchActivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_activate_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, native_style_service.BatchActivateNativeStylesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_activate_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, + "post_batch_activate_native_styles", + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_batch_activate_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "pre_batch_activate_native_styles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.BatchActivateNativeStylesRequest.pb( + native_style_service.BatchActivateNativeStylesRequest() + ) + 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 = native_style_service.BatchActivateNativeStylesResponse.to_json( + native_style_service.BatchActivateNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.BatchActivateNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.BatchActivateNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.BatchActivateNativeStylesResponse(), + metadata, + ) + + client.batch_activate_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_deactivate_native_styles_rest_bad_request( + request_type=native_style_service.BatchDeactivateNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_deactivate_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.BatchDeactivateNativeStylesRequest, + dict, + ], +) +def test_batch_deactivate_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.BatchDeactivateNativeStylesResponse() + + # 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 = native_style_service.BatchDeactivateNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_deactivate_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, native_style_service.BatchDeactivateNativeStylesResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_deactivate_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, + "post_batch_deactivate_native_styles", + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_batch_deactivate_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "pre_batch_deactivate_native_styles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.BatchDeactivateNativeStylesRequest.pb( + native_style_service.BatchDeactivateNativeStylesRequest() + ) + 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 = native_style_service.BatchDeactivateNativeStylesResponse.to_json( + native_style_service.BatchDeactivateNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.BatchDeactivateNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.BatchDeactivateNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.BatchDeactivateNativeStylesResponse(), + metadata, + ) + + client.batch_deactivate_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_archive_native_styles_rest_bad_request( + request_type=native_style_service.BatchArchiveNativeStylesRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_archive_native_styles(request) + + +@pytest.mark.parametrize( + "request_type", + [ + native_style_service.BatchArchiveNativeStylesRequest, + dict, + ], +) +def test_batch_archive_native_styles_rest_call_success(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "networks/sample1"} + 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 = native_style_service.BatchArchiveNativeStylesResponse() + + # 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 = native_style_service.BatchArchiveNativeStylesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_archive_native_styles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, native_style_service.BatchArchiveNativeStylesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_archive_native_styles_rest_interceptors(null_interceptor): + transport = transports.NativeStyleServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NativeStyleServiceRestInterceptor(), + ) + client = NativeStyleServiceClient(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.NativeStyleServiceRestInterceptor, + "post_batch_archive_native_styles", + ) as post, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "post_batch_archive_native_styles_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NativeStyleServiceRestInterceptor, + "pre_batch_archive_native_styles", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = native_style_service.BatchArchiveNativeStylesRequest.pb( + native_style_service.BatchArchiveNativeStylesRequest() + ) + 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 = native_style_service.BatchArchiveNativeStylesResponse.to_json( + native_style_service.BatchArchiveNativeStylesResponse() + ) + req.return_value.content = return_value + + request = native_style_service.BatchArchiveNativeStylesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = native_style_service.BatchArchiveNativeStylesResponse() + post_with_metadata.return_value = ( + native_style_service.BatchArchiveNativeStylesResponse(), + metadata, + ) + + client.batch_archive_native_styles( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "networks/sample1/operations/reports/runs/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "networks/sample1/operations/reports/runs/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "networks/sample1/operations/reports/runs/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "networks/sample1/operations/reports/runs/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_initialize_client_w_rest(): + client = NativeStyleServiceClient( + 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_get_native_style_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_native_style), "__call__") as call: + client.get_native_style(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.GetNativeStyleRequest() + assert args[0] == request_msg + + +# This 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_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_native_styles), "__call__" + ) as call: + client.list_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.ListNativeStylesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_native_styles), "__call__" + ) as call: + client.batch_create_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.BatchCreateNativeStylesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_native_styles), "__call__" + ) as call: + client.batch_update_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.BatchUpdateNativeStylesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_activate_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_activate_native_styles), "__call__" + ) as call: + client.batch_activate_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.BatchActivateNativeStylesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_deactivate_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_deactivate_native_styles), "__call__" + ) as call: + client.batch_deactivate_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.BatchDeactivateNativeStylesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_archive_native_styles_empty_call_rest(): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_archive_native_styles), "__call__" + ) as call: + client.batch_archive_native_styles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = native_style_service.BatchArchiveNativeStylesRequest() + assert args[0] == request_msg + + +def test_native_style_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NativeStyleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_native_style_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.ads.admanager_v1.services.native_style_service.transports.NativeStyleServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.NativeStyleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_native_style", + "list_native_styles", + "batch_create_native_styles", + "batch_update_native_styles", + "batch_activate_native_styles", + "batch_deactivate_native_styles", + "batch_archive_native_styles", + "get_operation", + "cancel_operation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_native_style_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.ads.admanager_v1.services.native_style_service.transports.NativeStyleServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NativeStyleServiceTransport( + 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/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ), + quota_project_id="octopus", + ) + + +def test_native_style_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.ads.admanager_v1.services.native_style_service.transports.NativeStyleServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NativeStyleServiceTransport() + adc.assert_called_once() + + +def test_native_style_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) + NativeStyleServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/admanager", + "https://www.googleapis.com/auth/admanager.readonly", + ), + quota_project_id=None, + ) + + +def test_native_style_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.NativeStyleServiceRestTransport( + 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", + [ + "rest", + ], +) +def test_native_style_service_host_no_port(transport_name): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="admanager.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "admanager.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_native_style_service_host_with_port(transport_name): + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="admanager.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "admanager.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://admanager.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_native_style_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NativeStyleServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NativeStyleServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_native_style._session + session2 = client2.transport.get_native_style._session + assert session1 != session2 + session1 = client1.transport.list_native_styles._session + session2 = client2.transport.list_native_styles._session + assert session1 != session2 + session1 = client1.transport.batch_create_native_styles._session + session2 = client2.transport.batch_create_native_styles._session + assert session1 != session2 + session1 = client1.transport.batch_update_native_styles._session + session2 = client2.transport.batch_update_native_styles._session + assert session1 != session2 + session1 = client1.transport.batch_activate_native_styles._session + session2 = client2.transport.batch_activate_native_styles._session + assert session1 != session2 + session1 = client1.transport.batch_deactivate_native_styles._session + session2 = client2.transport.batch_deactivate_native_styles._session + assert session1 != session2 + session1 = client1.transport.batch_archive_native_styles._session + session2 = client2.transport.batch_archive_native_styles._session + assert session1 != session2 + + +def test_ad_unit_path(): + network_code = "squid" + ad_unit = "clam" + expected = "networks/{network_code}/adUnits/{ad_unit}".format( + network_code=network_code, + ad_unit=ad_unit, + ) + actual = NativeStyleServiceClient.ad_unit_path(network_code, ad_unit) + assert expected == actual + + +def test_parse_ad_unit_path(): + expected = { + "network_code": "whelk", + "ad_unit": "octopus", + } + path = NativeStyleServiceClient.ad_unit_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_ad_unit_path(path) + assert expected == actual + + +def test_application_path(): + network_code = "oyster" + application = "nudibranch" + expected = "networks/{network_code}/applications/{application}".format( + network_code=network_code, + application=application, + ) + actual = NativeStyleServiceClient.application_path(network_code, application) + assert expected == actual + + +def test_parse_application_path(): + expected = { + "network_code": "cuttlefish", + "application": "mussel", + } + path = NativeStyleServiceClient.application_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_application_path(path) + assert expected == actual + + +def test_audience_segment_path(): + network_code = "winkle" + audience_segment = "nautilus" + expected = "networks/{network_code}/audienceSegments/{audience_segment}".format( + network_code=network_code, + audience_segment=audience_segment, + ) + actual = NativeStyleServiceClient.audience_segment_path( + network_code, audience_segment + ) + assert expected == actual + + +def test_parse_audience_segment_path(): + expected = { + "network_code": "scallop", + "audience_segment": "abalone", + } + path = NativeStyleServiceClient.audience_segment_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_audience_segment_path(path) + assert expected == actual + + +def test_bandwidth_group_path(): + network_code = "squid" + bandwidth_group = "clam" + expected = "networks/{network_code}/bandwidthGroups/{bandwidth_group}".format( + network_code=network_code, + bandwidth_group=bandwidth_group, + ) + actual = NativeStyleServiceClient.bandwidth_group_path( + network_code, bandwidth_group + ) + assert expected == actual + + +def test_parse_bandwidth_group_path(): + expected = { + "network_code": "whelk", + "bandwidth_group": "octopus", + } + path = NativeStyleServiceClient.bandwidth_group_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_bandwidth_group_path(path) + assert expected == actual + + +def test_browser_path(): + network_code = "oyster" + browser = "nudibranch" + expected = "networks/{network_code}/browsers/{browser}".format( + network_code=network_code, + browser=browser, + ) + actual = NativeStyleServiceClient.browser_path(network_code, browser) + assert expected == actual + + +def test_parse_browser_path(): + expected = { + "network_code": "cuttlefish", + "browser": "mussel", + } + path = NativeStyleServiceClient.browser_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_browser_path(path) + assert expected == actual + + +def test_browser_language_path(): + network_code = "winkle" + browser_language = "nautilus" + expected = "networks/{network_code}/browserLanguages/{browser_language}".format( + network_code=network_code, + browser_language=browser_language, + ) + actual = NativeStyleServiceClient.browser_language_path( + network_code, browser_language + ) + assert expected == actual + + +def test_parse_browser_language_path(): + expected = { + "network_code": "scallop", + "browser_language": "abalone", + } + path = NativeStyleServiceClient.browser_language_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_browser_language_path(path) + assert expected == actual + + +def test_cms_metadata_value_path(): + network_code = "squid" + cms_metadata_value = "clam" + expected = "networks/{network_code}/cmsMetadataValues/{cms_metadata_value}".format( + network_code=network_code, + cms_metadata_value=cms_metadata_value, + ) + actual = NativeStyleServiceClient.cms_metadata_value_path( + network_code, cms_metadata_value + ) + assert expected == actual + + +def test_parse_cms_metadata_value_path(): + expected = { + "network_code": "whelk", + "cms_metadata_value": "octopus", + } + path = NativeStyleServiceClient.cms_metadata_value_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_cms_metadata_value_path(path) + assert expected == actual + + +def test_content_path(): + network_code = "oyster" + content = "nudibranch" + expected = "networks/{network_code}/content/{content}".format( + network_code=network_code, + content=content, + ) + actual = NativeStyleServiceClient.content_path(network_code, content) + assert expected == actual + + +def test_parse_content_path(): + expected = { + "network_code": "cuttlefish", + "content": "mussel", + } + path = NativeStyleServiceClient.content_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_content_path(path) + assert expected == actual + + +def test_content_bundle_path(): + network_code = "winkle" + content_bundle = "nautilus" + expected = "networks/{network_code}/contentBundles/{content_bundle}".format( + network_code=network_code, + content_bundle=content_bundle, + ) + actual = NativeStyleServiceClient.content_bundle_path(network_code, content_bundle) + assert expected == actual + + +def test_parse_content_bundle_path(): + expected = { + "network_code": "scallop", + "content_bundle": "abalone", + } + path = NativeStyleServiceClient.content_bundle_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_content_bundle_path(path) + assert expected == actual + + +def test_creative_template_path(): + network_code = "squid" + creative_template = "clam" + expected = "networks/{network_code}/creativeTemplates/{creative_template}".format( + network_code=network_code, + creative_template=creative_template, + ) + actual = NativeStyleServiceClient.creative_template_path( + network_code, creative_template + ) + assert expected == actual + + +def test_parse_creative_template_path(): + expected = { + "network_code": "whelk", + "creative_template": "octopus", + } + path = NativeStyleServiceClient.creative_template_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_creative_template_path(path) + assert expected == actual + + +def test_custom_targeting_key_path(): + network_code = "oyster" + custom_targeting_key = "nudibranch" + expected = ( + "networks/{network_code}/customTargetingKeys/{custom_targeting_key}".format( + network_code=network_code, + custom_targeting_key=custom_targeting_key, + ) + ) + actual = NativeStyleServiceClient.custom_targeting_key_path( + network_code, custom_targeting_key + ) + assert expected == actual + + +def test_parse_custom_targeting_key_path(): + expected = { + "network_code": "cuttlefish", + "custom_targeting_key": "mussel", + } + path = NativeStyleServiceClient.custom_targeting_key_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_custom_targeting_key_path(path) + assert expected == actual + + +def test_custom_targeting_value_path(): + network_code = "winkle" + custom_targeting_value = "nautilus" + expected = ( + "networks/{network_code}/customTargetingValues/{custom_targeting_value}".format( + network_code=network_code, + custom_targeting_value=custom_targeting_value, + ) + ) + actual = NativeStyleServiceClient.custom_targeting_value_path( + network_code, custom_targeting_value + ) + assert expected == actual + + +def test_parse_custom_targeting_value_path(): + expected = { + "network_code": "scallop", + "custom_targeting_value": "abalone", + } + path = NativeStyleServiceClient.custom_targeting_value_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_custom_targeting_value_path(path) + assert expected == actual + + +def test_device_capability_path(): + network_code = "squid" + device_capability = "clam" + expected = "networks/{network_code}/deviceCapabilities/{device_capability}".format( + network_code=network_code, + device_capability=device_capability, + ) + actual = NativeStyleServiceClient.device_capability_path( + network_code, device_capability + ) + assert expected == actual + + +def test_parse_device_capability_path(): + expected = { + "network_code": "whelk", + "device_capability": "octopus", + } + path = NativeStyleServiceClient.device_capability_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_device_capability_path(path) + assert expected == actual + + +def test_device_category_path(): + network_code = "oyster" + device_category = "nudibranch" + expected = "networks/{network_code}/deviceCategories/{device_category}".format( + network_code=network_code, + device_category=device_category, + ) + actual = NativeStyleServiceClient.device_category_path( + network_code, device_category + ) + assert expected == actual + + +def test_parse_device_category_path(): + expected = { + "network_code": "cuttlefish", + "device_category": "mussel", + } + path = NativeStyleServiceClient.device_category_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_device_category_path(path) + assert expected == actual + + +def test_device_manufacturer_path(): + network_code = "winkle" + device_manufacturer = "nautilus" + expected = ( + "networks/{network_code}/deviceManufacturers/{device_manufacturer}".format( + network_code=network_code, + device_manufacturer=device_manufacturer, + ) + ) + actual = NativeStyleServiceClient.device_manufacturer_path( + network_code, device_manufacturer + ) + assert expected == actual + + +def test_parse_device_manufacturer_path(): + expected = { + "network_code": "scallop", + "device_manufacturer": "abalone", + } + path = NativeStyleServiceClient.device_manufacturer_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_device_manufacturer_path(path) + assert expected == actual + + +def test_geo_target_path(): + network_code = "squid" + geo_target = "clam" + expected = "networks/{network_code}/geoTargets/{geo_target}".format( + network_code=network_code, + geo_target=geo_target, + ) + actual = NativeStyleServiceClient.geo_target_path(network_code, geo_target) + assert expected == actual + + +def test_parse_geo_target_path(): + expected = { + "network_code": "whelk", + "geo_target": "octopus", + } + path = NativeStyleServiceClient.geo_target_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_geo_target_path(path) + assert expected == actual + + +def test_mobile_carrier_path(): + network_code = "oyster" + mobile_carrier = "nudibranch" + expected = "networks/{network_code}/mobileCarriers/{mobile_carrier}".format( + network_code=network_code, + mobile_carrier=mobile_carrier, + ) + actual = NativeStyleServiceClient.mobile_carrier_path(network_code, mobile_carrier) + assert expected == actual + + +def test_parse_mobile_carrier_path(): + expected = { + "network_code": "cuttlefish", + "mobile_carrier": "mussel", + } + path = NativeStyleServiceClient.mobile_carrier_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_mobile_carrier_path(path) + assert expected == actual + + +def test_mobile_device_path(): + network_code = "winkle" + mobile_device = "nautilus" + expected = "networks/{network_code}/mobileDevices/{mobile_device}".format( + network_code=network_code, + mobile_device=mobile_device, + ) + actual = NativeStyleServiceClient.mobile_device_path(network_code, mobile_device) + assert expected == actual + + +def test_parse_mobile_device_path(): + expected = { + "network_code": "scallop", + "mobile_device": "abalone", + } + path = NativeStyleServiceClient.mobile_device_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_mobile_device_path(path) + assert expected == actual + + +def test_mobile_device_submodel_path(): + network_code = "squid" + mobile_device_submodel = "clam" + expected = ( + "networks/{network_code}/mobileDeviceSubmodels/{mobile_device_submodel}".format( + network_code=network_code, + mobile_device_submodel=mobile_device_submodel, + ) + ) + actual = NativeStyleServiceClient.mobile_device_submodel_path( + network_code, mobile_device_submodel + ) + assert expected == actual + + +def test_parse_mobile_device_submodel_path(): + expected = { + "network_code": "whelk", + "mobile_device_submodel": "octopus", + } + path = NativeStyleServiceClient.mobile_device_submodel_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_mobile_device_submodel_path(path) + assert expected == actual + + +def test_native_style_path(): + network_code = "oyster" + native_style = "nudibranch" + expected = "networks/{network_code}/nativeStyles/{native_style}".format( + network_code=network_code, + native_style=native_style, + ) + actual = NativeStyleServiceClient.native_style_path(network_code, native_style) + assert expected == actual + + +def test_parse_native_style_path(): + expected = { + "network_code": "cuttlefish", + "native_style": "mussel", + } + path = NativeStyleServiceClient.native_style_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_native_style_path(path) + assert expected == actual + + +def test_network_path(): + network_code = "winkle" + expected = "networks/{network_code}".format( + network_code=network_code, + ) + actual = NativeStyleServiceClient.network_path(network_code) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "network_code": "nautilus", + } + path = NativeStyleServiceClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_network_path(path) + assert expected == actual + + +def test_operating_system_path(): + network_code = "scallop" + operating_system = "abalone" + expected = "networks/{network_code}/operatingSystems/{operating_system}".format( + network_code=network_code, + operating_system=operating_system, + ) + actual = NativeStyleServiceClient.operating_system_path( + network_code, operating_system + ) + assert expected == actual + + +def test_parse_operating_system_path(): + expected = { + "network_code": "squid", + "operating_system": "clam", + } + path = NativeStyleServiceClient.operating_system_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_operating_system_path(path) + assert expected == actual + + +def test_operating_system_version_path(): + network_code = "whelk" + operating_system_version = "octopus" + expected = "networks/{network_code}/operatingSystemVersions/{operating_system_version}".format( + network_code=network_code, + operating_system_version=operating_system_version, + ) + actual = NativeStyleServiceClient.operating_system_version_path( + network_code, operating_system_version + ) + assert expected == actual + + +def test_parse_operating_system_version_path(): + expected = { + "network_code": "oyster", + "operating_system_version": "nudibranch", + } + path = NativeStyleServiceClient.operating_system_version_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_operating_system_version_path(path) + assert expected == actual + + +def test_placement_path(): + network_code = "cuttlefish" + placement = "mussel" + expected = "networks/{network_code}/placements/{placement}".format( + network_code=network_code, + placement=placement, + ) + actual = NativeStyleServiceClient.placement_path(network_code, placement) + assert expected == actual + + +def test_parse_placement_path(): + expected = { + "network_code": "winkle", + "placement": "nautilus", + } + path = NativeStyleServiceClient.placement_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_placement_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = NativeStyleServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = NativeStyleServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = NativeStyleServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = NativeStyleServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = NativeStyleServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = NativeStyleServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = NativeStyleServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = NativeStyleServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = NativeStyleServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = NativeStyleServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NativeStyleServiceClient.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.NativeStyleServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = NativeStyleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.NativeStyleServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = NativeStyleServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = NativeStyleServiceClient( + 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", + ] + for transport in transports: + client = NativeStyleServiceClient( + 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", + [ + (NativeStyleServiceClient, transports.NativeStyleServiceRestTransport), + ], +) +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-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py index 29b0539b90ba..f9a7999fd5c7 100644 --- a/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py +++ b/packages/google-ads-admanager/tests/unit/gapic/admanager_v1/test_network_service.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore from google.api_core import ( client_options, gapic_v1, @@ -58,7 +59,11 @@ pagers, transports, ) -from google.ads.admanager_v1.types import network_messages, network_service +from google.ads.admanager_v1.types import ( + network_messages, + network_service, + third_party_data_declaration, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1451,213 +1456,995 @@ def test_list_networks_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_update_network_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 = NetworkServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkServiceClient( - client_options=options, - transport=transport, - ) + # Ensure method has been cached + assert client._transport.update_network in client._transport._wrapped_methods - # 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 = NetworkServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Replace cached wrapped function with mock + mock_rpc = 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_network] = mock_rpc - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + request = {} + client.update_network(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.update_network(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_network_rest_required_fields( + request_type=network_service.UpdateNetworkRequest, +): + transport_class = transports.NetworkServiceRestTransport + + 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) ) - client = NetworkServiceClient(transport=transport) - assert client.transport is transport + # verify fields with default values are dropped -@pytest.mark.parametrize( - "transport_class", - [ - transports.NetworkServiceRestTransport, - ], -) -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() + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_network._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_transport_kind_rest(): - transport = NetworkServiceClient.get_transport_class("rest")( + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + ).update_network._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 -def test_get_network_rest_bad_request(request_type=network_service.GetNetworkRequest): client = NetworkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1"} 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_network(request) + # Designate an appropriate value for the returned response. + return_value = network_messages.Network() + # 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 -@pytest.mark.parametrize( - "request_type", - [ - network_service.GetNetworkRequest, - dict, - ], -) -def test_get_network_rest_call_success(request_type): - client = NetworkServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + # Convert return value to protobuf type + return_value = network_messages.Network.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_network(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_network_rest_unset_required_fields(): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # send a request that will satisfy transcoding - request_init = {"name": "networks/sample1"} - request = request_type(**request_init) + unset_fields = transport.update_network._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("network",))) + + +def test_update_network_rest_flattened(): + client = NetworkServiceClient( + 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 = network_messages.Network( - name="name_value", - display_name="display_name_value", - network_code="network_code_value", - property_code="property_code_value", - time_zone="time_zone_value", - currency_code="currency_code_value", - secondary_currency_codes=["secondary_currency_codes_value"], - effective_root_ad_unit="effective_root_ad_unit_value", - test_network=True, - network_id=1078, + return_value = network_messages.Network() + + # get arguments that satisfy an http rule for this method + sample_request = {"network": {"name": "networks/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + network=network_messages.Network(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 = mock.Mock() + response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type return_value = network_messages.Network.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value._content = json_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_network(request) - # Establish that the response is the type that we expect. - assert isinstance(response, network_messages.Network) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.network_code == "network_code_value" - assert response.property_code == "property_code_value" - assert response.time_zone == "time_zone_value" - assert response.currency_code == "currency_code_value" - assert response.secondary_currency_codes == ["secondary_currency_codes_value"] - assert response.effective_root_ad_unit == "effective_root_ad_unit_value" - assert response.test_network is True - assert response.network_id == 1078 + client.update_network(**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/{network.name=networks/*}" % client.transport._host, args[1] + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_network_rest_interceptors(null_interceptor): - transport = transports.NetworkServiceRestTransport( +def test_update_network_rest_flattened_error(transport: str = "rest"): + client = NetworkServiceClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.NetworkServiceRestInterceptor(), + transport=transport, ) - client = NetworkServiceClient(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.NetworkServiceRestInterceptor, "post_get_network" - ) as post, - mock.patch.object( - transports.NetworkServiceRestInterceptor, "post_get_network_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.NetworkServiceRestInterceptor, "pre_get_network" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = network_service.GetNetworkRequest.pb( - network_service.GetNetworkRequest() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_network( + network_service.UpdateNetworkRequest(), + network=network_messages.Network(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - 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 + +def test_provision_test_network_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 = NetworkServiceClient( + 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.provision_test_network + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.provision_test_network] = ( + mock_rpc + ) + + request = {} + client.provision_test_network(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_test_network(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_default_third_party_data_declaration_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 = NetworkServiceClient( + 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_default_third_party_data_declaration + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_default_third_party_data_declaration + ] = mock_rpc + + request = {} + client.get_default_third_party_data_declaration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_default_third_party_data_declaration(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_default_third_party_data_declaration_rest_required_fields( + request_type=network_service.GetDefaultThirdPartyDataDeclarationRequest, +): + transport_class = transports.NetworkServiceRestTransport + + 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_default_third_party_data_declaration._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_default_third_party_data_declaration._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 = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = network_messages.DefaultThirdPartyDataDeclaration() + # 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 = network_messages.DefaultThirdPartyDataDeclaration.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_default_third_party_data_declaration(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_default_third_party_data_declaration_rest_unset_required_fields(): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_default_third_party_data_declaration._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_default_third_party_data_declaration_rest_flattened(): + client = NetworkServiceClient( + 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 = network_messages.DefaultThirdPartyDataDeclaration() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "networks/sample1/defaultThirdPartyDataDeclaration"} + + # 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 = network_messages.DefaultThirdPartyDataDeclaration.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_default_third_party_data_declaration(**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=networks/*/defaultThirdPartyDataDeclaration}" + % client.transport._host, + args[1], + ) + + +def test_get_default_third_party_data_declaration_rest_flattened_error( + transport: str = "rest", +): + client = NetworkServiceClient( + 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_default_third_party_data_declaration( + network_service.GetDefaultThirdPartyDataDeclarationRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkServiceClient( + 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 = NetworkServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkServiceClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkServiceRestTransport, + ], +) +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_rest(): + transport = NetworkServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_network_rest_bad_request(request_type=network_service.GetNetworkRequest): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1"} + 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_network(request) + + +@pytest.mark.parametrize( + "request_type", + [ + network_service.GetNetworkRequest, + dict, + ], +) +def test_get_network_rest_call_success(request_type): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1"} + 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 = network_messages.Network( + name="name_value", + display_name="display_name_value", + network_code="network_code_value", + property_code="property_code_value", + time_zone="time_zone_value", + currency_code="currency_code_value", + secondary_currency_codes=["secondary_currency_codes_value"], + effective_root_ad_unit="effective_root_ad_unit_value", + test_network=True, + network_id=1078, + ) + + # 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 = network_messages.Network.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_network(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, network_messages.Network) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.network_code == "network_code_value" + assert response.property_code == "property_code_value" + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.secondary_currency_codes == ["secondary_currency_codes_value"] + assert response.effective_root_ad_unit == "effective_root_ad_unit_value" + assert response.test_network is True + assert response.network_id == 1078 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_network_rest_interceptors(null_interceptor): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServiceRestInterceptor(), + ) + client = NetworkServiceClient(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.NetworkServiceRestInterceptor, "post_get_network" + ) as post, + mock.patch.object( + transports.NetworkServiceRestInterceptor, "post_get_network_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServiceRestInterceptor, "pre_get_network" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = network_service.GetNetworkRequest.pb( + network_service.GetNetworkRequest() + ) + 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 = network_messages.Network.to_json(network_messages.Network()) + req.return_value.content = return_value + + request = network_service.GetNetworkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network_messages.Network() + post_with_metadata.return_value = network_messages.Network(), metadata + + client.get_network( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_networks_rest_bad_request( + request_type=network_service.ListNetworksRequest, +): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + 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_networks(request) + + +@pytest.mark.parametrize( + "request_type", + [ + network_service.ListNetworksRequest, + dict, + ], +) +def test_list_networks_rest_call_success(request_type): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + 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 = network_service.ListNetworksResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # 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 = network_service.ListNetworksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_networks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNetworksPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_networks_rest_interceptors(null_interceptor): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServiceRestInterceptor(), + ) + client = NetworkServiceClient(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.NetworkServiceRestInterceptor, "post_list_networks" + ) as post, + mock.patch.object( + transports.NetworkServiceRestInterceptor, "post_list_networks_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServiceRestInterceptor, "pre_list_networks" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = network_service.ListNetworksRequest.pb( + network_service.ListNetworksRequest() + ) + 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 = network_service.ListNetworksResponse.to_json( + network_service.ListNetworksResponse() + ) + req.return_value.content = return_value + + request = network_service.ListNetworksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network_service.ListNetworksResponse() + post_with_metadata.return_value = ( + network_service.ListNetworksResponse(), + metadata, + ) + + client.list_networks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_network_rest_bad_request( + request_type=network_service.UpdateNetworkRequest, +): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"network": {"name": "networks/sample1"}} + 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_network(request) + + +@pytest.mark.parametrize( + "request_type", + [ + network_service.UpdateNetworkRequest, + dict, + ], +) +def test_update_network_rest_call_success(request_type): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"network": {"name": "networks/sample1"}} + request_init["network"] = { + "name": "networks/sample1", + "display_name": "display_name_value", + "network_code": "network_code_value", + "property_code": "property_code_value", + "time_zone": "time_zone_value", + "currency_code": "currency_code_value", + "secondary_currency_codes": [ + "secondary_currency_codes_value1", + "secondary_currency_codes_value2", + ], + "effective_root_ad_unit": "effective_root_ad_unit_value", + "test_network": True, + "network_id": 1078, + } + # 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 = network_service.UpdateNetworkRequest.meta.fields["network"] + + 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["network"].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["network"][field])): + del request_init["network"][field][i][subfield] + else: + del request_init["network"][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 = network_messages.Network( + name="name_value", + display_name="display_name_value", + network_code="network_code_value", + property_code="property_code_value", + time_zone="time_zone_value", + currency_code="currency_code_value", + secondary_currency_codes=["secondary_currency_codes_value"], + effective_root_ad_unit="effective_root_ad_unit_value", + test_network=True, + network_id=1078, + ) + + # 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 = network_messages.Network.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_network(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, network_messages.Network) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.network_code == "network_code_value" + assert response.property_code == "property_code_value" + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.secondary_currency_codes == ["secondary_currency_codes_value"] + assert response.effective_root_ad_unit == "effective_root_ad_unit_value" + assert response.test_network is True + assert response.network_id == 1078 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_network_rest_interceptors(null_interceptor): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServiceRestInterceptor(), + ) + client = NetworkServiceClient(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.NetworkServiceRestInterceptor, "post_update_network" + ) as post, + mock.patch.object( + transports.NetworkServiceRestInterceptor, + "post_update_network_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServiceRestInterceptor, "pre_update_network" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = network_service.UpdateNetworkRequest.pb( + network_service.UpdateNetworkRequest() + ) + 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 = network_messages.Network.to_json(network_messages.Network()) req.return_value.content = return_value - request = network_service.GetNetworkRequest() + request = network_service.UpdateNetworkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -1666,7 +2453,7 @@ def test_get_network_rest_interceptors(null_interceptor): post.return_value = network_messages.Network() post_with_metadata.return_value = network_messages.Network(), metadata - client.get_network( + client.update_network( request, metadata=[ ("key", "val"), @@ -1679,8 +2466,8 @@ def test_get_network_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_networks_rest_bad_request( - request_type=network_service.ListNetworksRequest, +def test_provision_test_network_rest_bad_request( + request_type=network_service.ProvisionTestNetworkRequest, ): client = NetworkServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -1702,17 +2489,17 @@ def test_list_networks_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_networks(request) + client.provision_test_network(request) @pytest.mark.parametrize( "request_type", [ - network_service.ListNetworksRequest, + network_service.ProvisionTestNetworkRequest, dict, ], ) -def test_list_networks_rest_call_success(request_type): +def test_provision_test_network_rest_call_success(request_type): client = NetworkServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -1724,9 +2511,17 @@ def test_list_networks_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 = network_service.ListNetworksResponse( - next_page_token="next_page_token_value", - total_size=1086, + return_value = network_messages.Network( + name="name_value", + display_name="display_name_value", + network_code="network_code_value", + property_code="property_code_value", + time_zone="time_zone_value", + currency_code="currency_code_value", + secondary_currency_codes=["secondary_currency_codes_value"], + effective_root_ad_unit="effective_root_ad_unit_value", + test_network=True, + network_id=1078, ) # Wrap the value into a proper Response obj @@ -1734,21 +2529,29 @@ def test_list_networks_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = network_service.ListNetworksResponse.pb(return_value) + return_value = network_messages.Network.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_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_networks(request) + response = client.provision_test_network(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNetworksPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, network_messages.Network) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.network_code == "network_code_value" + assert response.property_code == "property_code_value" + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.secondary_currency_codes == ["secondary_currency_codes_value"] + assert response.effective_root_ad_unit == "effective_root_ad_unit_value" + assert response.test_network is True + assert response.network_id == 1078 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_networks_rest_interceptors(null_interceptor): +def test_provision_test_network_rest_interceptors(null_interceptor): transport = transports.NetworkServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1761,20 +2564,21 @@ def test_list_networks_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.NetworkServiceRestInterceptor, "post_list_networks" + transports.NetworkServiceRestInterceptor, "post_provision_test_network" ) as post, mock.patch.object( - transports.NetworkServiceRestInterceptor, "post_list_networks_with_metadata" + transports.NetworkServiceRestInterceptor, + "post_provision_test_network_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.NetworkServiceRestInterceptor, "pre_list_networks" + transports.NetworkServiceRestInterceptor, "pre_provision_test_network" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = network_service.ListNetworksRequest.pb( - network_service.ListNetworksRequest() + pb_message = network_service.ProvisionTestNetworkRequest.pb( + network_service.ProvisionTestNetworkRequest() ) transcode.return_value = { "method": "post", @@ -1786,24 +2590,159 @@ def test_list_networks_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 = network_service.ListNetworksResponse.to_json( - network_service.ListNetworksResponse() + return_value = network_messages.Network.to_json(network_messages.Network()) + req.return_value.content = return_value + + request = network_service.ProvisionTestNetworkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network_messages.Network() + post_with_metadata.return_value = network_messages.Network(), metadata + + client.provision_test_network( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_default_third_party_data_declaration_rest_bad_request( + request_type=network_service.GetDefaultThirdPartyDataDeclarationRequest, +): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/defaultThirdPartyDataDeclaration"} + 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_default_third_party_data_declaration(request) + + +@pytest.mark.parametrize( + "request_type", + [ + network_service.GetDefaultThirdPartyDataDeclarationRequest, + dict, + ], +) +def test_get_default_third_party_data_declaration_rest_call_success(request_type): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "networks/sample1/defaultThirdPartyDataDeclaration"} + 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 = network_messages.DefaultThirdPartyDataDeclaration( + name="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 = network_messages.DefaultThirdPartyDataDeclaration.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_default_third_party_data_declaration(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, network_messages.DefaultThirdPartyDataDeclaration) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_default_third_party_data_declaration_rest_interceptors(null_interceptor): + transport = transports.NetworkServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.NetworkServiceRestInterceptor(), + ) + client = NetworkServiceClient(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.NetworkServiceRestInterceptor, + "post_get_default_third_party_data_declaration", + ) as post, + mock.patch.object( + transports.NetworkServiceRestInterceptor, + "post_get_default_third_party_data_declaration_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.NetworkServiceRestInterceptor, + "pre_get_default_third_party_data_declaration", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = network_service.GetDefaultThirdPartyDataDeclarationRequest.pb( + network_service.GetDefaultThirdPartyDataDeclarationRequest() + ) + 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 = network_messages.DefaultThirdPartyDataDeclaration.to_json( + network_messages.DefaultThirdPartyDataDeclaration() ) req.return_value.content = return_value - request = network_service.ListNetworksRequest() + request = network_service.GetDefaultThirdPartyDataDeclarationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = network_service.ListNetworksResponse() + post.return_value = network_messages.DefaultThirdPartyDataDeclaration() post_with_metadata.return_value = ( - network_service.ListNetworksResponse(), + network_messages.DefaultThirdPartyDataDeclaration(), metadata, ) - client.list_networks( + client.get_default_third_party_data_declaration( request, metadata=[ ("key", "val"), @@ -1987,6 +2926,67 @@ def test_list_networks_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_network_empty_call_rest(): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_network), "__call__") as call: + client.update_network(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = network_service.UpdateNetworkRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_provision_test_network_empty_call_rest(): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.provision_test_network), "__call__" + ) as call: + client.provision_test_network(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = network_service.ProvisionTestNetworkRequest() + assert args[0] == request_msg + + +# This 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_default_third_party_data_declaration_empty_call_rest(): + client = NetworkServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_default_third_party_data_declaration), "__call__" + ) as call: + client.get_default_third_party_data_declaration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = network_service.GetDefaultThirdPartyDataDeclarationRequest() + assert args[0] == request_msg + + def test_network_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -2011,6 +3011,9 @@ def test_network_service_base_transport(): methods = ( "get_network", "list_networks", + "update_network", + "provision_test_network", + "get_default_third_party_data_declaration", "get_operation", "cancel_operation", ) @@ -2162,6 +3165,15 @@ def test_network_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_networks._session session2 = client2.transport.list_networks._session assert session1 != session2 + session1 = client1.transport.update_network._session + session2 = client2.transport.update_network._session + assert session1 != session2 + session1 = client1.transport.provision_test_network._session + session2 = client2.transport.provision_test_network._session + assert session1 != session2 + session1 = client1.transport.get_default_third_party_data_declaration._session + session2 = client2.transport.get_default_third_party_data_declaration._session + assert session1 != session2 def test_ad_unit_path(): @@ -2187,8 +3199,30 @@ def test_parse_ad_unit_path(): assert expected == actual -def test_network_path(): +def test_default_third_party_data_declaration_path(): network_code = "oyster" + expected = "networks/{network_code}/defaultThirdPartyDataDeclaration".format( + network_code=network_code, + ) + actual = NetworkServiceClient.default_third_party_data_declaration_path( + network_code + ) + assert expected == actual + + +def test_parse_default_third_party_data_declaration_path(): + expected = { + "network_code": "nudibranch", + } + path = NetworkServiceClient.default_third_party_data_declaration_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServiceClient.parse_default_third_party_data_declaration_path(path) + assert expected == actual + + +def test_network_path(): + network_code = "cuttlefish" expected = "networks/{network_code}".format( network_code=network_code, ) @@ -2198,7 +3232,7 @@ def test_network_path(): def test_parse_network_path(): expected = { - "network_code": "nudibranch", + "network_code": "mussel", } path = NetworkServiceClient.network_path(**expected) @@ -2207,8 +3241,35 @@ def test_parse_network_path(): assert expected == actual +def test_third_party_company_path(): + network_code = "winkle" + third_party_company = "nautilus" + expected = ( + "networks/{network_code}/thirdPartyCompanies/{third_party_company}".format( + network_code=network_code, + third_party_company=third_party_company, + ) + ) + actual = NetworkServiceClient.third_party_company_path( + network_code, third_party_company + ) + assert expected == actual + + +def test_parse_third_party_company_path(): + expected = { + "network_code": "scallop", + "third_party_company": "abalone", + } + path = NetworkServiceClient.third_party_company_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkServiceClient.parse_third_party_company_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2218,7 +3279,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "clam", } path = NetworkServiceClient.common_billing_account_path(**expected) @@ -2228,7 +3289,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -2238,7 +3299,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "octopus", } path = NetworkServiceClient.common_folder_path(**expected) @@ -2248,7 +3309,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -2258,7 +3319,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nudibranch", } path = NetworkServiceClient.common_organization_path(**expected) @@ -2268,7 +3329,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -2278,7 +3339,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "mussel", } path = NetworkServiceClient.common_project_path(**expected) @@ -2288,8 +3349,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -2300,8 +3361,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "scallop", + "location": "abalone", } path = NetworkServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/__init__.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/__init__.py index 17258d0cb6b4..b915825555c0 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/__init__.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation/__init__.py @@ -66,6 +66,7 @@ UpdateAssignmentRequest, UpdateBiReservationRequest, UpdateCapacityCommitmentRequest, + UpdateReservationGroupRequest, UpdateReservationRequest, ) @@ -111,6 +112,7 @@ "UpdateAssignmentRequest", "UpdateBiReservationRequest", "UpdateCapacityCommitmentRequest", + "UpdateReservationGroupRequest", "UpdateReservationRequest", "Edition", "FailoverMode", diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/__init__.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/__init__.py index b70de8972b26..a83469e4d25c 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/__init__.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/__init__.py @@ -81,6 +81,7 @@ UpdateAssignmentRequest, UpdateBiReservationRequest, UpdateCapacityCommitmentRequest, + UpdateReservationGroupRequest, UpdateReservationRequest, ) @@ -211,5 +212,6 @@ def _get_version(dependency_name): "UpdateAssignmentRequest", "UpdateBiReservationRequest", "UpdateCapacityCommitmentRequest", + "UpdateReservationGroupRequest", "UpdateReservationRequest", ) diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_metadata.json b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_metadata.json index 7216bd76bb22..910bdf28472f 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_metadata.json +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/gapic_metadata.json @@ -154,6 +154,11 @@ "methods": [ "update_reservation" ] + }, + "UpdateReservationGroup": { + "methods": [ + "update_reservation_group" + ] } } }, @@ -304,6 +309,11 @@ "methods": [ "update_reservation" ] + }, + "UpdateReservationGroup": { + "methods": [ + "update_reservation_group" + ] } } }, @@ -454,6 +464,11 @@ "methods": [ "update_reservation" ] + }, + "UpdateReservationGroup": { + "methods": [ + "update_reservation_group" + ] } } } diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/async_client.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/async_client.py index 92827af6fc24..2e4350237bb5 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/async_client.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/async_client.py @@ -4036,6 +4036,130 @@ async def sample_list_reservation_groups(): # Done; return the response. return response + async def update_reservation_group( + self, + request: Optional[ + Union[reservation.UpdateReservationGroupRequest, dict] + ] = None, + *, + reservation_group: Optional[reservation.ReservationGroup] = 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]]] = (), + ) -> reservation.ReservationGroup: + r"""Updates an existing reservation group 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 bigquery_reservation_v1 + + async def sample_update_reservation_group(): + # Create a client + client = bigquery_reservation_v1.ReservationServiceAsyncClient() + + # Initialize request argument(s) + request = bigquery_reservation_v1.UpdateReservationGroupRequest( + ) + + # Make the request + response = await client.update_reservation_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.bigquery_reservation_v1.types.UpdateReservationGroupRequest, dict]]): + The request object. The request for + [ReservationService.UpdateReservationGroup][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup]. + reservation_group (:class:`google.cloud.bigquery_reservation_v1.types.ReservationGroup`): + Required. Content of the reservation + group to update. + + This corresponds to the ``reservation_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Standard field mask for the + set of fields to be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigquery_reservation_v1.types.ReservationGroup: + A reservation group is a container + for reservations. + + """ + # 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 = [reservation_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, reservation.UpdateReservationGroupRequest): + request = reservation.UpdateReservationGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if reservation_group is not None: + request.reservation_group = reservation_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_reservation_group + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("reservation_group.name", request.reservation_group.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "ReservationServiceAsyncClient": return self diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py index c727d3a2cca1..e7e0faa1c240 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py @@ -4475,6 +4475,127 @@ def sample_list_reservation_groups(): # Done; return the response. return response + def update_reservation_group( + self, + request: Optional[ + Union[reservation.UpdateReservationGroupRequest, dict] + ] = None, + *, + reservation_group: Optional[reservation.ReservationGroup] = 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]]] = (), + ) -> reservation.ReservationGroup: + r"""Updates an existing reservation group 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 bigquery_reservation_v1 + + def sample_update_reservation_group(): + # Create a client + client = bigquery_reservation_v1.ReservationServiceClient() + + # Initialize request argument(s) + request = bigquery_reservation_v1.UpdateReservationGroupRequest( + ) + + # Make the request + response = client.update_reservation_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.bigquery_reservation_v1.types.UpdateReservationGroupRequest, dict]): + The request object. The request for + [ReservationService.UpdateReservationGroup][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup]. + reservation_group (google.cloud.bigquery_reservation_v1.types.ReservationGroup): + Required. Content of the reservation + group to update. + + This corresponds to the ``reservation_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Standard field mask for the + set of fields to be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.bigquery_reservation_v1.types.ReservationGroup: + A reservation group is a container + for reservations. + + """ + # 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 = [reservation_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, reservation.UpdateReservationGroupRequest): + request = reservation.UpdateReservationGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if reservation_group is not None: + request.reservation_group = reservation_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_reservation_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("reservation_group.name", request.reservation_group.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ReservationServiceClient": return self diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/base.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/base.py index 55eac772fc48..555cc3440743 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/base.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/base.py @@ -392,6 +392,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_reservation_group: gapic_v1.method.wrap_method( + self.update_reservation_group, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -696,6 +701,15 @@ def list_reservation_groups( ]: raise NotImplementedError() + @property + def update_reservation_group( + self, + ) -> Callable[ + [reservation.UpdateReservationGroupRequest], + Union[reservation.ReservationGroup, Awaitable[reservation.ReservationGroup]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc.py index fd14071e4552..a5ef884a4145 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc.py @@ -1349,6 +1349,34 @@ def list_reservation_groups( ) return self._stubs["list_reservation_groups"] + @property + def update_reservation_group( + self, + ) -> Callable[ + [reservation.UpdateReservationGroupRequest], reservation.ReservationGroup + ]: + r"""Return a callable for the update reservation group method over gRPC. + + Updates an existing reservation group resource. + + Returns: + Callable[[~.UpdateReservationGroupRequest], + ~.ReservationGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reservation_group" not in self._stubs: + self._stubs["update_reservation_group"] = self._logged_channel.unary_unary( + "/google.cloud.bigquery.reservation.v1.ReservationService/UpdateReservationGroup", + request_serializer=reservation.UpdateReservationGroupRequest.serialize, + response_deserializer=reservation.ReservationGroup.deserialize, + ) + return self._stubs["update_reservation_group"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc_asyncio.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc_asyncio.py index 717dff00fbbe..6dda89f2cf7a 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/grpc_asyncio.py @@ -1386,6 +1386,35 @@ def list_reservation_groups( ) return self._stubs["list_reservation_groups"] + @property + def update_reservation_group( + self, + ) -> Callable[ + [reservation.UpdateReservationGroupRequest], + Awaitable[reservation.ReservationGroup], + ]: + r"""Return a callable for the update reservation group method over gRPC. + + Updates an existing reservation group resource. + + Returns: + Callable[[~.UpdateReservationGroupRequest], + Awaitable[~.ReservationGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_reservation_group" not in self._stubs: + self._stubs["update_reservation_group"] = self._logged_channel.unary_unary( + "/google.cloud.bigquery.reservation.v1.ReservationService/UpdateReservationGroup", + request_serializer=reservation.UpdateReservationGroupRequest.serialize, + response_deserializer=reservation.ReservationGroup.deserialize, + ) + return self._stubs["update_reservation_group"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1634,6 +1663,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update_reservation_group: self._wrap_method( + self.update_reservation_group, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py index 8f84746d12ac..15c850ceb461 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py @@ -291,6 +291,14 @@ def post_update_reservation(self, response): logging.log(f"Received response: {response}") return response + def pre_update_reservation_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_reservation_group(self, response): + logging.log(f"Received response: {response}") + return response + transport = ReservationServiceRestTransport(interceptor=MyCustomReservationServiceInterceptor()) client = ReservationServiceClient(transport=transport) @@ -1583,6 +1591,55 @@ def post_update_reservation_with_metadata( """ return response, metadata + def pre_update_reservation_group( + self, + request: reservation.UpdateReservationGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + reservation.UpdateReservationGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_reservation_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_update_reservation_group( + self, response: reservation.ReservationGroup + ) -> reservation.ReservationGroup: + """Post-rpc interceptor for update_reservation_group + + DEPRECATED. Please use the `post_update_reservation_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. This `post_update_reservation_group` interceptor runs + before the `post_update_reservation_group_with_metadata` interceptor. + """ + return response + + def post_update_reservation_group_with_metadata( + self, + response: reservation.ReservationGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[reservation.ReservationGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_reservation_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ReservationService server but before it is returned to user code. + + We recommend only using this `post_update_reservation_group_with_metadata` + interceptor in new development instead of the `post_update_reservation_group` interceptor. + When both interceptors are used, this `post_update_reservation_group_with_metadata` interceptor runs after the + `post_update_reservation_group` interceptor. The (possibly modified) response returned by + `post_update_reservation_group` will be passed to + `post_update_reservation_group_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class ReservationServiceRestStub: @@ -6150,6 +6207,162 @@ def __call__( ) return resp + class _UpdateReservationGroup( + _BaseReservationServiceRestTransport._BaseUpdateReservationGroup, + ReservationServiceRestStub, + ): + def __hash__(self): + return hash("ReservationServiceRestTransport.UpdateReservationGroup") + + @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: reservation.UpdateReservationGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> reservation.ReservationGroup: + r"""Call the update reservation group method over HTTP. + + Args: + request (~.reservation.UpdateReservationGroupRequest): + The request object. The request for + [ReservationService.UpdateReservationGroup][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.reservation.ReservationGroup: + A reservation group is a container + for reservations. + + """ + + http_options = _BaseReservationServiceRestTransport._BaseUpdateReservationGroup._get_http_options() + + request, metadata = self._interceptor.pre_update_reservation_group( + request, metadata + ) + transcoded_request = _BaseReservationServiceRestTransport._BaseUpdateReservationGroup._get_transcoded_request( + http_options, request + ) + + body = _BaseReservationServiceRestTransport._BaseUpdateReservationGroup._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseReservationServiceRestTransport._BaseUpdateReservationGroup._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.bigquery.reservation_v1.ReservationServiceClient.UpdateReservationGroup", + extra={ + "serviceName": "google.cloud.bigquery.reservation.v1.ReservationService", + "rpcName": "UpdateReservationGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ReservationServiceRestTransport._UpdateReservationGroup._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 = reservation.ReservationGroup() + pb_resp = reservation.ReservationGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_reservation_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_reservation_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = reservation.ReservationGroup.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.bigquery.reservation_v1.ReservationServiceClient.update_reservation_group", + extra={ + "serviceName": "google.cloud.bigquery.reservation.v1.ReservationService", + "rpcName": "UpdateReservationGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def create_assignment( self, @@ -6435,6 +6648,18 @@ def update_reservation( # In C++ this would require a dynamic_cast return self._UpdateReservation(self._session, self._host, self._interceptor) # type: ignore + @property + def update_reservation_group( + self, + ) -> Callable[ + [reservation.UpdateReservationGroupRequest], reservation.ReservationGroup + ]: + # 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._UpdateReservationGroup( + self._session, self._host, self._interceptor + ) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest_base.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest_base.py index 2bf95fad2f3a..34c67914a914 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest_base.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest_base.py @@ -1535,5 +1535,62 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseUpdateReservationGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{reservation_group.name=projects/*/locations/*/reservationGroups/*}", + "body": "reservation_group", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = reservation.UpdateReservationGroupRequest.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( + _BaseReservationServiceRestTransport._BaseUpdateReservationGroup._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + __all__ = ("_BaseReservationServiceRestTransport",) diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/__init__.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/__init__.py index 6054dbe41eab..4138299b08db 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/__init__.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/__init__.py @@ -55,6 +55,7 @@ UpdateAssignmentRequest, UpdateBiReservationRequest, UpdateCapacityCommitmentRequest, + UpdateReservationGroupRequest, UpdateReservationRequest, ) @@ -98,6 +99,7 @@ "UpdateAssignmentRequest", "UpdateBiReservationRequest", "UpdateCapacityCommitmentRequest", + "UpdateReservationGroupRequest", "UpdateReservationRequest", "Edition", "FailoverMode", diff --git a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/reservation.py b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/reservation.py index 21df486ccc0d..c899d6b8c4cd 100644 --- a/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/reservation.py +++ b/packages/google-cloud-bigquery-reservation/google/cloud/bigquery_reservation_v1/types/reservation.py @@ -44,6 +44,7 @@ "ListReservationGroupsRequest", "ListReservationGroupsResponse", "DeleteReservationGroupRequest", + "UpdateReservationGroupRequest", "CreateCapacityCommitmentRequest", "ListCapacityCommitmentsRequest", "ListCapacityCommitmentsResponse", @@ -309,6 +310,13 @@ class Reservation(proto.Message): reservation's resources are distributed. This feature is not yet generally available. + reservation_group_path (MutableSequence[str]): + Output only. The reservation group path of the reservation + from root to leaf. The order of elements matters: the first + element is the top level group and the last element is the + direct parent reservation group. For example, if a + reservation is under group-1 -> group-2 -> group-3, then the + reservation group path is ["group-1", "group-2", "group-3"]. """ class ScalingMode(proto.Enum): @@ -538,6 +546,10 @@ class ReplicationStatus(proto.Message): number=27, message="SchedulingPolicy", ) + reservation_group_path: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=28, + ) class SchedulingPolicy(proto.Message): @@ -592,12 +604,42 @@ class ReservationGroup(proto.Message): alphanumeric characters or dashes. It must start with a letter and must not end with a dash. Its maximum length is 64 characters. + parent_group (str): + Optional. The parent reservation group of the reservation + group. Format: + ``projects/*/locations/*/reservationGroups/team1-prod`` for + non-root reservation groups, or ``projects/*/locations/*`` + for root reservation groups. + creation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time of the reservation + group. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update time of the + reservation group via a user operation. This + timestamp is updated only when an update + operation explicitly targets this reservation + group directly. It is not updated when parent or + child groups are created, updated, or deleted. """ name: str = proto.Field( proto.STRING, number=1, ) + parent_group: str = proto.Field( + proto.STRING, + number=2, + ) + creation_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, + ) class CapacityCommitment(proto.Message): @@ -680,6 +722,8 @@ class CommitmentPlan(proto.Enum): rejected with error code ``google.rpc.Code.INVALID_ARGUMENT``. FLEX (3): + Deprecated: Flex commitments are deprecated. + Please use Edition-based capacity commitments. Flex commitments have committed period of 1 minute after becoming ACTIVE. After that, they are not in a committed period anymore and can be @@ -1110,6 +1154,31 @@ class DeleteReservationGroupRequest(proto.Message): ) +class UpdateReservationGroupRequest(proto.Message): + r"""The request for + [ReservationService.UpdateReservationGroup][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup]. + + Attributes: + reservation_group (google.cloud.bigquery_reservation_v1.types.ReservationGroup): + Required. Content of the reservation group to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Standard field mask for the set of + fields to be updated. + """ + + reservation_group: "ReservationGroup" = proto.Field( + proto.MESSAGE, + number=1, + message="ReservationGroup", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + class CreateCapacityCommitmentRequest(proto.Message): r"""The request for [ReservationService.CreateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.CreateCapacityCommitment]. @@ -1403,11 +1472,11 @@ class Assignment(proto.Message): This feature is not yet generally available. principal (str): Optional. Represents the principal for this assignment. If - not empty, jobs run by this principal will utilize the - associated reservation. Otherwise, jobs will fall back to - using the reservation assigned to the project, folder, or - organization (in that order). If no reservation is assigned - at any of these levels, on-demand capacity will be used. + not empty, jobs run by this principal utilize the associated + reservation. Otherwise, jobs fall back to using the + reservation assigned to the project, folder, or + organization, in that order. If no reservation is assigned + at any of these levels, on-demand capacity is used. The supported formats are: @@ -1418,7 +1487,7 @@ class Assignment(proto.Message): for workload identity pool identities. - The special value ``unknown_or_deleted_user`` represents principals which cannot be read from the user info - service, for example deleted users. + service, for example, deleted users. precedence (int): Optional. Specifies the priority precedence for this assignment. Used to resolve ambiguity @@ -1483,6 +1552,11 @@ class JobType(proto.Enum): columns. Reservations with this job type take priority over a default BACKGROUND reservation assignment (if it exists). + AUTOMATIC_MATERIALIZED_VIEW_REFRESH (10): + Automated materialized view refresh jobs will + use the reservation. Reservations with this job + type will take priority over a default QUERY + reservation assignment (if it exists). """ JOB_TYPE_UNSPECIFIED = 0 @@ -1494,6 +1568,7 @@ class JobType(proto.Enum): BACKGROUND_CHANGE_DATA_CAPTURE = 7 BACKGROUND_COLUMN_METADATA_INDEX = 8 BACKGROUND_SEARCH_INDEX_REFRESH = 9 + AUTOMATIC_MATERIALIZED_VIEW_REFRESH = 10 class State(proto.Enum): r"""Assignment will remain in PENDING state if no active capacity diff --git a/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_async.py b/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_async.py new file mode 100644 index 000000000000..74de3286d614 --- /dev/null +++ b/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateReservationGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigquery-reservation + + +# [START bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_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 bigquery_reservation_v1 + + +async def sample_update_reservation_group(): + # Create a client + client = bigquery_reservation_v1.ReservationServiceAsyncClient() + + # Initialize request argument(s) + request = bigquery_reservation_v1.UpdateReservationGroupRequest() + + # Make the request + response = await client.update_reservation_group(request=request) + + # Handle the response + print(response) + + +# [END bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_async] diff --git a/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_sync.py b/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_sync.py new file mode 100644 index 000000000000..8da339ea13fc --- /dev/null +++ b/packages/google-cloud-bigquery-reservation/samples/generated_samples/bigqueryreservation_v1_generated_reservation_service_update_reservation_group_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateReservationGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-bigquery-reservation + + +# [START bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_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 bigquery_reservation_v1 + + +def sample_update_reservation_group(): + # Create a client + client = bigquery_reservation_v1.ReservationServiceClient() + + # Initialize request argument(s) + request = bigquery_reservation_v1.UpdateReservationGroupRequest() + + # Make the request + response = client.update_reservation_group(request=request) + + # Handle the response + print(response) + + +# [END bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_sync] diff --git a/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json b/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json index 945eb8401573..9bc0d4bc9993 100644 --- a/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json +++ b/packages/google-cloud-bigquery-reservation/samples/generated_samples/snippet_metadata_google.cloud.bigquery.reservation.v1.json @@ -4567,6 +4567,175 @@ ], "title": "bigqueryreservation_v1_generated_reservation_service_update_capacity_commitment_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.bigquery_reservation_v1.ReservationServiceAsyncClient", + "shortName": "ReservationServiceAsyncClient" + }, + "fullName": "google.cloud.bigquery_reservation_v1.ReservationServiceAsyncClient.update_reservation_group", + "method": { + "fullName": "google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup", + "service": { + "fullName": "google.cloud.bigquery.reservation.v1.ReservationService", + "shortName": "ReservationService" + }, + "shortName": "UpdateReservationGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigquery_reservation_v1.types.UpdateReservationGroupRequest" + }, + { + "name": "reservation_group", + "type": "google.cloud.bigquery_reservation_v1.types.ReservationGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigquery_reservation_v1.types.ReservationGroup", + "shortName": "update_reservation_group" + }, + "description": "Sample for UpdateReservationGroup", + "file": "bigqueryreservation_v1_generated_reservation_service_update_reservation_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigqueryreservation_v1_generated_reservation_service_update_reservation_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.bigquery_reservation_v1.ReservationServiceClient", + "shortName": "ReservationServiceClient" + }, + "fullName": "google.cloud.bigquery_reservation_v1.ReservationServiceClient.update_reservation_group", + "method": { + "fullName": "google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservationGroup", + "service": { + "fullName": "google.cloud.bigquery.reservation.v1.ReservationService", + "shortName": "ReservationService" + }, + "shortName": "UpdateReservationGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.bigquery_reservation_v1.types.UpdateReservationGroupRequest" + }, + { + "name": "reservation_group", + "type": "google.cloud.bigquery_reservation_v1.types.ReservationGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.bigquery_reservation_v1.types.ReservationGroup", + "shortName": "update_reservation_group" + }, + "description": "Sample for UpdateReservationGroup", + "file": "bigqueryreservation_v1_generated_reservation_service_update_reservation_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "bigqueryreservation_v1_generated_ReservationService_UpdateReservationGroup_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "bigqueryreservation_v1_generated_reservation_service_update_reservation_group_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py b/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py index 2cae2391e2bc..ae8fe40f0641 100644 --- a/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py +++ b/packages/google-cloud-bigquery-reservation/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py @@ -1426,6 +1426,7 @@ def test_create_reservation(request_type, transport: str = "grpc"): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) response = client.create_reservation(request) @@ -1451,6 +1452,7 @@ def test_create_reservation(request_type, transport: str = "grpc"): response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_create_reservation_non_empty_request_with_auto_populated_field(): @@ -1604,6 +1606,7 @@ async def test_create_reservation_async(request_type, transport: str = "grpc_asy max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) response = await client.create_reservation(request) @@ -1630,6 +1633,7 @@ async def test_create_reservation_async(request_type, transport: str = "grpc_asy response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_create_reservation_field_headers(): @@ -2381,6 +2385,7 @@ def test_get_reservation(request_type, transport: str = "grpc"): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) response = client.get_reservation(request) @@ -2404,6 +2409,7 @@ def test_get_reservation(request_type, transport: str = "grpc"): assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_get_reservation_non_empty_request_with_auto_populated_field(): @@ -2547,6 +2553,7 @@ async def test_get_reservation_async(request_type, transport: str = "grpc_asynci max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) response = await client.get_reservation(request) @@ -2571,6 +2578,7 @@ async def test_get_reservation_async(request_type, transport: str = "grpc_asynci assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_get_reservation_field_headers(): @@ -3081,6 +3089,7 @@ def test_update_reservation(request_type, transport: str = "grpc"): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) response = client.update_reservation(request) @@ -3106,6 +3115,7 @@ def test_update_reservation(request_type, transport: str = "grpc"): response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_update_reservation_non_empty_request_with_auto_populated_field(): @@ -3253,6 +3263,7 @@ async def test_update_reservation_async(request_type, transport: str = "grpc_asy max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) response = await client.update_reservation(request) @@ -3279,6 +3290,7 @@ async def test_update_reservation_async(request_type, transport: str = "grpc_asy response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_update_reservation_field_headers(): @@ -3477,6 +3489,7 @@ def test_failover_reservation(request_type, transport: str = "grpc"): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) response = client.failover_reservation(request) @@ -3500,6 +3513,7 @@ def test_failover_reservation(request_type, transport: str = "grpc"): assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_failover_reservation_non_empty_request_with_auto_populated_field(): @@ -3653,6 +3667,7 @@ async def test_failover_reservation_async( max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) response = await client.failover_reservation(request) @@ -3677,6 +3692,7 @@ async def test_failover_reservation_async( assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] def test_failover_reservation_field_headers(): @@ -11265,6 +11281,7 @@ def test_create_reservation_group(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) response = client.create_reservation_group(request) @@ -11277,6 +11294,7 @@ def test_create_reservation_group(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" def test_create_reservation_group_non_empty_request_with_auto_populated_field(): @@ -11422,6 +11440,7 @@ async def test_create_reservation_group_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) ) response = await client.create_reservation_group(request) @@ -11435,6 +11454,7 @@ async def test_create_reservation_group_async( # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" def test_create_reservation_group_field_headers(): @@ -11526,6 +11546,7 @@ def test_get_reservation_group(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) response = client.get_reservation_group(request) @@ -11538,6 +11559,7 @@ def test_get_reservation_group(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" def test_get_reservation_group_non_empty_request_with_auto_populated_field(): @@ -11681,6 +11703,7 @@ async def test_get_reservation_group_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) ) response = await client.get_reservation_group(request) @@ -11694,6 +11717,7 @@ async def test_get_reservation_group_async( # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" def test_get_reservation_group_field_headers(): @@ -12730,6 +12754,361 @@ async def test_list_reservation_groups_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + reservation.UpdateReservationGroupRequest(), + {}, + ], +) +def test_update_reservation_group(request_type, transport: str = "grpc"): + client = ReservationServiceClient( + 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_reservation_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reservation.ReservationGroup( + name="name_value", + parent_group="parent_group_value", + ) + response = client.update_reservation_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = reservation.UpdateReservationGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.ReservationGroup) + assert response.name == "name_value" + assert response.parent_group == "parent_group_value" + + +def test_update_reservation_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 = ReservationServiceClient( + 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 = reservation.UpdateReservationGroupRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_reservation_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reservation.UpdateReservationGroupRequest() + assert args[0] == request_msg + + +def test_update_reservation_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 = ReservationServiceClient( + 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_reservation_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_reservation_group + ] = mock_rpc + request = {} + client.update_reservation_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_reservation_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_reservation_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 = ReservationServiceAsyncClient( + 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_reservation_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_reservation_group + ] = mock_rpc + + request = {} + await client.update_reservation_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_reservation_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", + [ + reservation.UpdateReservationGroupRequest(), + {}, + ], +) +async def test_update_reservation_group_async( + request_type, transport: str = "grpc_asyncio" +): + client = ReservationServiceAsyncClient( + 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_reservation_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reservation.ReservationGroup( + name="name_value", + parent_group="parent_group_value", + ) + ) + response = await client.update_reservation_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = reservation.UpdateReservationGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.ReservationGroup) + assert response.name == "name_value" + assert response.parent_group == "parent_group_value" + + +def test_update_reservation_group_field_headers(): + client = ReservationServiceClient( + 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 = reservation.UpdateReservationGroupRequest() + + request.reservation_group.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + call.return_value = reservation.ReservationGroup() + client.update_reservation_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", + "reservation_group.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_reservation_group_field_headers_async(): + client = ReservationServiceAsyncClient( + 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 = reservation.UpdateReservationGroupRequest() + + request.reservation_group.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reservation.ReservationGroup() + ) + await client.update_reservation_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", + "reservation_group.name=name_value", + ) in kw["metadata"] + + +def test_update_reservation_group_flattened(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reservation.ReservationGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_reservation_group( + reservation_group=reservation.ReservationGroup(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].reservation_group + mock_val = reservation.ReservationGroup(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_reservation_group_flattened_error(): + client = ReservationServiceClient( + 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_reservation_group( + reservation.UpdateReservationGroupRequest(), + reservation_group=reservation.ReservationGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_reservation_group_flattened_async(): + client = ReservationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = reservation.ReservationGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reservation.ReservationGroup() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_reservation_group( + reservation_group=reservation.ReservationGroup(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].reservation_group + mock_val = reservation.ReservationGroup(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_reservation_group_flattened_error_async(): + client = ReservationServiceAsyncClient( + 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_reservation_group( + reservation.UpdateReservationGroupRequest(), + reservation_group=reservation.ReservationGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + def test_create_reservation_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -18009,6 +18388,193 @@ def test_list_reservation_groups_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token +def test_update_reservation_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 = ReservationServiceClient( + 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_reservation_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_reservation_group + ] = mock_rpc + + request = {} + client.update_reservation_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_reservation_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_reservation_group_rest_required_fields( + request_type=reservation.UpdateReservationGroupRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_reservation_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_reservation_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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.ReservationGroup() + # 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 = reservation.ReservationGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_reservation_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_reservation_group_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_reservation_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("reservationGroup",))) + + +def test_update_reservation_group_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.ReservationGroup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "reservation_group": { + "name": "projects/sample1/locations/sample2/reservationGroups/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + reservation_group=reservation.ReservationGroup(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 = reservation.ReservationGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_reservation_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/{reservation_group.name=projects/*/locations/*/reservationGroups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_reservation_group_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_reservation_group( + reservation.UpdateReservationGroupRequest(), + reservation_group=reservation.ReservationGroup(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.ReservationServiceGrpcTransport( @@ -18717,13 +19283,35 @@ def test_delete_reservation_group_empty_call_grpc(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reservation.DeleteReservationGroupRequest() + request_msg = reservation.DeleteReservationGroupRequest() + assert args[0] == request_msg + + +# This 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_reservation_groups_empty_call_grpc(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_reservation_groups), "__call__" + ) as call: + call.return_value = reservation.ListReservationGroupsResponse() + client.list_reservation_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reservation.ListReservationGroupsRequest() assert args[0] == request_msg # This 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_reservation_groups_empty_call_grpc(): +def test_update_reservation_group_empty_call_grpc(): client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", @@ -18731,15 +19319,15 @@ def test_list_reservation_groups_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_reservation_groups), "__call__" + type(client.transport.update_reservation_group), "__call__" ) as call: - call.return_value = reservation.ListReservationGroupsResponse() - client.list_reservation_groups(request=None) + call.return_value = reservation.ReservationGroup() + client.update_reservation_group(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = reservation.ListReservationGroupsRequest() + request_msg = reservation.UpdateReservationGroupRequest() assert args[0] == request_msg @@ -18785,6 +19373,7 @@ async def test_create_reservation_empty_call_grpc_asyncio(): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) await client.create_reservation(request=None) @@ -18850,6 +19439,7 @@ async def test_get_reservation_empty_call_grpc_asyncio(): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) await client.get_reservation(request=None) @@ -18913,6 +19503,7 @@ async def test_update_reservation_empty_call_grpc_asyncio(): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) await client.update_reservation(request=None) @@ -18952,6 +19543,7 @@ async def test_failover_reservation_empty_call_grpc_asyncio(): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) ) await client.failover_reservation(request=None) @@ -19544,6 +20136,7 @@ async def test_create_reservation_group_empty_call_grpc_asyncio(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) ) await client.create_reservation_group(request=None) @@ -19572,6 +20165,7 @@ async def test_get_reservation_group_empty_call_grpc_asyncio(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) ) await client.get_reservation_group(request=None) @@ -19635,6 +20229,35 @@ async def test_list_reservation_groups_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_update_reservation_group_empty_call_grpc_asyncio(): + client = ReservationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reservation.ReservationGroup( + name="name_value", + parent_group="parent_group_value", + ) + ) + await client.update_reservation_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reservation.UpdateReservationGroupRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = ReservationServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -19715,6 +20338,10 @@ def test_create_reservation_rest_call_success(request_type): "soft_failover_start_time": {}, }, "scheduling_policy": {"concurrency": 1195, "max_slots": 986}, + "reservation_group_path": [ + "reservation_group_path_value1", + "reservation_group_path_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 @@ -19801,6 +20428,7 @@ def get_message_fields(field): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) # Wrap the value into a proper Response obj @@ -19831,6 +20459,7 @@ def get_message_fields(field): response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -20094,6 +20723,7 @@ def test_get_reservation_rest_call_success(request_type): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) # Wrap the value into a proper Response obj @@ -20122,6 +20752,7 @@ def test_get_reservation_rest_call_success(request_type): assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -20380,6 +21011,10 @@ def test_update_reservation_rest_call_success(request_type): "soft_failover_start_time": {}, }, "scheduling_policy": {"concurrency": 1195, "max_slots": 986}, + "reservation_group_path": [ + "reservation_group_path_value1", + "reservation_group_path_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 @@ -20466,6 +21101,7 @@ def get_message_fields(field): max_slots=986, scaling_mode=gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) # Wrap the value into a proper Response obj @@ -20496,6 +21132,7 @@ def get_message_fields(field): response.scaling_mode == gcbr_reservation.Reservation.ScalingMode.AUTOSCALE_ONLY ) assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -20623,6 +21260,7 @@ def test_failover_reservation_rest_call_success(request_type): max_slots=986, scaling_mode=reservation.Reservation.ScalingMode.AUTOSCALE_ONLY, reservation_group="reservation_group_value", + reservation_group_path=["reservation_group_path_value"], ) # Wrap the value into a proper Response obj @@ -20651,6 +21289,7 @@ def test_failover_reservation_rest_call_success(request_type): assert response.max_slots == 986 assert response.scaling_mode == reservation.Reservation.ScalingMode.AUTOSCALE_ONLY assert response.reservation_group == "reservation_group_value" + assert response.reservation_group_path == ["reservation_group_path_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -23815,7 +24454,12 @@ def test_create_reservation_group_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["reservation_group"] = {"name": "name_value"} + request_init["reservation_group"] = { + "name": "name_value", + "parent_group": "parent_group_value", + "creation_time": {"seconds": 751, "nanos": 543}, + "update_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 @@ -23892,6 +24536,7 @@ def get_message_fields(field): # Designate an appropriate value for the returned response. return_value = reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) # Wrap the value into a proper Response obj @@ -23909,6 +24554,7 @@ def get_message_fields(field): # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -24030,6 +24676,7 @@ def test_get_reservation_group_rest_call_success(request_type): # Designate an appropriate value for the returned response. return_value = reservation.ReservationGroup( name="name_value", + parent_group="parent_group_value", ) # Wrap the value into a proper Response obj @@ -24047,6 +24694,7 @@ def test_get_reservation_group_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, reservation.ReservationGroup) assert response.name == "name_value" + assert response.parent_group == "parent_group_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -24366,6 +25014,225 @@ def test_list_reservation_groups_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_update_reservation_group_rest_bad_request( + request_type=reservation.UpdateReservationGroupRequest, +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "reservation_group": { + "name": "projects/sample1/locations/sample2/reservationGroups/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_reservation_group(request) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.UpdateReservationGroupRequest, + dict, + ], +) +def test_update_reservation_group_rest_call_success(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "reservation_group": { + "name": "projects/sample1/locations/sample2/reservationGroups/sample3" + } + } + request_init["reservation_group"] = { + "name": "projects/sample1/locations/sample2/reservationGroups/sample3", + "parent_group": "parent_group_value", + "creation_time": {"seconds": 751, "nanos": 543}, + "update_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 = reservation.UpdateReservationGroupRequest.meta.fields[ + "reservation_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["reservation_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["reservation_group"][field])): + del request_init["reservation_group"][field][i][subfield] + else: + del request_init["reservation_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 = reservation.ReservationGroup( + name="name_value", + parent_group="parent_group_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 = reservation.ReservationGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_reservation_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.ReservationGroup) + assert response.name == "name_value" + assert response.parent_group == "parent_group_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_reservation_group_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, + "post_update_reservation_group", + ) as post, + mock.patch.object( + transports.ReservationServiceRestInterceptor, + "post_update_reservation_group_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_update_reservation_group" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = reservation.UpdateReservationGroupRequest.pb( + reservation.UpdateReservationGroupRequest() + ) + 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 = reservation.ReservationGroup.to_json( + reservation.ReservationGroup() + ) + req.return_value.content = return_value + + request = reservation.UpdateReservationGroupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.ReservationGroup() + post_with_metadata.return_value = reservation.ReservationGroup(), metadata + + client.update_reservation_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_initialize_client_w_rest(): client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -24972,6 +25839,27 @@ def test_list_reservation_groups_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_reservation_group_empty_call_rest(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_reservation_group), "__call__" + ) as call: + client.update_reservation_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = reservation.UpdateReservationGroupRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ReservationServiceClient( @@ -25034,6 +25922,7 @@ def test_reservation_service_base_transport(): "get_reservation_group", "delete_reservation_group", "list_reservation_groups", + "update_reservation_group", ) for method in methods: with pytest.raises(NotImplementedError): @@ -25400,6 +26289,9 @@ def test_reservation_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_reservation_groups._session session2 = client2.transport.list_reservation_groups._session assert session1 != session2 + session1 = client1.transport.update_reservation_group._session + session2 = client2.transport.update_reservation_group._session + assert session1 != session2 def test_reservation_service_grpc_transport_channel(): diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/managed_rulesets.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/managed_rulesets.rst new file mode 100644 index 000000000000..de74cccfdc59 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/managed_rulesets.rst @@ -0,0 +1,10 @@ +ManagedRulesets +--------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.managed_rulesets + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.managed_rulesets.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst index 5885cb33ce6d..3b0e45abd135 100644 --- a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst @@ -48,6 +48,7 @@ Services for Google Cloud Compute v1beta API licenses machine_images machine_types + managed_rulesets network_attachments network_edge_security_services network_endpoint_groups diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py index 2b521975a737..86592b203c69 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute/__init__.py @@ -125,6 +125,9 @@ MachineImagesClient, ) from google.cloud.compute_v1beta.services.machine_types.client import MachineTypesClient +from google.cloud.compute_v1beta.services.managed_rulesets.client import ( + ManagedRulesetsClient, +) from google.cloud.compute_v1beta.services.network_attachments.client import ( NetworkAttachmentsClient, ) @@ -831,6 +834,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -938,6 +943,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetManagedRulesetRequest, GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, @@ -1485,6 +1491,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListManagedRulesetsRequest, ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, @@ -1609,6 +1616,8 @@ ManagedInstanceScheduling, ManagedInstanceShutdownDetails, ManagedInstanceVersion, + ManagedRuleset, + ManagedRulesetList, Metadata, MetadataFilter, MetadataFilterLabelMatch, @@ -2623,6 +2632,7 @@ "LicensesClient", "MachineImagesClient", "MachineTypesClient", + "ManagedRulesetsClient", "NetworkAttachmentsClient", "NetworkEdgeSecurityServicesClient", "NetworkEndpointGroupsClient", @@ -3194,6 +3204,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureResourcesRecommendation", "FutureResourcesRecommendationOtherLocation", @@ -3301,6 +3313,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetManagedRulesetRequest", "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", @@ -3848,6 +3861,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListManagedRulesetsRequest", "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", @@ -3972,6 +3986,8 @@ "ManagedInstanceScheduling", "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", + "ManagedRuleset", + "ManagedRulesetList", "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py index 3fd7dc62a217..9d52b85c5290 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py @@ -75,6 +75,7 @@ "google.cloud.compute_v1beta.services.licenses", "google.cloud.compute_v1beta.services.machine_images", "google.cloud.compute_v1beta.services.machine_types", + "google.cloud.compute_v1beta.services.managed_rulesets", "google.cloud.compute_v1beta.services.network_attachments", "google.cloud.compute_v1beta.services.network_edge_security_services", "google.cloud.compute_v1beta.services.network_endpoint_groups", @@ -218,6 +219,7 @@ from .services.licenses import LicensesClient from .services.machine_images import MachineImagesClient from .services.machine_types import MachineTypesClient +from .services.managed_rulesets import ManagedRulesetsClient from .services.network_attachments import NetworkAttachmentsClient from .services.network_edge_security_services import NetworkEdgeSecurityServicesClient from .services.network_endpoint_groups import NetworkEndpointGroupsClient @@ -796,6 +798,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -903,6 +907,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetManagedRulesetRequest, GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, @@ -1450,6 +1455,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListManagedRulesetsRequest, ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, @@ -1574,6 +1580,8 @@ ManagedInstanceScheduling, ManagedInstanceShutdownDetails, ManagedInstanceVersion, + ManagedRuleset, + ManagedRulesetList, Metadata, MetadataFilter, MetadataFilterLabelMatch, @@ -3118,6 +3126,8 @@ def _get_version(dependency_name): "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureReservationsAggregatedListResponse", "FutureReservationsClient", @@ -3231,6 +3241,7 @@ def _get_version(dependency_name): "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetManagedRulesetRequest", "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", @@ -3804,6 +3815,7 @@ def _get_version(dependency_name): "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListManagedRulesetsRequest", "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", @@ -3930,6 +3942,9 @@ def _get_version(dependency_name): "ManagedInstanceScheduling", "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", + "ManagedRuleset", + "ManagedRulesetList", + "ManagedRulesetsClient", "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json index 9f180261dfa5..87d4ec908b41 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json @@ -2355,6 +2355,25 @@ } } }, + "ManagedRulesets": { + "clients": { + "rest": { + "libraryClient": "ManagedRulesetsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "NetworkAttachments": { "clients": { "rest": { diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/__init__.py new file mode 100644 index 000000000000..5c6e780a49c4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/__init__.py @@ -0,0 +1,18 @@ +# -*- 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 .client import ManagedRulesetsClient + +__all__ = ("ManagedRulesetsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/client.py new file mode 100644 index 000000000000..1ec5527a0220 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/client.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 +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.compute_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.compute_v1beta.services.managed_rulesets import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ManagedRulesetsTransport +from .transports.rest import ManagedRulesetsRestTransport + + +class ManagedRulesetsClientMeta(type): + """Metaclass for the ManagedRulesets 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[ManagedRulesetsTransport]] + _transport_registry["rest"] = ManagedRulesetsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ManagedRulesetsTransport]: + """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 ManagedRulesetsClient(metaclass=ManagedRulesetsClientMeta): + """The ManagedRulesets API.""" + + @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 = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{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: + ManagedRulesetsClient: 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: + ManagedRulesetsClient: 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) -> ManagedRulesetsTransport: + """Returns the transport used by the client instance. + + Returns: + ManagedRulesetsTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = ManagedRulesetsClient._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 = ManagedRulesetsClient._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 = ManagedRulesetsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ManagedRulesetsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ManagedRulesetsClient._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 = ManagedRulesetsClient._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, ManagedRulesetsTransport, Callable[..., ManagedRulesetsTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the managed rulesets 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,ManagedRulesetsTransport,Callable[..., ManagedRulesetsTransport]]]): + 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 ManagedRulesetsTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + 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 = ( + ManagedRulesetsClient._read_environment_variables() + ) + self._client_cert_source = ManagedRulesetsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ManagedRulesetsClient._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, ManagedRulesetsTransport) + if transport_provided: + # transport is a ManagedRulesetsTransport 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(ManagedRulesetsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or ManagedRulesetsClient._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[ManagedRulesetsTransport], Callable[..., ManagedRulesetsTransport] + ] = ( + ManagedRulesetsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ManagedRulesetsTransport], 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.compute_v1beta.ManagedRulesetsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.ManagedRulesets", + "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.compute.v1beta.ManagedRulesets", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetManagedRulesetRequest, dict]] = None, + *, + project: Optional[str] = None, + managed_ruleset: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ManagedRuleset: + r"""Gets the details for the specified managed ruleset + name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_get(): + # Create a client + client = compute_v1beta.ManagedRulesetsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetManagedRulesetRequest( + managed_ruleset="managed_ruleset_value", + project="project_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetManagedRulesetRequest, dict]): + The request object. A request message for + ManagedRulesets.Get. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + managed_ruleset (str): + Name of the managed ruleset to + return. + + This corresponds to the ``managed_ruleset`` 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.compute_v1beta.types.ManagedRuleset: + Represents a ManagedRuleset resource. + + Managed internally by Cloud Armor CLH + for Managed Rules features. Customers + can only view these resources to modify + their Security Policies. For more + information, see + https://cloud.google.com/armor/docs/. + + """ + # 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 = [project, managed_ruleset] + 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, compute.GetManagedRulesetRequest): + request = compute.GetManagedRulesetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if managed_ruleset is not None: + request.managed_ruleset = managed_ruleset + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("managed_ruleset", request.managed_ruleset), + ) + ), + ) + + # 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( + self, + request: Optional[Union[compute.ListManagedRulesetsRequest, dict]] = None, + *, + project: 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.ListPager: + r"""Retrieves the list of all the managed rulesets + available. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.ManagedRulesetsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListManagedRulesetsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ListManagedRulesetsRequest, dict]): + The request object. A request message for + ManagedRulesets.List. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` 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.compute_v1beta.services.managed_rulesets.pagers.ListPager: + 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 = [project] + 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, compute.ListManagedRulesetsRequest): + request = compute.ListManagedRulesetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # 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.ListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ManagedRulesetsClient": + 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() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ManagedRulesetsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/pagers.py new file mode 100644 index 000000000000..bb6e270be4d3 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/pagers.py @@ -0,0 +1,117 @@ +# -*- 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.compute_v1beta.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1beta.types.ManagedRulesetList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1beta.types.ManagedRulesetList` + 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[..., compute.ManagedRulesetList], + request: compute.ListManagedRulesetsRequest, + response: compute.ManagedRulesetList, + *, + 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.compute_v1beta.types.ListManagedRulesetsRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.ManagedRulesetList): + 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 = compute.ListManagedRulesetsRequest(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[compute.ManagedRulesetList]: + 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[compute.ManagedRuleset]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/README.rst new file mode 100644 index 000000000000..f54dedabc457 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ManagedRulesetsTransport`` is the ABC for all transports. + +- public child ``ManagedRulesetsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ManagedRulesetsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseManagedRulesetsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ManagedRulesetsRestTransport`` 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-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/__init__.py new file mode 100644 index 000000000000..ea7086941754 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- 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 ManagedRulesetsTransport +from .rest import ManagedRulesetsRestInterceptor, ManagedRulesetsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ManagedRulesetsTransport]] +_transport_registry["rest"] = ManagedRulesetsRestTransport + +__all__ = ( + "ManagedRulesetsTransport", + "ManagedRulesetsRestTransport", + "ManagedRulesetsRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/base.py new file mode 100644 index 000000000000..a12597359cdc --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/base.py @@ -0,0 +1,211 @@ +# -*- 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 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ManagedRulesetsTransport(abc.ABC): + """Abstract transport class for ManagedRulesets.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.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: 'compute.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.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + 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 get( + self, + ) -> Callable[ + [compute.GetManagedRulesetRequest], + Union[compute.ManagedRuleset, Awaitable[compute.ManagedRuleset]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListManagedRulesetsRequest], + Union[compute.ManagedRulesetList, Awaitable[compute.ManagedRulesetList]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ManagedRulesetsTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest.py new file mode 100644 index 000000000000..e0a73d77531d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest.py @@ -0,0 +1,612 @@ +# -*- 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, 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.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseManagedRulesetsRestTransport + +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}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ManagedRulesetsRestInterceptor: + """Interceptor for ManagedRulesets. + + 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 ManagedRulesetsRestTransport. + + .. code-block:: python + class MyCustomManagedRulesetsInterceptor(ManagedRulesetsRestInterceptor): + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ManagedRulesetsRestTransport(interceptor=MyCustomManagedRulesetsInterceptor()) + client = ManagedRulesetsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetManagedRulesetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetManagedRulesetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the ManagedRulesets server. + """ + return request, metadata + + def post_get(self, response: compute.ManagedRuleset) -> compute.ManagedRuleset: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ManagedRulesets server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.ManagedRuleset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ManagedRuleset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ManagedRulesets server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListManagedRulesetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListManagedRulesetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the ManagedRulesets server. + """ + return request, metadata + + def post_list( + self, response: compute.ManagedRulesetList + ) -> compute.ManagedRulesetList: + """Post-rpc interceptor for list + + DEPRECATED. Please use the `post_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ManagedRulesets server but before + it is returned to user code. This `post_list` interceptor runs + before the `post_list_with_metadata` interceptor. + """ + return response + + def post_list_with_metadata( + self, + response: compute.ManagedRulesetList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ManagedRulesetList, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ManagedRulesets server but before it is returned to user code. + + We recommend only using this `post_list_with_metadata` + interceptor in new development instead of the `post_list` interceptor. + When both interceptors are used, this `post_list_with_metadata` interceptor runs after the + `post_list` interceptor. The (possibly modified) response returned by + `post_list` will be passed to + `post_list_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ManagedRulesetsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ManagedRulesetsRestInterceptor + + +class ManagedRulesetsRestTransport(_BaseManagedRulesetsRestTransport): + """REST backend synchronous transport for ManagedRulesets. + + The ManagedRulesets API. + + 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 = "compute.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[ManagedRulesetsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.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[ManagedRulesetsRestInterceptor]): 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 + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ManagedRulesetsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseManagedRulesetsRestTransport._BaseGet, ManagedRulesetsRestStub): + def __hash__(self): + return hash("ManagedRulesetsRestTransport.Get") + + @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: compute.GetManagedRulesetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ManagedRuleset: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetManagedRulesetRequest): + The request object. A request message for + ManagedRulesets.Get. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ManagedRuleset: + Represents a ManagedRuleset resource. + + Managed internally by Cloud Armor CLH + for Managed Rules features. Customers + can only view these resources to modify + their Security Policies. For more + information, see + https://cloud.google.com/armor/docs/. + + """ + + http_options = ( + _BaseManagedRulesetsRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseManagedRulesetsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseManagedRulesetsRestTransport._BaseGet._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.compute_v1beta.ManagedRulesetsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ManagedRulesets", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ManagedRulesetsRestTransport._Get._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 = compute.ManagedRuleset() + pb_resp = compute.ManagedRuleset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ManagedRuleset.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.compute_v1beta.ManagedRulesetsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ManagedRulesets", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseManagedRulesetsRestTransport._BaseList, ManagedRulesetsRestStub): + def __hash__(self): + return hash("ManagedRulesetsRestTransport.List") + + @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: compute.ListManagedRulesetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ManagedRulesetList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListManagedRulesetsRequest): + The request object. A request message for + ManagedRulesets.List. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ManagedRulesetList: + + """ + + http_options = ( + _BaseManagedRulesetsRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseManagedRulesetsRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseManagedRulesetsRestTransport._BaseList._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.compute_v1beta.ManagedRulesetsClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.ManagedRulesets", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ManagedRulesetsRestTransport._List._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 = compute.ManagedRulesetList() + pb_resp = compute.ManagedRulesetList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ManagedRulesetList.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.compute_v1beta.ManagedRulesetsClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.ManagedRulesets", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get( + self, + ) -> Callable[[compute.GetManagedRulesetRequest], compute.ManagedRuleset]: + # 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._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[[compute.ListManagedRulesetsRequest], compute.ManagedRulesetList]: + # 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._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ManagedRulesetsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest_base.py new file mode 100644 index 000000000000..fc3dcbc4c990 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/managed_rulesets/transports/rest_base.py @@ -0,0 +1,183 @@ +# -*- 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.protobuf import json_format + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO, ManagedRulesetsTransport + + +class _BaseManagedRulesetsRestTransport(ManagedRulesetsTransport): + """Base REST backend transport for ManagedRulesets. + + 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 = "compute.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: 'compute.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 _BaseGet: + 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": "/compute/beta/projects/{project}/global/managedRulesets/{managed_ruleset}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetManagedRulesetRequest.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=False, + ) + ) + query_params.update( + _BaseManagedRulesetsRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + 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": "/compute/beta/projects/{project}/global/managedRulesets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListManagedRulesetsRequest.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=False, + ) + ) + query_params.update( + _BaseManagedRulesetsRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseManagedRulesetsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py index 6b3008deb15c..0f66420efbf7 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py @@ -495,6 +495,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -602,6 +604,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetManagedRulesetRequest, GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, @@ -1149,6 +1152,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListManagedRulesetsRequest, ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, @@ -1273,6 +1277,8 @@ ManagedInstanceScheduling, ManagedInstanceShutdownDetails, ManagedInstanceVersion, + ManagedRuleset, + ManagedRulesetList, Metadata, MetadataFilter, MetadataFilterLabelMatch, @@ -2723,6 +2729,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureResourcesRecommendation", "FutureResourcesRecommendationOtherLocation", @@ -2830,6 +2838,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetManagedRulesetRequest", "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", @@ -3377,6 +3386,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListManagedRulesetsRequest", "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", @@ -3501,6 +3511,8 @@ "ManagedInstanceScheduling", "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", + "ManagedRuleset", + "ManagedRulesetList", "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py index ae71b9d84285..36490d733528 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py @@ -502,6 +502,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureReservationsAggregatedListResponse", "FutureReservationsListResponse", @@ -614,6 +616,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetManagedRulesetRequest", "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", @@ -1159,6 +1162,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListManagedRulesetsRequest", "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", @@ -1283,6 +1287,8 @@ "ManagedInstanceScheduling", "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", + "ManagedRuleset", + "ManagedRulesetList", "Metadata", "MetadataFilter", "MetadataFilterLabelMatch", @@ -19641,9 +19647,11 @@ class Backend(proto.Message): guidelines, see Connection balancing mode. Backends must use compatible balancing modes. - For more information, see Supported balancing - modes and target capacity settings and - Restrictions and guidance for instance groups. + Backends of a backend service may use different + balancing modes. For more information, see + Supported balancing modes and target capacity + settings and Restrictions and guidance for + instance groups. Note: Currently, if you use the API to configure incompatible balancing modes, the configuration @@ -19686,6 +19694,11 @@ class Backend(proto.Message): failover backend. More than one failover backend can be configured for a given BackendService. + This field can only be used for a regional + external Passthrough Network Load Balancer or a + regional internal Passthrough Network Load + Balancer. + This field is a member of `oneof`_ ``_failover``. group (str): The fully-qualified URL of aninstance group or network @@ -19804,6 +19817,14 @@ class Backend(proto.Message): would be used and traffic would be assigned based on the load balancing algorithm you use. This is the default + + For global external Passthrough Network Load + Balancers, the following restrictions apply: + + - At most one backend can be marked as + PREFERRED. + - PREFERRED and DEFAULT backends cannot + reside in the same Cloud region. Check the Preference enum for the list of possible values. @@ -19830,7 +19851,8 @@ class BalancingMode(proto.Enum): balancer can handle additional traffic or is fully loaded. For usage guidelines, see Connection balancing mode. - Backends must use compatible balancing modes. For more + Backends must use compatible balancing modes. Backends of a + backend service may use different balancing modes. For more information, see Supported balancing modes and target capacity settings and Restrictions and guidance for instance groups. @@ -19878,6 +19900,13 @@ class Preference(proto.Enum): would be assigned based on the load balancing algorithm you use. This is the default + For global external Passthrough Network Load Balancers, the + following restrictions apply: + + - At most one backend can be marked as PREFERRED. + - PREFERRED and DEFAULT backends cannot reside + in the same Cloud region. + Values: UNDEFINED_PREFERENCE (0): A value indicating that the enum field is not @@ -20370,16 +20399,16 @@ class BackendBucketCdnPolicy(proto.Message): This field is a member of `oneof`_ ``_cache_key_policy``. cache_mode (str): Specifies the cache setting for all responses from this - backend. The possible values are:USE_ORIGIN_HEADERS Requires - the origin to set valid caching headers to cache content. - Responses without these headers will not be cached at - Google's edge, and will require a full trip to the origin on - every request, potentially impacting performance and - increasing load on the origin server.FORCE_CACHE_ALL Cache + backend. The possible values are: USE_ORIGIN_HEADERS + Requires the origin to set valid caching headers to cache + content. Responses without these headers will not be cached + at Google's edge, and will require a full trip to the origin + on every request, potentially impacting performance and + increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, - per-user (user identifiable) content.CACHE_ALL_STATIC + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as @@ -20508,19 +20537,19 @@ class BackendBucketCdnPolicy(proto.Message): class CacheMode(proto.Enum): r"""Specifies the cache setting for all responses from this backend. The - possible values are:USE_ORIGIN_HEADERS Requires the origin to set + possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting - performance and increasing load on the origin server.FORCE_CACHE_ALL - Cache all content, ignoring any "private", "no-store" or "no-cache" - directives in Cache-Control response headers. Warning: this may - result in Cloud CDN caching private, per-user (user identifiable) - content.CACHE_ALL_STATIC Automatically cache static content, - including common image formats, media (video and audio), and web - assets (JavaScript and CSS). Requests and responses that are marked - as uncacheable, as well as dynamic content (including HTML), will - not be cached. + performance and increasing load on the origin server. + FORCE_CACHE_ALL Cache all content, ignoring any "private", + "no-store" or "no-cache" directives in Cache-Control response + headers. Warning: this may result in Cloud CDN caching private, + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically + cache static content, including common image formats, media (video + and audio), and web assets (JavaScript and CSS). Requests and + responses that are marked as uncacheable, as well as dynamic content + (including HTML), will not be cached. If no value is provided for cdnPolicy.cacheMode, it defaults to CACHE_ALL_STATIC. @@ -21167,8 +21196,9 @@ class BackendService(proto.Message): Balancers `__ and `external passthrough Network Load Balancers `__. - - failoverPolicy cannot be specified with haPolicy. + failoverPolicy cannot be specified with + haPolicy.failoverPolicy cannot be used by global external + Passthrough Network Load Balancers. This field is a member of `oneof`_ ``_failover_policy``. fingerprint (str): @@ -21214,11 +21244,10 @@ class BackendService(proto.Message): haPolicy requires customers to be responsible for tracking backend endpoint health and electing a leader among the healthy endpoints. Therefore, haPolicy cannot be specified - with healthChecks. - - haPolicy can only be specified for External Passthrough - Network Load Balancers and Internal Passthrough Network Load - Balancers. + with healthChecks. haPolicy can only be specified for + External Passthrough Network Load Balancers and Internal + Passthrough Network Load Balancers.haPolicy cannot be used + by global external Passthrough Network Load Balancers. This field is a member of `oneof`_ ``_ha_policy``. health_checks (MutableSequence[str]): @@ -21294,8 +21323,8 @@ class BackendService(proto.Message): Specifies the load balancer type. A backend service created for one type of load balancer cannot be used with another. For more - information, refer toChoosing - a load balancer. + information, refer to + Backend services product and scheme table. Check the LoadBalancingScheme enum for the list of possible values. @@ -21346,31 +21375,39 @@ class BackendService(proto.Message): If set, the Backend Service responses are expected to contain non-standard HTTP response header field Endpoint-Load-Metrics. The reported metrics to use for computing the weights are specified via thecustomMetrics field. + - WEIGHTED_MAGLEV: Per-endpoint weighted load balancing via + health check reported weights. If set, the backend service must configure + an HTTP-based Health Check, and health check replies are expected to + contain the non-standard HTTP response header fieldX-Load-Balancing-Endpoint-Weight to specify the per-endpoint + weights. If set, load balancing is weighted based on the per-endpoint + weights reported in the last processed health check replies, as long as + every instance either reported a valid weight or had UNAVAILABLE_WEIGHT. + Otherwise, load balancing remains equal-weight. - This field is applicable to either: - - A regional backend service with the service protocol set to HTTP, - HTTPS, HTTP2 or H2C, and load_balancing_scheme set to - INTERNAL_MANAGED. - - A global backend service with the - load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or - EXTERNAL_MANAGED. - - - If sessionAffinity is not configured—that is, if session - affinity remains at the default value of NONE—then the - default value for localityLbPolicy - is ROUND_ROBIN. If session affinity is set to a value other - than NONE, - then the default value for localityLbPolicy isMAGLEV. + This field is applicable to either: - Only ROUND_ROBIN and RING_HASH are supported - when the backend service is referenced by a URL map that is bound to - target gRPC proxy that has validateForProxyless field set to true. + :: - localityLbPolicy cannot be specified with haPolicy. + - A regional backend service with the service protocol set to HTTP, + HTTPS, HTTP2 or H2C, and load_balancing_scheme set to + INTERNAL_MANAGED. + - A global backend service with the + load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or + EXTERNAL_MANAGED. + + If sessionAffinity is not configured—that is, if session + affinity remains at the default value of NONE—then the + default value for localityLbPolicy is ROUND_ROBIN. If + session affinity is set to a value other than NONE, then the + default value for localityLbPolicy isMAGLEV. + + Only ROUND_ROBIN and RING_HASH are supported when the + backend service is referenced by a URL map that is bound to + target gRPC proxy that has validateForProxyless field set to + true. - Check the LocalityLbPolicy enum for the list of possible - values. + localityLbPolicy cannot be specified with haPolicy. Check + the LocalityLbPolicy enum for the list of possible values. This field is a member of `oneof`_ ``_locality_lb_policy``. log_config (google.cloud.compute_v1beta.types.BackendServiceLogConfig): @@ -21514,13 +21551,12 @@ class BackendService(proto.Message): protocol (str): The protocol this BackendService uses to communicate with backends. - Possible values are HTTP, HTTPS, HTTP2, H2C, - TCP, SSL, UDP or GRPC. depending on the chosen - load balancer or Traffic Director configuration. - Refer to the documentation for the load - balancers or for Traffic Director for more - information. + TCP, SSL, UDP, GRPC, or UNSPECIFIED, depending + on the chosen load balancer or Traffic Director + configuration. + Refer to + Load balancing features for more information. Must be set to GRPC when the backend service is referenced by a URL map that is bound to target @@ -21754,8 +21790,8 @@ class IpAddressSelectionPolicy(proto.Enum): class LoadBalancingScheme(proto.Enum): r"""Specifies the load balancer type. A backend service created for one type of load balancer cannot be used with - another. For more information, refer toChoosing - a load balancer. + another. For more information, refer to + Backend services product and scheme table. Values: UNDEFINED_LOAD_BALANCING_SCHEME (0): @@ -21827,28 +21863,37 @@ class LocalityLbPolicy(proto.Enum): If set, the Backend Service responses are expected to contain non-standard HTTP response header field Endpoint-Load-Metrics. The reported metrics to use for computing the weights are specified via thecustomMetrics field. + - WEIGHTED_MAGLEV: Per-endpoint weighted load balancing via + health check reported weights. If set, the backend service must configure + an HTTP-based Health Check, and health check replies are expected to + contain the non-standard HTTP response header fieldX-Load-Balancing-Endpoint-Weight to specify the per-endpoint + weights. If set, load balancing is weighted based on the per-endpoint + weights reported in the last processed health check replies, as long as + every instance either reported a valid weight or had UNAVAILABLE_WEIGHT. + Otherwise, load balancing remains equal-weight. - This field is applicable to either: - - A regional backend service with the service protocol set to HTTP, - HTTPS, HTTP2 or H2C, and load_balancing_scheme set to - INTERNAL_MANAGED. - - A global backend service with the - load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or - EXTERNAL_MANAGED. + This field is applicable to either: + :: - If sessionAffinity is not configured—that is, if session - affinity remains at the default value of NONE—then the - default value for localityLbPolicy - is ROUND_ROBIN. If session affinity is set to a value other - than NONE, - then the default value for localityLbPolicy isMAGLEV. + - A regional backend service with the service protocol set to HTTP, + HTTPS, HTTP2 or H2C, and load_balancing_scheme set to + INTERNAL_MANAGED. + - A global backend service with the + load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or + EXTERNAL_MANAGED. - Only ROUND_ROBIN and RING_HASH are supported - when the backend service is referenced by a URL map that is bound to - target gRPC proxy that has validateForProxyless field set to true. + If sessionAffinity is not configured—that is, if session affinity + remains at the default value of NONE—then the default value for + localityLbPolicy is ROUND_ROBIN. If session affinity is set to a + value other than NONE, then the default value for localityLbPolicy + isMAGLEV. - localityLbPolicy cannot be specified with haPolicy. + Only ROUND_ROBIN and RING_HASH are supported when the backend + service is referenced by a URL map that is bound to target gRPC + proxy that has validateForProxyless field set to true. + + localityLbPolicy cannot be specified with haPolicy. Values: UNDEFINED_LOCALITY_LB_POLICY (0): @@ -21933,13 +21978,13 @@ class LocalityLbPolicy(proto.Enum): WEIGHTED_ROUND_ROBIN = 5584977 class Protocol(proto.Enum): - r"""The protocol this BackendService uses to communicate - with backends. - - Possible values are HTTP, HTTPS, HTTP2, H2C, TCP, SSL, UDP or - GRPC. depending on the chosen load balancer or Traffic Director - configuration. Refer to the documentation for the load balancers - or for Traffic Director for more information. + r"""The protocol this BackendService uses to communicate with + backends. + Possible values are HTTP, HTTPS, HTTP2, H2C, TCP, SSL, UDP, + GRPC, or UNSPECIFIED, depending on the chosen load balancer or + Traffic Director configuration. + Refer to + Load balancing features for more information. Must be set to GRPC when the backend service is referenced by a URL map that is bound to target gRPC proxy. @@ -22445,16 +22490,16 @@ class BackendServiceCdnPolicy(proto.Message): This field is a member of `oneof`_ ``_cache_key_policy``. cache_mode (str): Specifies the cache setting for all responses from this - backend. The possible values are:USE_ORIGIN_HEADERS Requires - the origin to set valid caching headers to cache content. - Responses without these headers will not be cached at - Google's edge, and will require a full trip to the origin on - every request, potentially impacting performance and - increasing load on the origin server.FORCE_CACHE_ALL Cache + backend. The possible values are: USE_ORIGIN_HEADERS + Requires the origin to set valid caching headers to cache + content. Responses without these headers will not be cached + at Google's edge, and will require a full trip to the origin + on every request, potentially impacting performance and + increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, - per-user (user identifiable) content.CACHE_ALL_STATIC + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as @@ -22583,19 +22628,19 @@ class BackendServiceCdnPolicy(proto.Message): class CacheMode(proto.Enum): r"""Specifies the cache setting for all responses from this backend. The - possible values are:USE_ORIGIN_HEADERS Requires the origin to set + possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting - performance and increasing load on the origin server.FORCE_CACHE_ALL - Cache all content, ignoring any "private", "no-store" or "no-cache" - directives in Cache-Control response headers. Warning: this may - result in Cloud CDN caching private, per-user (user identifiable) - content.CACHE_ALL_STATIC Automatically cache static content, - including common image formats, media (video and audio), and web - assets (JavaScript and CSS). Requests and responses that are marked - as uncacheable, as well as dynamic content (including HTML), will - not be cached. + performance and increasing load on the origin server. + FORCE_CACHE_ALL Cache all content, ignoring any "private", + "no-store" or "no-cache" directives in Cache-Control response + headers. Warning: this may result in Cloud CDN caching private, + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically + cache static content, including common image formats, media (video + and audio), and web assets (JavaScript and CSS). Requests and + responses that are marked as uncacheable, as well as dynamic content + (including HTML), will not be cached. If no value is provided for cdnPolicy.cacheMode, it defaults to CACHE_ALL_STATIC. @@ -27159,7 +27204,6 @@ class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDis Attributes: type_ (str): Specifies the type of the disk. - This field must be set to SCRATCH. Check the Type enum for the list of possible values. @@ -27168,16 +27212,15 @@ class CapacityAdviceRequestInstanceFlexibilityPolicyInstanceSelectionAttachedDis class Type(proto.Enum): r"""Specifies the type of the disk. - This field must be set to SCRATCH. Values: UNDEFINED_TYPE (0): A value indicating that the enum field is not set. DISK_TYPE_UNSPECIFIED (333621236): - No description available. + Default value, unspecified disk type. SCRATCH (496778970): - No description available. + Scratch disk (Local SSD). """ UNDEFINED_TYPE = 0 @@ -28447,6 +28490,12 @@ class Type(proto.Enum): 16TB of memory. NETWORK_OPTIMIZED_C4N (147027572): CUD bucket for C4N (dual Diorite) machines. + NETWORK_OPTIMIZED_U4C (147044859): + CUD bucket for NETWORK_OPTIMIZED_U4C machines. + NETWORK_OPTIMIZED_U4P (147044872): + CUD bucket for NETWORK_OPTIMIZED_U4P machines. + NETWORK_OPTIMIZED_U4S (147044875): + CUD bucket for NETWORK_OPTIMIZED_U4S machines. STORAGE_OPTIMIZED_Z3 (316796085): No description available. TYPE_UNSPECIFIED (437714322): @@ -28496,6 +28545,9 @@ class Type(proto.Enum): MEMORY_OPTIMIZED_X4_960_12T = 424752410 MEMORY_OPTIMIZED_X4_960_16T = 424752534 NETWORK_OPTIMIZED_C4N = 147027572 + NETWORK_OPTIMIZED_U4C = 147044859 + NETWORK_OPTIMIZED_U4P = 147044872 + NETWORK_OPTIMIZED_U4S = 147044875 STORAGE_OPTIMIZED_Z3 = 316796085 TYPE_UNSPECIFIED = 437714322 @@ -42697,6 +42749,9 @@ class ForwardingRule(proto.Message): - global/addresses/address-name - address-name + The IP address can only be set at creation. Once set, it + cannot be updated. + The forwarding rule's target or backendService, and in most cases, also the loadBalancingScheme, determine the type of IP address that you can use. For detailed information, see @@ -42706,9 +42761,86 @@ class ForwardingRule(proto.Message): When reading an IPAddress, the API always returns the IP address number. + When creating a global external Passthrough Network Load + Balancer forwarding rule (a parent forwarding rule), you + must use theIPAddresses field, but the Google Cloud + generated child forwarding rules set the IPAddress field + instead. Refer to theavailabilityGroup field for further + details. + This field is a member of `oneof`_ ``_I_p_address``. I_p_addresses (MutableSequence[str]): + IP addresses for which this forwarding rule accepts traffic. + All IP addresses must have the same IP version, IPv4 or + IPv6. When a client sends traffic that matches one of the + specified IP addresses, protocol and ports, the forwarding + rule directs the traffic to the referencedbackendService. + All IP addresses are served by the same set of backends, and + they share the target capacities specified in the backend + service fairly. + + Global external Passthrough Network Load Balancer requires + two IP addresses for each forwarding rule to provide high + availability when both IP addresses are used to serve client + requests. The two IP addresses must come from global IP + pools that belong to two distinct Availability Groups, + represented by the + purposePASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP0 + andPASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP1. + TheIPAddresses field specifies zero, one, or two IP + addresses: + + :: + + - If omitted, Google Cloud assigns two ephemeral IP addresses, one from + each Availability Group. + - If you specify one IP address that references an existing static IP + address resource from one Availability Group, Google Cloud assigns an + ephemeral IP address from the other Availability Group. + - If you specify two IP addresses that reference existing static IP + address resources, they are required to be from different Availability + Groups. + + For global external Passthrough Network Load Balancer, each + IP address can be one of the following: + + :: + + - A static or ephemeral IPv4 address from a Google-owned IP pool. + - A static IPv4 address from a global public delegated prefix. + - A static or ephemeral IPv6 /96 prefix from a Google-owned IP pool. + + For global external Passthrough Network Load Balancer, the + two IP addresses can be of different types. One IP address + can be from a BYOIP prefix while the other is from a + Google-owned IP pool. One IP address can be static while the + other is ephemeral. However, both IP addresses must have the + same IP version, IPv4 or IPv6. + + The IP addresses can only be set at creation and cannot be + updated. + + When creating a global external Passthrough Network Load + Balancer forwarding rule (a parent forwarding rule), you + must use theIPAddresses field, but the Google + Cloud-generated child forwarding rules set the IPAddress + field instead. Refer to theavailabilityGroup field for + further details. + + Refer to the IPAddress field for the formats that can be + used to specify IP addresses while creating a forwarding + rule. + + Because Passthrough Network Load Balancers do not terminate + or translate traffic, the backend stack types must be + compatible with the forwarding rule IP version: + + :: + - If the forwarding rule IP version is IPv4, backends should be + configured as dual-stack or IPv4-only. + - If the forwarding rule IP version is IPv6, backends should be + configured as dual-stack or IPv6-only. I_p_protocol (str): The IP protocol to which this rule applies. @@ -42766,20 +42898,52 @@ class ForwardingRule(proto.Message): Output only. [Output Only]. The extensions that are attached to this ForwardingRule. availability_group (str): - [Output Only] Specifies the availability group of the - forwarding rule. This field is for use by global external - passthrough load balancers (load balancing scheme - EXTERNAL_PASSTHROUGH) and is set for the child forwarding - rules only. Check the AvailabilityGroup enum for the list of - possible values. + Output only. [Output Only] Specifies the load balancing + availability group, one of the two that collectively provide + high availability. + + Specifies the availability group of the forwarding rule. + This field is for use by global external passthrough load + balancers (load balancing scheme EXTERNAL_PASSTHROUGH) and + is set for the child forwarding rules only. The possible + values are: + + :: + + - AVAILABILITY_GROUP0: Set for the child forwarding rule + that is programmed on the AVAILABILITY_GROUP0 load balancing + stack. The child forwarding rule has the same IP protocol, port, and + backend service settings as the parent forwarding rule, but has only one of + the two IP addresses of the parent forwarding rule, the one with the + purpose PASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP0. + - AVAILABILITY_GROUP1: Set for the child forwarding rule + that is programmed on the AVAILABILITY_GROUP1 load balancing + stack. The child forwarding rule has the same IP protocol, port and backend + service settings as the parent forwarding rule, but has only one of the two + IP addresses of the parent forwarding rule, the one with the purposePASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP1. + + For each global external Passthrough Network Load Balancer + forwarding rule (a parent forwarding rule) that you create, + Google Cloud generates two output-only child forwarding + rules, one forAVAILABILITY_GROUP0 and one + forAVAILABILITY_GROUP1. Check the AvailabilityGroup enum for + the list of possible values. This field is a member of `oneof`_ ``_availability_group``. backend_service (str): Identifies the backend service to which the - forwarding rule sends traffic. Required for - internal and external passthrough Network Load - Balancers; must be omitted for all other load - balancer types. + forwarding rule sends traffic. + It is a required field for the following load + balancers: + + - Internal passthrough Network Load Balancers + - Backend service-based regional external + passthrough Network Load Balancers + - Global external passthrough Network Load + Balancers + + It cannot be set by other load balancer types + and protocol forwarding rules. This field is a member of `oneof`_ ``_backend_service``. base_forwarding_rule (str): @@ -42792,13 +42956,17 @@ class ForwardingRule(proto.Message): This field is a member of `oneof`_ ``_base_forwarding_rule``. child_forwarding_rules (MutableSequence[str]): - Output only. [Output Only] Applicable only to the parent - forwarding rule of global external passthrough load - balancers. This field contains the list of child forwarding - rule URLs associated with the parent forwarding rule: one - for each availability group. AVAILABILITY_GROUP0 will be the - first element, and AVAILABILITY_GROUP1 will be the second - element. + Output only. [Output Only] The resource URLs for the child + forwarding rules. + + Applicable only to the parent forwarding rule of global + external passthrough load balancers. This field contains the + list of child forwarding rule URLs associated with the + parent forwarding rule: one for each availability group. + AVAILABILITY_GROUP0 will be the first element, and + AVAILABILITY_GROUP1 will be the second element. Refer to + theavailabilityGroup field for further details. It cannot be + set by any other forwarding rules. creation_timestamp (str): Output only. [Output Only] Creation timestamp inRFC3339 text format. @@ -42927,8 +43095,8 @@ class ForwardingRule(proto.Message): load_balancing_scheme (str): Specifies the forwarding rule type. - For more information about forwarding rules, - refer to Forwarding rule concepts. + For more information, refer to + Forwarding rule product and scheme table. Check the LoadBalancingScheme enum for the list of possible values. @@ -42971,6 +43139,16 @@ class ForwardingRule(proto.Message): 1-20 characters string with lowercase letters and numbers and must start with a letter. + For global external Passthrough Network Load Balancer + forwarding rules, the forwarding rule name must be 1-43 + characters long. For each global external Passthrough + Network Load Balancer forwarding rule (a parent forwarding + rule) that you create, Google Cloud generates two + output-only child forwarding rules that are named by + concatenating the parent forwarding rule name with the + ``-ag0`` and ``-ag1`` suffixes, respectively. Refer to + theavailabilityGroup field for further details. + This field is a member of `oneof`_ ``_name``. network (str): This field is not used for global external @@ -43015,11 +43193,13 @@ class ForwardingRule(proto.Message): This field is a member of `oneof`_ ``_no_automate_dns_zone``. parent_forwarding_rule (str): - Output only. [Output Only] Applicable only to the child - forwarding rules of global external passthrough load - balancers. This field contains the URL of the parent + Output only. [Output Only] The resource URL for the parent forwarding rule. + Applicable only to the child forwarding rules of global + external passthrough load balancers. This field contains the + URL of the parent forwarding rule. + This field is a member of `oneof`_ ``_parent_forwarding_rule``. port_range (str): The ports, portRange, and allPorts fields are mutually @@ -43041,8 +43221,9 @@ class ForwardingRule(proto.Message): port specifications for details. For external forwarding rules, two or more forwarding rules - cannot use the same [IPAddress, IPProtocol] pair, and cannot - have overlappingportRanges. + cannot use the same [IPAddress, IPProtocol] pair (specified + inIPAddress, IPAddresses, IPProtocol fields) if they have + overlapping portRanges. For internal forwarding rules within the same VPC network, two or more forwarding rules cannot use the same [IPAddress, @@ -43070,8 +43251,9 @@ class ForwardingRule(proto.Message): commas. The ports can be contiguous or discontiguous. For external forwarding rules, two or more forwarding rules - cannot use the same [IPAddress, IPProtocol] pair if they - share at least one port number. + cannot use the same [IPAddress, IPProtocol] pair (specified + inIPAddress, IPAddresses, IPProtocol fields) if they share + at least one port number. For internal forwarding rules within the same VPC network, two or more forwarding rules cannot use the same [IPAddress, @@ -43177,14 +43359,46 @@ class ForwardingRule(proto.Message): - For Private Service Connect forwarding rules that forward traffic to managed services, the target must be a service attachment. The target is not mutable once set as a service attachment. + The following load balancers cannot set the target field + (they should set the backendService field instead): + + :: + + - Internal passthrough Network Load Balancers + - Backend service-based regional external passthrough Network Load + Balancers + - Global external passthrough Network Load Balancers + This field is a member of `oneof`_ ``_target``. """ class AvailabilityGroup(proto.Enum): - r"""[Output Only] Specifies the availability group of the forwarding - rule. This field is for use by global external passthrough load - balancers (load balancing scheme EXTERNAL_PASSTHROUGH) and is set - for the child forwarding rules only. + r"""Output only. [Output Only] Specifies the load balancing availability + group, one of the two that collectively provide high availability. + + Specifies the availability group of the forwarding rule. This field + is for use by global external passthrough load balancers (load + balancing scheme EXTERNAL_PASSTHROUGH) and is set for the child + forwarding rules only. The possible values are: + + :: + + - AVAILABILITY_GROUP0: Set for the child forwarding rule + that is programmed on the AVAILABILITY_GROUP0 load balancing + stack. The child forwarding rule has the same IP protocol, port, and + backend service settings as the parent forwarding rule, but has only one of + the two IP addresses of the parent forwarding rule, the one with the + purpose PASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP0. + - AVAILABILITY_GROUP1: Set for the child forwarding rule + that is programmed on the AVAILABILITY_GROUP1 load balancing + stack. The child forwarding rule has the same IP protocol, port and backend + service settings as the parent forwarding rule, but has only one of the two + IP addresses of the parent forwarding rule, the one with the purposePASSTHROUGH_LOAD_BALANCER_AVAILABILITY_GROUP1. + + For each global external Passthrough Network Load Balancer + forwarding rule (a parent forwarding rule) that you create, Google + Cloud generates two output-only child forwarding rules, one + forAVAILABILITY_GROUP0 and one forAVAILABILITY_GROUP1. Values: UNDEFINED_AVAILABILITY_GROUP (0): @@ -43303,8 +43517,8 @@ class IpVersion(proto.Enum): class LoadBalancingScheme(proto.Enum): r"""Specifies the forwarding rule type. - For more information about forwarding rules, refer to Forwarding - rule concepts. + For more information, refer to + Forwarding rule product and scheme table. Values: UNDEFINED_LOAD_BALANCING_SCHEME (0): @@ -44043,6 +44257,13 @@ class FutureReservation(proto.Message): reservation_name or a name_prefix. This field is a member of `oneof`_ ``_reservation_name``. + resource_name (str): + Name of the resource intended to be + delivered. Name should conform to RFC1035. This + will be the name of storage pool or Exapool for + persistent disk FRs. + + This field is a member of `oneof`_ ``_resource_name``. scheduling_type (str): Maintenance information for this reservation Check the SchedulingType enum for the list of @@ -44080,6 +44301,11 @@ class FutureReservation(proto.Message): Output only. [Output only] Status of the Future Reservation This field is a member of `oneof`_ ``_status``. + storage_pool_properties (google.cloud.compute_v1beta.types.FutureReservationStoragePoolProperties): + Storage pool details for the future + reservation. + + This field is a member of `oneof`_ ``_storage_pool_properties``. time_window (google.cloud.compute_v1beta.types.FutureReservationTimeWindow): Time window for this Future Reservation. @@ -44337,6 +44563,11 @@ class SchedulingType(proto.Enum): number=277311262, optional=True, ) + resource_name: str = proto.Field( + proto.STRING, + number=442550300, + optional=True, + ) scheduling_type: str = proto.Field( proto.STRING, number=199835397, @@ -44375,6 +44606,12 @@ class SchedulingType(proto.Enum): optional=True, message="FutureReservationStatus", ) + storage_pool_properties: "FutureReservationStoragePoolProperties" = proto.Field( + proto.MESSAGE, + number=71410546, + optional=True, + message="FutureReservationStoragePoolProperties", + ) time_window: "FutureReservationTimeWindow" = proto.Field( proto.MESSAGE, number=422983074, @@ -44561,6 +44798,11 @@ class FutureReservationStatus(proto.Message): auto_created_reservations (MutableSequence[str]): Output only. Fully qualified urls of the automatically created reservations at start_time. + exapool_provisioned_capacity_gb (google.cloud.compute_v1beta.types.StoragePoolExapoolProvisionedCapacityGb): + Output only. Exapool provisioned capacities + for each SKU type. + + This field is a member of `oneof`_ ``_exapool_provisioned_capacity_gb``. existing_matching_usage_info (google.cloud.compute_v1beta.types.FutureReservationStatusExistingMatchingUsageInfo): Output only. [Output Only] Represents the existing matching usage for the future reservation. @@ -44601,6 +44843,11 @@ class FutureReservationStatus(proto.Message): specific_sku_properties (google.cloud.compute_v1beta.types.FutureReservationStatusSpecificSKUProperties): This field is a member of `oneof`_ ``_specific_sku_properties``. + storage_pool_provisioned_capacity (google.cloud.compute_v1beta.types.FutureReservationStoragePoolProvisionedCapacity): + Output only. Storage pool provisioned + capacities for each SKU type. + + This field is a member of `oneof`_ ``_storage_pool_provisioned_capacity``. """ class AmendmentStatus(proto.Enum): @@ -44705,6 +44952,14 @@ class ProcurementStatus(proto.Enum): proto.STRING, number=140217006, ) + exapool_provisioned_capacity_gb: "StoragePoolExapoolProvisionedCapacityGb" = ( + proto.Field( + proto.MESSAGE, + number=345174240, + optional=True, + message="StoragePoolExapoolProvisionedCapacityGb", + ) + ) existing_matching_usage_info: "FutureReservationStatusExistingMatchingUsageInfo" = ( proto.Field( proto.MESSAGE, @@ -44742,6 +44997,12 @@ class ProcurementStatus(proto.Enum): message="FutureReservationStatusSpecificSKUProperties", ) ) + storage_pool_provisioned_capacity: "FutureReservationStoragePoolProvisionedCapacity" = proto.Field( + proto.MESSAGE, + number=135892964, + optional=True, + message="FutureReservationStoragePoolProvisionedCapacity", + ) class FutureReservationStatusExistingMatchingUsageInfo(proto.Message): @@ -44982,6 +45243,87 @@ class FutureReservationStatusSpecificSKUProperties(proto.Message): ) +class FutureReservationStoragePoolProperties(proto.Message): + r"""Storage pool properties for the future reservation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + requested_exapool_provisioned_capacity_gb (google.cloud.compute_v1beta.types.StoragePoolExapoolProvisionedCapacityGb): + Requested exapool provisioned capacity in + GiB. + + This field is a member of `oneof`_ ``_requested_exapool_provisioned_capacity_gb``. + requested_storage_pool_provisioned_capacity (google.cloud.compute_v1beta.types.FutureReservationStoragePoolProvisionedCapacity): + Requested storage pool provisioned capacity. + + This field is a member of `oneof`_ ``_requested_storage_pool_provisioned_capacity``. + storage_pool_type (str): + Type of the storage pool. + + This field is a member of `oneof`_ ``_storage_pool_type``. + """ + + requested_exapool_provisioned_capacity_gb: "StoragePoolExapoolProvisionedCapacityGb" = proto.Field( + proto.MESSAGE, + number=174982159, + optional=True, + message="StoragePoolExapoolProvisionedCapacityGb", + ) + requested_storage_pool_provisioned_capacity: "FutureReservationStoragePoolProvisionedCapacity" = proto.Field( + proto.MESSAGE, + number=326931283, + optional=True, + message="FutureReservationStoragePoolProvisionedCapacity", + ) + storage_pool_type: str = proto.Field( + proto.STRING, + number=285999289, + optional=True, + ) + + +class FutureReservationStoragePoolProvisionedCapacity(proto.Message): + r"""Storage pool provisioned capacities for each SKU type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pool_provisioned_capacity_gb (int): + Size of the storage pool in GiB. + + This field is a member of `oneof`_ ``_pool_provisioned_capacity_gb``. + pool_provisioned_iops (int): + Provisioned IOPS of the storage pool. Only + relevant if the storage pool type is + hyperdisk-balanced. + + This field is a member of `oneof`_ ``_pool_provisioned_iops``. + pool_provisioned_throughput (int): + Provisioned throughput of the storage pool in + MiB/s. Only relevant if the storage pool type is + hyperdisk-balanced or hyperdisk-throughput. + + This field is a member of `oneof`_ ``_pool_provisioned_throughput``. + """ + + pool_provisioned_capacity_gb: int = proto.Field( + proto.INT64, + number=478537682, + optional=True, + ) + pool_provisioned_iops: int = proto.Field( + proto.INT64, + number=112092311, + optional=True, + ) + pool_provisioned_throughput: int = proto.Field( + proto.INT64, + number=169215640, + optional=True, + ) + + class FutureReservationTimeWindow(proto.Message): r""" @@ -49072,6 +49414,27 @@ class GetMacsecConfigInterconnectRequest(proto.Message): ) +class GetManagedRulesetRequest(proto.Message): + r"""A request message for ManagedRulesets.Get. See the method + description for details. + + Attributes: + managed_ruleset (str): + Name of the managed ruleset to return. + project (str): + Project ID for this request. + """ + + managed_ruleset: str = proto.Field( + proto.STRING, + number=447322950, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + + class GetNamedSetRouterRequest(proto.Message): r"""A request message for Routers.GetNamedSet. See the method description for details. @@ -56588,11 +56951,6 @@ class HealthStatus(proto.Message): class HealthState(proto.Enum): r"""Health state of the IPv4 address of the instance. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - HEALTHY - UNHEALTHY Values: UNDEFINED_HEALTH_STATE (0): @@ -56767,26 +57125,19 @@ class HealthStatusForNetworkEndpoint(proto.Message): class HealthState(proto.Enum): r"""Health state of the network endpoint determined based on the health checks configured. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - DRAINING - HEALTHY - UNHEALTHY - UNKNOWN Values: UNDEFINED_HEALTH_STATE (0): A value indicating that the enum field is not set. DRAINING (480455402): - No description available. + Endpoint is being drained. HEALTHY (439801213): - No description available. + Endpoint is healthy. UNHEALTHY (462118084): - No description available. + Endpoint is unhealthy. UNKNOWN (433141802): - No description available. + Health status of the endpoint is unknown. """ UNDEFINED_HEALTH_STATE = 0 @@ -65213,6 +65564,7 @@ class Instance(proto.Message): For example: zones/us-central1-f/machineTypes/custom-4-5120 + For a full list of restrictions, read theSpecifications for custom machine types. @@ -66042,6 +66394,12 @@ class InstanceFlexibilityPolicyInstanceSelection(proto.Message): created from these properties. This field only accepts a machine type names, for example ``n2-standard-4`` and not URLs or partial URLs. + min_cpu_platform (str): + Name of the minimum CPU platform to be used + by this instance selection. e.g. 'Intel Ice + Lake'. + + This field is a member of `oneof`_ ``_min_cpu_platform``. rank (int): Rank when prioritizing the shape flexibilities. The instance selections with rank @@ -66061,6 +66419,11 @@ class InstanceFlexibilityPolicyInstanceSelection(proto.Message): proto.STRING, number=79720065, ) + min_cpu_platform: str = proto.Field( + proto.STRING, + number=242912759, + optional=True, + ) rank: int = proto.Field( proto.INT64, number=3492908, @@ -67465,9 +67828,6 @@ class DefaultActionOnFailure(proto.Enum): repairing VMs in a MIG. - DO_NOTHING: MIG does not repair a failed VM. - Additional supported values which may be not listed in the enum - directly due to technical reasons: DO_NOTHING REPAIR - Values: UNDEFINED_DEFAULT_ACTION_ON_FAILURE (0): A value indicating that the enum field is not @@ -67477,9 +67837,11 @@ class DefaultActionOnFailure(proto.Enum): Deleting the VM decreases the target size of the MIG. DO_NOTHING (451307513): - No description available. + MIG does not repair a failed VM. REPAIR (266277773): - No description available. + (default): MIG automatically repairs a failed + VM by recreating it. For more information, see + About repairing VMs in a MIG. """ UNDEFINED_DEFAULT_ACTION_ON_FAILURE = 0 @@ -89054,6 +89416,163 @@ class ListManagedInstancesRegionInstanceGroupManagersRequest(proto.Message): ) +class ListManagedRulesetsRequest(proto.Message): + r"""A request message for ManagedRulesets.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. + + If you want to use AIP-160, your expression must specify the + field name, an operator, and the value that you want to use + for filtering. The value must be a string, a number, or a + boolean. The operator must be either ``=``, ``!=``, ``>``, + ``<``, ``<=``, ``>=`` or ``:``. + + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. + + The ``:*`` comparison can be used to test whether a key has + been defined. For example, to find all objects with + ``owner`` label use: + + :: + + labels.owner:* + + You can also filter nested fields. For example, you could + specify ``scheduling.automaticRestart = false`` to include + instances only if they are not scheduled for automatic + restarts. You can use filtering on nested fields to filter + based onresource labels. + + To filter on multiple expressions, provide each separate + expression within parentheses. For example: + + :: + + (scheduling.automaticRestart = true) + (cpuPlatform = "Intel Skylake") + + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + + :: + + (cpuPlatform = "Intel Skylake") OR + (cpuPlatform = "Intel Broadwell") AND + (scheduling.automaticRestart = true) + + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` + + The literal value is interpreted as a regular expression + using GoogleRE2 library syntax. The literal value must match + the entire field. + + For example, to filter for instances that do not end with + name "instance", you would use ``name ne .*instance``. + + You cannot combine constraints on multiple fields using + regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListNamedSetsRoutersRequest(proto.Message): r"""A request message for Routers.ListNamedSets. See the method description for details. @@ -106999,7 +107518,7 @@ class InstanceStatus(proto.Enum): r"""Output only. [Output Only] The status of the instance. This field is empty when the instance does not exist. Additional supported values which may be not listed in the enum directly due to technical - reasons: RUNNING STOPPED STOPPING SUSPENDED SUSPENDING + reasons: RUNNING STOPPED SUSPENDED Values: UNDEFINED_INSTANCE_STATUS (0): @@ -107028,11 +107547,12 @@ class InstanceStatus(proto.Enum): STOPPED (444276141): No description available. STOPPING (350791796): - No description available. + The instance is currently stopping (either + being deleted or killed). SUSPENDED (51223995): No description available. SUSPENDING (514206246): - No description available. + The instance is suspending. TERMINATED (250018339): The instance has stopped (either by explicit action or underlying failure). @@ -107462,6 +107982,150 @@ class ManagedInstanceVersion(proto.Message): ) +class ManagedRuleset(proto.Message): + r"""Represents a ManagedRuleset resource. + + Managed internally by Cloud Armor CLH for Managed Rules + features. Customers can only view these resources to modify + their Security Policies. For more information, see + https://cloud.google.com/armor/docs/. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + change_log (str): + Output only. [Output Only] The change log for this managed + ruleset. + + This field is a member of `oneof`_ ``_change_log``. + creation_timestamp (str): + Output only. [Output Only] Creation timestamp in RFC3339 + text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + [Output Only] An optional description of this resource. + + This field is a member of `oneof`_ ``_description``. + id (int): + Output only. [Output Only] The unique identifier for the + resource. This identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + name (str): + Name of the resource. Generated internally when the resource + is created. The name must be 1-63 characters long, and + comply withRFC1035. Specifically, the name 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 field is a member of `oneof`_ ``_name``. + rule_ids (MutableSequence[str]): + Output only. [Output Only] The list of managed rule IDs that + are included in this managed ruleset. + ruleset_id (str): + Output only. [Output Only] The managed ruleset identifier + that can be configured in Security Policy rules. + + This field is a member of `oneof`_ ``_ruleset_id``. + self_link (str): + Output only. [Output Only] Server-defined URL for the + resource. + + This field is a member of `oneof`_ ``_self_link``. + """ + + change_log: str = proto.Field( + proto.STRING, + number=15896117, + optional=True, + ) + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + rule_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=226918133, + ) + ruleset_id: str = proto.Field( + proto.STRING, + number=131214356, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + + +class ManagedRulesetList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1beta.types.ManagedRuleset]): + + next_page_token (str): + + This field is a member of `oneof`_ ``_next_page_token``. + warning (google.cloud.compute_v1beta.types.Warning): + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["ManagedRuleset"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="ManagedRuleset", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class Metadata(proto.Message): r"""A metadata key/value entry. @@ -113373,8 +114037,7 @@ class NetworkProfileNetworkFeatures(proto.Message): """ class AddressPurposes(proto.Enum): - r"""Additional supported values which may be not listed in the enum - directly due to technical reasons: PRIVATE_SERVICE_CONNECT + r""" Values: UNDEFINED_ADDRESS_PURPOSES (0): @@ -113410,7 +114073,10 @@ class AddressPurposes(proto.Enum): Load Balancer forwarding rules, as an Availability Group 1 address. PRIVATE_SERVICE_CONNECT (48134724): - No description available. + A private network IP address that can be used + to configure Private Service Connect. This + purpose can be specified only forGLOBAL + addresses of Type INTERNAL SERVERLESS (270492508): A regional internal IP address range reserved for Serverless. @@ -114605,9 +115271,7 @@ class BgpBestPathSelectionMode(proto.Enum): class BgpInterRegionCost(proto.Enum): r"""Allows to define a preferred approach for handling inter-region cost in the selection process when using the STANDARD BGP best path - selection algorithm. Can be DEFAULT orADD_COST_TO_MED. Additional - supported values which may be not listed in the enum directly due to - technical reasons: ADD_COST_TO_MED DEFAULT + selection algorithm. Can be DEFAULT orADD_COST_TO_MED. Values: UNDEFINED_BGP_INTER_REGION_COST (0): @@ -127948,7 +128612,7 @@ class QuotaStatusWarning(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. @@ -128399,8 +129063,8 @@ class RegexRewrite(proto.Message): Attributes: path_pattern (str): - The regular expression used to match against the URL path. - It uses RE2 syntax with the following constraints: + Required. The regular expression used to match against the + URL path. It uses RE2 syntax with the following constraints: :: @@ -128427,8 +129091,9 @@ class RegexRewrite(proto.Message): This field is a member of `oneof`_ ``_path_pattern``. path_substitution (str): - Required when path pattern is specified. Used - to rewrite matching parts of the path. + Required. Required when path pattern is + specified. Used to rewrite matching parts of the + path. This field is a member of `oneof`_ ``_path_substitution``. """ @@ -145412,13 +146077,16 @@ class SecurityPolicyRuleRateLimitOptions(proto.Message): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, - the key type defaults to ALL. For "fairshare" action, this - value is limited to ALL i.e. a single rate limit threshold - is enforced for all the requests matching the rule. Check - the EnforceOnKey enum for the list of possible values. + For "fairshare" action, this value is limited to ALL i.e. a + single rate limit threshold is enforced for all the requests + matching the rule. Check the EnforceOnKey enum for the list + of possible values. This field is a member of `oneof`_ ``_enforce_on_key``. enforce_on_key_configs (MutableSequence[google.cloud.compute_v1beta.types.SecurityPolicyRuleRateLimitOptionsEnforceOnKeyConfig]): @@ -145499,12 +146167,15 @@ class EnforceOnKey(proto.Enum): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key - type defaults to ALL. For "fairshare" action, this value is - limited to ALL i.e. a single rate limit threshold is enforced for - all the requests matching the rule. + For "fairshare" action, this value is limited to ALL i.e. a single + rate limit threshold is enforced for all the requests matching the + rule. Values: UNDEFINED_ENFORCE_ON_KEY (0): @@ -145514,6 +146185,8 @@ class EnforceOnKey(proto.Enum): No description available. ALL_IPS (343973966): No description available. + ASN (65116): + No description available. HTTP_COOKIE (494981627): No description available. HTTP_HEADER (91597348): @@ -145539,6 +146212,7 @@ class EnforceOnKey(proto.Enum): UNDEFINED_ENFORCE_ON_KEY = 0 ALL = 64897 ALL_IPS = 343973966 + ASN = 65116 HTTP_COOKIE = 494981627 HTTP_HEADER = 91597348 HTTP_PATH = 311503228 @@ -145654,11 +146328,14 @@ class SecurityPolicyRuleRateLimitOptionsEnforceOnKeyConfig(proto.Message): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, - the key type defaults to ALL. Check the EnforceOnKeyType - enum for the list of possible values. + Check the EnforceOnKeyType enum for the list of possible + values. This field is a member of `oneof`_ ``_enforce_on_key_type``. """ @@ -145702,10 +146379,11 @@ class EnforceOnKeyType(proto.Enum): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. - - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key - type defaults to ALL. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. Values: UNDEFINED_ENFORCE_ON_KEY_TYPE (0): @@ -145715,6 +146393,8 @@ class EnforceOnKeyType(proto.Enum): No description available. ALL_IPS (343973966): No description available. + ASN (65116): + No description available. HTTP_COOKIE (494981627): No description available. HTTP_HEADER (91597348): @@ -145740,6 +146420,7 @@ class EnforceOnKeyType(proto.Enum): UNDEFINED_ENFORCE_ON_KEY_TYPE = 0 ALL = 64897 ALL_IPS = 343973966 + ASN = 65116 HTTP_COOKIE = 494981627 HTTP_HEADER = 91597348 HTTP_PATH = 311503228 @@ -161859,7 +162540,7 @@ class TargetPool(proto.Message): The server-defined URL for the resource. This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool, and its failoverRatio - field is properly set to a value between [0, 1].backupPool + field is properly set to a value between [0, 1]. backupPool and failoverRatio together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or belowfailoverRatio, @@ -173122,7 +173803,7 @@ class WaitZoneOperationRequest(proto.Message): class Warning(proto.Message): - r"""Informational warning message. + r""" .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -173138,7 +173819,7 @@ class Warning(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. @@ -173312,7 +173993,7 @@ class Warnings(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_get_sync.py new file mode 100644 index 000000000000..97973546ed95 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_get_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 Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_ManagedRulesets_Get_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 compute_v1beta + + +def sample_get(): + # Create a client + client = compute_v1beta.ManagedRulesetsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetManagedRulesetRequest( + managed_ruleset="managed_ruleset_value", + project="project_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_ManagedRulesets_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_list_sync.py new file mode 100644 index 000000000000..225f5e832ad4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_managed_rulesets_list_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 List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute-v1beta + + +# [START compute_v1beta_generated_ManagedRulesets_List_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 compute_v1beta + + +def sample_list(): + # Create a client + client = compute_v1beta.ManagedRulesetsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListManagedRulesetsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_ManagedRulesets_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json index 4af065031e4a..3d8431cd93b8 100644 --- a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json @@ -33763,6 +33763,170 @@ ], "title": "compute_v1beta_generated_machine_types_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ManagedRulesetsClient", + "shortName": "ManagedRulesetsClient" + }, + "fullName": "google.cloud.compute_v1beta.ManagedRulesetsClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.ManagedRulesets.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.ManagedRulesets", + "shortName": "ManagedRulesets" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetManagedRulesetRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "managed_ruleset", + "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.compute_v1beta.types.ManagedRuleset", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_managed_rulesets_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_ManagedRulesets_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_managed_rulesets_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ManagedRulesetsClient", + "shortName": "ManagedRulesetsClient" + }, + "fullName": "google.cloud.compute_v1beta.ManagedRulesetsClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.ManagedRulesets.List", + "service": { + "fullName": "google.cloud.compute.v1beta.ManagedRulesets", + "shortName": "ManagedRulesets" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListManagedRulesetsRequest" + }, + { + "name": "project", + "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.compute_v1beta.services.managed_rulesets.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_managed_rulesets_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_ManagedRulesets_List_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": "compute_v1beta_generated_managed_rulesets_list_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py index 4bee67f20358..786762f7412e 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py @@ -4334,6 +4334,7 @@ def test_get_rest_call_success(request_type): protection_tier="protection_tier_value", reservation_mode="reservation_mode_value", reservation_name="reservation_name_value", + resource_name="resource_name_value", scheduling_type="scheduling_type_value", self_link="self_link_value", self_link_with_id="self_link_with_id_value", @@ -4373,6 +4374,7 @@ def test_get_rest_call_success(request_type): assert response.protection_tier == "protection_tier_value" assert response.reservation_mode == "reservation_mode_value" assert response.reservation_name == "reservation_name_value" + assert response.resource_name == "resource_name_value" assert response.scheduling_type == "scheduling_type_value" assert response.self_link == "self_link_value" assert response.self_link_with_id == "self_link_with_id_value" @@ -4524,6 +4526,7 @@ def test_insert_rest_call_success(request_type): "protection_tier": "protection_tier_value", "reservation_mode": "reservation_mode_value", "reservation_name": "reservation_name_value", + "resource_name": "resource_name_value", "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", @@ -4558,6 +4561,11 @@ def test_insert_rest_call_success(request_type): "auto_created_reservations_value1", "auto_created_reservations_value2", ], + "exapool_provisioned_capacity_gb": { + "capacity_optimized": 1922, + "read_optimized": 1488, + "write_optimized": 1631, + }, "existing_matching_usage_info": { "count": 553, "timestamp": "timestamp_value", @@ -4584,6 +4592,16 @@ def test_insert_rest_call_success(request_type): "specific_sku_properties": { "source_instance_template_id": "source_instance_template_id_value" }, + "storage_pool_provisioned_capacity": { + "pool_provisioned_capacity_gb": 2976, + "pool_provisioned_iops": 2277, + "pool_provisioned_throughput": 2948, + }, + }, + "storage_pool_properties": { + "requested_exapool_provisioned_capacity_gb": {}, + "requested_storage_pool_provisioned_capacity": {}, + "storage_pool_type": "storage_pool_type_value", }, "time_window": {}, "zone": "zone_value", @@ -5024,6 +5042,7 @@ def test_update_rest_call_success(request_type): "protection_tier": "protection_tier_value", "reservation_mode": "reservation_mode_value", "reservation_name": "reservation_name_value", + "resource_name": "resource_name_value", "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", @@ -5058,6 +5077,11 @@ def test_update_rest_call_success(request_type): "auto_created_reservations_value1", "auto_created_reservations_value2", ], + "exapool_provisioned_capacity_gb": { + "capacity_optimized": 1922, + "read_optimized": 1488, + "write_optimized": 1631, + }, "existing_matching_usage_info": { "count": 553, "timestamp": "timestamp_value", @@ -5084,6 +5108,16 @@ def test_update_rest_call_success(request_type): "specific_sku_properties": { "source_instance_template_id": "source_instance_template_id_value" }, + "storage_pool_provisioned_capacity": { + "pool_provisioned_capacity_gb": 2976, + "pool_provisioned_iops": 2277, + "pool_provisioned_throughput": 2948, + }, + }, + "storage_pool_properties": { + "requested_exapool_provisioned_capacity_gb": {}, + "requested_storage_pool_provisioned_capacity": {}, + "storage_pool_type": "storage_pool_type_value", }, "time_window": {}, "zone": "zone_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_managed_rulesets.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_managed_rulesets.py new file mode 100644 index 000000000000..dadce23278f4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_managed_rulesets.py @@ -0,0 +1,2395 @@ +# -*- 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.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.managed_rulesets import ( + ManagedRulesetsClient, + pagers, + transports, +) +from google.cloud.compute_v1beta.types import compute + +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 ManagedRulesetsClient._get_default_mtls_endpoint(None) is None + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + assert ( + ManagedRulesetsClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert ManagedRulesetsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ManagedRulesetsClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ManagedRulesetsClient._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: + ManagedRulesetsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ManagedRulesetsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ManagedRulesetsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ManagedRulesetsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ManagedRulesetsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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): + ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._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 ManagedRulesetsClient._get_client_cert_source(None, False) is None + assert ( + ManagedRulesetsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ManagedRulesetsClient._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 ( + ManagedRulesetsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ManagedRulesetsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ManagedRulesetsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ManagedRulesetsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ManagedRulesetsClient._DEFAULT_UNIVERSE + default_endpoint = ManagedRulesetsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ManagedRulesetsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ManagedRulesetsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ManagedRulesetsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ManagedRulesetsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ManagedRulesetsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ManagedRulesetsClient._get_api_endpoint(None, None, default_universe, "always") + == ManagedRulesetsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ManagedRulesetsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ManagedRulesetsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ManagedRulesetsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ManagedRulesetsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ManagedRulesetsClient._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 ( + ManagedRulesetsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ManagedRulesetsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ManagedRulesetsClient._get_universe_domain(None, None) + == ManagedRulesetsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ManagedRulesetsClient._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 = ManagedRulesetsClient(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 = ManagedRulesetsClient(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", + [ + (ManagedRulesetsClient, "rest"), + ], +) +def test_managed_rulesets_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 == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ManagedRulesetsRestTransport, "rest"), + ], +) +def test_managed_rulesets_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", + [ + (ManagedRulesetsClient, "rest"), + ], +) +def test_managed_rulesets_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 == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_managed_rulesets_client_get_transport_class(): + transport = ManagedRulesetsClient.get_transport_class() + available_transports = [ + transports.ManagedRulesetsRestTransport, + ] + assert transport in available_transports + + transport = ManagedRulesetsClient.get_transport_class("rest") + assert transport == transports.ManagedRulesetsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ManagedRulesetsClient, transports.ManagedRulesetsRestTransport, "rest"), + ], +) +@mock.patch.object( + ManagedRulesetsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ManagedRulesetsClient), +) +def test_managed_rulesets_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(ManagedRulesetsClient, "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(ManagedRulesetsClient, "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", + [ + ( + ManagedRulesetsClient, + transports.ManagedRulesetsRestTransport, + "rest", + "true", + ), + ( + ManagedRulesetsClient, + transports.ManagedRulesetsRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + ManagedRulesetsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ManagedRulesetsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_managed_rulesets_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", [ManagedRulesetsClient]) +@mock.patch.object( + ManagedRulesetsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ManagedRulesetsClient), +) +def test_managed_rulesets_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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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", [ManagedRulesetsClient]) +@mock.patch.object( + ManagedRulesetsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ManagedRulesetsClient), +) +def test_managed_rulesets_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ManagedRulesetsClient._DEFAULT_UNIVERSE + default_endpoint = ManagedRulesetsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ManagedRulesetsClient._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", + [ + (ManagedRulesetsClient, transports.ManagedRulesetsRestTransport, "rest"), + ], +) +def test_managed_rulesets_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", + [ + (ManagedRulesetsClient, transports.ManagedRulesetsRestTransport, "rest", None), + ], +) +def test_managed_rulesets_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_get_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 = ManagedRulesetsClient( + 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 in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(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_rest_required_fields(request_type=compute.GetManagedRulesetRequest): + transport_class = transports.ManagedRulesetsRestTransport + + request_init = {} + request_init["managed_ruleset"] = "" + request_init["project"] = "" + 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._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["managedRuleset"] = "managed_ruleset_value" + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "managedRuleset" in jsonified_request + assert jsonified_request["managedRuleset"] == "managed_ruleset_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ManagedRuleset() + # 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 = compute.ManagedRuleset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "managedRuleset", + "project", + ) + ) + ) + + +def test_get_rest_flattened(): + client = ManagedRulesetsClient( + 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 = compute.ManagedRuleset() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "managed_ruleset": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + managed_ruleset="managed_ruleset_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 = compute.ManagedRuleset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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(**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/compute/beta/projects/{project}/global/managedRulesets/{managed_ruleset}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ManagedRulesetsClient( + 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( + compute.GetManagedRulesetRequest(), + project="project_value", + managed_ruleset="managed_ruleset_value", + ) + + +def test_list_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 = ManagedRulesetsClient( + 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 in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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] = mock_rpc + + request = {} + client.list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list(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_rest_required_fields(request_type=compute.ListManagedRulesetsRequest): + transport_class = transports.ManagedRulesetsRestTransport + + request_init = {} + request_init["project"] = "" + 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._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ManagedRulesetList() + # 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 = compute.ManagedRulesetList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = ManagedRulesetsClient( + 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 = compute.ManagedRulesetList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_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 = compute.ManagedRulesetList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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(**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/compute/beta/projects/{project}/global/managedRulesets" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = ManagedRulesetsClient( + 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( + compute.ListManagedRulesetsRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = ManagedRulesetsClient( + 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 = ( + compute.ManagedRulesetList( + items=[ + compute.ManagedRuleset(), + compute.ManagedRuleset(), + compute.ManagedRuleset(), + ], + next_page_token="abc", + ), + compute.ManagedRulesetList( + items=[], + next_page_token="def", + ), + compute.ManagedRulesetList( + items=[ + compute.ManagedRuleset(), + ], + next_page_token="ghi", + ), + compute.ManagedRulesetList( + items=[ + compute.ManagedRuleset(), + compute.ManagedRuleset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.ManagedRulesetList.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 = {"project": "sample1"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.ManagedRuleset) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ManagedRulesetsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ManagedRulesetsClient( + 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 = ManagedRulesetsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ManagedRulesetsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ManagedRulesetsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ManagedRulesetsRestTransport, + ], +) +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_rest(): + transport = ManagedRulesetsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetManagedRulesetRequest): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "managed_ruleset": "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.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetManagedRulesetRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "managed_ruleset": "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 = compute.ManagedRuleset( + change_log="change_log_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + name="name_value", + rule_ids=["rule_ids_value"], + ruleset_id="ruleset_id_value", + self_link="self_link_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 = compute.ManagedRuleset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.ManagedRuleset) + assert response.change_log == "change_log_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.name == "name_value" + assert response.rule_ids == ["rule_ids_value"] + assert response.ruleset_id == "ruleset_id_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ManagedRulesetsRestInterceptor(), + ) + client = ManagedRulesetsClient(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.ManagedRulesetsRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.ManagedRulesetsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ManagedRulesetsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetManagedRulesetRequest.pb( + compute.GetManagedRulesetRequest() + ) + 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 = compute.ManagedRuleset.to_json(compute.ManagedRuleset()) + req.return_value.content = return_value + + request = compute.GetManagedRulesetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ManagedRuleset() + post_with_metadata.return_value = compute.ManagedRuleset(), metadata + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_rest_bad_request(request_type=compute.ListManagedRulesetsRequest): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + 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(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListManagedRulesetsRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + 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 = compute.ManagedRulesetList( + id="id_value", + 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 = compute.ManagedRulesetList.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.ManagedRulesetsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ManagedRulesetsRestInterceptor(), + ) + client = ManagedRulesetsClient(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.ManagedRulesetsRestInterceptor, "post_list" + ) as post, + mock.patch.object( + transports.ManagedRulesetsRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ManagedRulesetsRestInterceptor, "pre_list") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListManagedRulesetsRequest.pb( + compute.ListManagedRulesetsRequest() + ) + 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 = compute.ManagedRulesetList.to_json(compute.ManagedRulesetList()) + req.return_value.content = return_value + + request = compute.ListManagedRulesetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ManagedRulesetList() + post_with_metadata.return_value = compute.ManagedRulesetList(), metadata + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = ManagedRulesetsClient( + 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_get_empty_call_rest(): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetManagedRulesetRequest() + assert args[0] == request_msg + + +# This 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_empty_call_rest(): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list), "__call__") as call: + client.list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListManagedRulesetsRequest() + assert args[0] == request_msg + + +def test_managed_rulesets_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ManagedRulesetsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_managed_rulesets_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.managed_rulesets.transports.ManagedRulesetsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ManagedRulesetsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get", + "list", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_managed_rulesets_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.compute_v1beta.services.managed_rulesets.transports.ManagedRulesetsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ManagedRulesetsTransport( + 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/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_managed_rulesets_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.compute_v1beta.services.managed_rulesets.transports.ManagedRulesetsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ManagedRulesetsTransport() + adc.assert_called_once() + + +def test_managed_rulesets_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) + ManagedRulesetsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_managed_rulesets_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.ManagedRulesetsRestTransport( + 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", + [ + "rest", + ], +) +def test_managed_rulesets_host_no_port(transport_name): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_managed_rulesets_host_with_port(transport_name): + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_managed_rulesets_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ManagedRulesetsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ManagedRulesetsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ManagedRulesetsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ManagedRulesetsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ManagedRulesetsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ManagedRulesetsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ManagedRulesetsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ManagedRulesetsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ManagedRulesetsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ManagedRulesetsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ManagedRulesetsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ManagedRulesetsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ManagedRulesetsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ManagedRulesetsClient.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 = ManagedRulesetsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ManagedRulesetsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ManagedRulesetsClient.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.ManagedRulesetsTransport, "_prep_wrapped_messages" + ) as prep: + client = ManagedRulesetsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ManagedRulesetsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ManagedRulesetsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = ManagedRulesetsClient( + 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", + ] + for transport in transports: + client = ManagedRulesetsClient( + 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", + [ + (ManagedRulesetsClient, transports.ManagedRulesetsRestTransport), + ], +) +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-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index c194c5e7e677..37c0cbe340ae 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -748,6 +748,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -1695,6 +1697,7 @@ RecreateInstancesInstanceGroupManagerRequest, RecreateInstancesRegionInstanceGroupManagerRequest, Reference, + RegexRewrite, Region, RegionAddressesMoveRequest, RegionAutoscalerList, @@ -1800,6 +1803,7 @@ ResizeReservationRequest, ResourceCommitment, ResourceGroupReference, + ResourceMetadata, ResourcePoliciesScopedList, ResourcePolicy, ResourcePolicyAggregatedList, @@ -2915,6 +2919,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureResourcesRecommendation", "FutureResourcesRecommendationOtherLocation", @@ -3862,6 +3868,7 @@ "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -3967,6 +3974,7 @@ "ResizeReservationRequest", "ResourceCommitment", "ResourceGroupReference", + "ResourceMetadata", "ResourcePoliciesScopedList", "ResourcePolicy", "ResourcePolicyAggregatedList", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 7b5e14dd37c6..9c92ce3f7a12 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -733,6 +733,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -1680,6 +1682,7 @@ RecreateInstancesInstanceGroupManagerRequest, RecreateInstancesRegionInstanceGroupManagerRequest, Reference, + RegexRewrite, Region, RegionAddressesMoveRequest, RegionAutoscalerList, @@ -1785,6 +1788,7 @@ ResizeReservationRequest, ResourceCommitment, ResourceGroupReference, + ResourceMetadata, ResourcePoliciesScopedList, ResourcePolicy, ResourcePolicyAggregatedList, @@ -2868,6 +2872,8 @@ def _get_version(dependency_name): "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureReservationsAggregatedListResponse", "FutureReservationsClient", @@ -3863,6 +3869,7 @@ def _get_version(dependency_name): "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -4006,6 +4013,7 @@ def _get_version(dependency_name): "ResizeReservationRequest", "ResourceCommitment", "ResourceGroupReference", + "ResourceMetadata", "ResourcePoliciesClient", "ResourcePoliciesScopedList", "ResourcePolicy", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index 104b154cb640..f05bb318a6be 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -452,6 +452,8 @@ FutureReservationStatusLastKnownGoodState, FutureReservationStatusLastKnownGoodStateFutureReservationSpecs, FutureReservationStatusSpecificSKUProperties, + FutureReservationStoragePoolProperties, + FutureReservationStoragePoolProvisionedCapacity, FutureReservationTimeWindow, FutureResourcesRecommendation, FutureResourcesRecommendationOtherLocation, @@ -1399,6 +1401,7 @@ RecreateInstancesInstanceGroupManagerRequest, RecreateInstancesRegionInstanceGroupManagerRequest, Reference, + RegexRewrite, Region, RegionAddressesMoveRequest, RegionAutoscalerList, @@ -1504,6 +1507,7 @@ ResizeReservationRequest, ResourceCommitment, ResourceGroupReference, + ResourceMetadata, ResourcePoliciesScopedList, ResourcePolicy, ResourcePolicyAggregatedList, @@ -2494,6 +2498,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureResourcesRecommendation", "FutureResourcesRecommendationOtherLocation", @@ -3441,6 +3447,7 @@ "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -3546,6 +3553,7 @@ "ResizeReservationRequest", "ResourceCommitment", "ResourceGroupReference", + "ResourceMetadata", "ResourcePoliciesScopedList", "ResourcePolicy", "ResourcePolicyAggregatedList", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 1dee5b6878b6..5b86c45eee55 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -458,6 +458,8 @@ "FutureReservationStatusLastKnownGoodState", "FutureReservationStatusLastKnownGoodStateFutureReservationSpecs", "FutureReservationStatusSpecificSKUProperties", + "FutureReservationStoragePoolProperties", + "FutureReservationStoragePoolProvisionedCapacity", "FutureReservationTimeWindow", "FutureReservationsAggregatedListResponse", "FutureReservationsListResponse", @@ -1408,6 +1410,7 @@ "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -1513,6 +1516,7 @@ "ResizeReservationRequest", "ResourceCommitment", "ResourceGroupReference", + "ResourceMetadata", "ResourcePoliciesScopedList", "ResourcePolicy", "ResourcePolicyAggregatedList", @@ -2454,6 +2458,14 @@ class AcceleratorType(proto.Message): [Output Only] Name of the resource. This field is a member of `oneof`_ ``_name``. + resource_metadata (google.cloud.compute_v1.types.ResourceMetadata): + Output only. Contains standard resource metadata for an + AcceleratorType resource. It is populated for each instance + of the AcceleratorType resource, and includes the + api_version the instance was retrieved through, and its + canonical resource_type name. + + This field is a member of `oneof`_ ``_resource_metadata``. self_link (str): Output only. [Output Only] Server-defined, fully qualified URL for this resource. @@ -2504,6 +2516,12 @@ class AcceleratorType(proto.Message): number=3373707, optional=True, ) + resource_metadata: "ResourceMetadata" = proto.Field( + proto.MESSAGE, + number=99063872, + optional=True, + message="ResourceMetadata", + ) self_link: str = proto.Field( proto.STRING, number=456214797, @@ -18529,9 +18547,11 @@ class Backend(proto.Message): guidelines, see Connection balancing mode. Backends must use compatible balancing modes. - For more information, see Supported balancing - modes and target capacity settings and - Restrictions and guidance for instance groups. + Backends of a backend service may use different + balancing modes. For more information, see + Supported balancing modes and target capacity + settings and Restrictions and guidance for + instance groups. Note: Currently, if you use the API to configure incompatible balancing modes, the configuration @@ -18574,6 +18594,11 @@ class Backend(proto.Message): failover backend. More than one failover backend can be configured for a given BackendService. + This field can only be used for a regional + external Passthrough Network Load Balancer or a + regional internal Passthrough Network Load + Balancer. + This field is a member of `oneof`_ ``_failover``. group (str): The fully-qualified URL of aninstance group or network @@ -18692,6 +18717,14 @@ class Backend(proto.Message): would be used and traffic would be assigned based on the load balancing algorithm you use. This is the default + + For global external Passthrough Network Load + Balancers, the following restrictions apply: + + - At most one backend can be marked as + PREFERRED. + - PREFERRED and DEFAULT backends cannot + reside in the same Cloud region. Check the Preference enum for the list of possible values. @@ -18708,7 +18741,8 @@ class BalancingMode(proto.Enum): balancer can handle additional traffic or is fully loaded. For usage guidelines, see Connection balancing mode. - Backends must use compatible balancing modes. For more + Backends must use compatible balancing modes. Backends of a + backend service may use different balancing modes. For more information, see Supported balancing modes and target capacity settings and Restrictions and guidance for instance groups. @@ -18756,6 +18790,13 @@ class Preference(proto.Enum): would be assigned based on the load balancing algorithm you use. This is the default + For global external Passthrough Network Load Balancers, the + following restrictions apply: + + - At most one backend can be marked as PREFERRED. + - PREFERRED and DEFAULT backends cannot reside + in the same Cloud region. + Values: UNDEFINED_PREFERENCE (0): A value indicating that the enum field is not @@ -19243,16 +19284,16 @@ class BackendBucketCdnPolicy(proto.Message): This field is a member of `oneof`_ ``_cache_key_policy``. cache_mode (str): Specifies the cache setting for all responses from this - backend. The possible values are:USE_ORIGIN_HEADERS Requires - the origin to set valid caching headers to cache content. - Responses without these headers will not be cached at - Google's edge, and will require a full trip to the origin on - every request, potentially impacting performance and - increasing load on the origin server.FORCE_CACHE_ALL Cache + backend. The possible values are: USE_ORIGIN_HEADERS + Requires the origin to set valid caching headers to cache + content. Responses without these headers will not be cached + at Google's edge, and will require a full trip to the origin + on every request, potentially impacting performance and + increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, - per-user (user identifiable) content.CACHE_ALL_STATIC + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as @@ -19381,19 +19422,19 @@ class BackendBucketCdnPolicy(proto.Message): class CacheMode(proto.Enum): r"""Specifies the cache setting for all responses from this backend. The - possible values are:USE_ORIGIN_HEADERS Requires the origin to set + possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting - performance and increasing load on the origin server.FORCE_CACHE_ALL - Cache all content, ignoring any "private", "no-store" or "no-cache" - directives in Cache-Control response headers. Warning: this may - result in Cloud CDN caching private, per-user (user identifiable) - content.CACHE_ALL_STATIC Automatically cache static content, - including common image formats, media (video and audio), and web - assets (JavaScript and CSS). Requests and responses that are marked - as uncacheable, as well as dynamic content (including HTML), will - not be cached. + performance and increasing load on the origin server. + FORCE_CACHE_ALL Cache all content, ignoring any "private", + "no-store" or "no-cache" directives in Cache-Control response + headers. Warning: this may result in Cloud CDN caching private, + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically + cache static content, including common image formats, media (video + and audio), and web assets (JavaScript and CSS). Requests and + responses that are marked as uncacheable, as well as dynamic content + (including HTML), will not be cached. If no value is provided for cdnPolicy.cacheMode, it defaults to CACHE_ALL_STATIC. @@ -20032,8 +20073,9 @@ class BackendService(proto.Message): Balancers `__ and `external passthrough Network Load Balancers `__. - - failoverPolicy cannot be specified with haPolicy. + failoverPolicy cannot be specified with + haPolicy.failoverPolicy cannot be used by global external + Passthrough Network Load Balancers. This field is a member of `oneof`_ ``_failover_policy``. fingerprint (str): @@ -20079,11 +20121,10 @@ class BackendService(proto.Message): haPolicy requires customers to be responsible for tracking backend endpoint health and electing a leader among the healthy endpoints. Therefore, haPolicy cannot be specified - with healthChecks. - - haPolicy can only be specified for External Passthrough - Network Load Balancers and Internal Passthrough Network Load - Balancers. + with healthChecks. haPolicy can only be specified for + External Passthrough Network Load Balancers and Internal + Passthrough Network Load Balancers.haPolicy cannot be used + by global external Passthrough Network Load Balancers. This field is a member of `oneof`_ ``_ha_policy``. health_checks (MutableSequence[str]): @@ -20159,8 +20200,8 @@ class BackendService(proto.Message): Specifies the load balancer type. A backend service created for one type of load balancer cannot be used with another. For more - information, refer toChoosing - a load balancer. + information, refer to + Backend services product and scheme table. Check the LoadBalancingScheme enum for the list of possible values. @@ -20211,31 +20252,39 @@ class BackendService(proto.Message): If set, the Backend Service responses are expected to contain non-standard HTTP response header field Endpoint-Load-Metrics. The reported metrics to use for computing the weights are specified via thecustomMetrics field. + - WEIGHTED_MAGLEV: Per-endpoint weighted load balancing via + health check reported weights. If set, the backend service must configure + an HTTP-based Health Check, and health check replies are expected to + contain the non-standard HTTP response header fieldX-Load-Balancing-Endpoint-Weight to specify the per-endpoint + weights. If set, load balancing is weighted based on the per-endpoint + weights reported in the last processed health check replies, as long as + every instance either reported a valid weight or had UNAVAILABLE_WEIGHT. + Otherwise, load balancing remains equal-weight. - This field is applicable to either: - - A regional backend service with the service protocol set to HTTP, - HTTPS, HTTP2 or H2C, and load_balancing_scheme set to - INTERNAL_MANAGED. - - A global backend service with the - load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or - EXTERNAL_MANAGED. - - - If sessionAffinity is not configured—that is, if session - affinity remains at the default value of NONE—then the - default value for localityLbPolicy - is ROUND_ROBIN. If session affinity is set to a value other - than NONE, - then the default value for localityLbPolicy isMAGLEV. + This field is applicable to either: - Only ROUND_ROBIN and RING_HASH are supported - when the backend service is referenced by a URL map that is bound to - target gRPC proxy that has validateForProxyless field set to true. + :: - localityLbPolicy cannot be specified with haPolicy. + - A regional backend service with the service protocol set to HTTP, + HTTPS, HTTP2 or H2C, and load_balancing_scheme set to + INTERNAL_MANAGED. + - A global backend service with the + load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or + EXTERNAL_MANAGED. + + If sessionAffinity is not configured—that is, if session + affinity remains at the default value of NONE—then the + default value for localityLbPolicy is ROUND_ROBIN. If + session affinity is set to a value other than NONE, then the + default value for localityLbPolicy isMAGLEV. + + Only ROUND_ROBIN and RING_HASH are supported when the + backend service is referenced by a URL map that is bound to + target gRPC proxy that has validateForProxyless field set to + true. - Check the LocalityLbPolicy enum for the list of possible - values. + localityLbPolicy cannot be specified with haPolicy. Check + the LocalityLbPolicy enum for the list of possible values. This field is a member of `oneof`_ ``_locality_lb_policy``. log_config (google.cloud.compute_v1.types.BackendServiceLogConfig): @@ -20379,13 +20428,12 @@ class BackendService(proto.Message): protocol (str): The protocol this BackendService uses to communicate with backends. - Possible values are HTTP, HTTPS, HTTP2, H2C, - TCP, SSL, UDP or GRPC. depending on the chosen - load balancer or Traffic Director configuration. - Refer to the documentation for the load - balancers or for Traffic Director for more - information. + TCP, SSL, UDP, GRPC, or UNSPECIFIED, depending + on the chosen load balancer or Traffic Director + configuration. + Refer to + Load balancing features for more information. Must be set to GRPC when the backend service is referenced by a URL map that is bound to target @@ -20619,8 +20667,8 @@ class IpAddressSelectionPolicy(proto.Enum): class LoadBalancingScheme(proto.Enum): r"""Specifies the load balancer type. A backend service created for one type of load balancer cannot be used with - another. For more information, refer toChoosing - a load balancer. + another. For more information, refer to + Backend services product and scheme table. Values: UNDEFINED_LOAD_BALANCING_SCHEME (0): @@ -20688,28 +20736,37 @@ class LocalityLbPolicy(proto.Enum): If set, the Backend Service responses are expected to contain non-standard HTTP response header field Endpoint-Load-Metrics. The reported metrics to use for computing the weights are specified via thecustomMetrics field. + - WEIGHTED_MAGLEV: Per-endpoint weighted load balancing via + health check reported weights. If set, the backend service must configure + an HTTP-based Health Check, and health check replies are expected to + contain the non-standard HTTP response header fieldX-Load-Balancing-Endpoint-Weight to specify the per-endpoint + weights. If set, load balancing is weighted based on the per-endpoint + weights reported in the last processed health check replies, as long as + every instance either reported a valid weight or had UNAVAILABLE_WEIGHT. + Otherwise, load balancing remains equal-weight. - This field is applicable to either: - - A regional backend service with the service protocol set to HTTP, - HTTPS, HTTP2 or H2C, and load_balancing_scheme set to - INTERNAL_MANAGED. - - A global backend service with the - load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or - EXTERNAL_MANAGED. + This field is applicable to either: + + :: + - A regional backend service with the service protocol set to HTTP, + HTTPS, HTTP2 or H2C, and load_balancing_scheme set to + INTERNAL_MANAGED. + - A global backend service with the + load_balancing_scheme set to INTERNAL_SELF_MANAGED, INTERNAL_MANAGED, or + EXTERNAL_MANAGED. - If sessionAffinity is not configured—that is, if session - affinity remains at the default value of NONE—then the - default value for localityLbPolicy - is ROUND_ROBIN. If session affinity is set to a value other - than NONE, - then the default value for localityLbPolicy isMAGLEV. + If sessionAffinity is not configured—that is, if session affinity + remains at the default value of NONE—then the default value for + localityLbPolicy is ROUND_ROBIN. If session affinity is set to a + value other than NONE, then the default value for localityLbPolicy + isMAGLEV. - Only ROUND_ROBIN and RING_HASH are supported - when the backend service is referenced by a URL map that is bound to - target gRPC proxy that has validateForProxyless field set to true. + Only ROUND_ROBIN and RING_HASH are supported when the backend + service is referenced by a URL map that is bound to target gRPC + proxy that has validateForProxyless field set to true. - localityLbPolicy cannot be specified with haPolicy. + localityLbPolicy cannot be specified with haPolicy. Values: UNDEFINED_LOCALITY_LB_POLICY (0): @@ -20794,13 +20851,13 @@ class LocalityLbPolicy(proto.Enum): WEIGHTED_ROUND_ROBIN = 5584977 class Protocol(proto.Enum): - r"""The protocol this BackendService uses to communicate - with backends. - - Possible values are HTTP, HTTPS, HTTP2, H2C, TCP, SSL, UDP or - GRPC. depending on the chosen load balancer or Traffic Director - configuration. Refer to the documentation for the load balancers - or for Traffic Director for more information. + r"""The protocol this BackendService uses to communicate with + backends. + Possible values are HTTP, HTTPS, HTTP2, H2C, TCP, SSL, UDP, + GRPC, or UNSPECIFIED, depending on the chosen load balancer or + Traffic Director configuration. + Refer to + Load balancing features for more information. Must be set to GRPC when the backend service is referenced by a URL map that is bound to target gRPC proxy. @@ -21300,16 +21357,16 @@ class BackendServiceCdnPolicy(proto.Message): This field is a member of `oneof`_ ``_cache_key_policy``. cache_mode (str): Specifies the cache setting for all responses from this - backend. The possible values are:USE_ORIGIN_HEADERS Requires - the origin to set valid caching headers to cache content. - Responses without these headers will not be cached at - Google's edge, and will require a full trip to the origin on - every request, potentially impacting performance and - increasing load on the origin server.FORCE_CACHE_ALL Cache + backend. The possible values are: USE_ORIGIN_HEADERS + Requires the origin to set valid caching headers to cache + content. Responses without these headers will not be cached + at Google's edge, and will require a full trip to the origin + on every request, potentially impacting performance and + increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, - per-user (user identifiable) content.CACHE_ALL_STATIC + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as @@ -21438,19 +21495,19 @@ class BackendServiceCdnPolicy(proto.Message): class CacheMode(proto.Enum): r"""Specifies the cache setting for all responses from this backend. The - possible values are:USE_ORIGIN_HEADERS Requires the origin to set + possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting - performance and increasing load on the origin server.FORCE_CACHE_ALL - Cache all content, ignoring any "private", "no-store" or "no-cache" - directives in Cache-Control response headers. Warning: this may - result in Cloud CDN caching private, per-user (user identifiable) - content.CACHE_ALL_STATIC Automatically cache static content, - including common image formats, media (video and audio), and web - assets (JavaScript and CSS). Requests and responses that are marked - as uncacheable, as well as dynamic content (including HTML), will - not be cached. + performance and increasing load on the origin server. + FORCE_CACHE_ALL Cache all content, ignoring any "private", + "no-store" or "no-cache" directives in Cache-Control response + headers. Warning: this may result in Cloud CDN caching private, + per-user (user identifiable) content. CACHE_ALL_STATIC Automatically + cache static content, including common image formats, media (video + and audio), and web assets (JavaScript and CSS). Requests and + responses that are marked as uncacheable, as well as dynamic content + (including HTML), will not be cached. If no value is provided for cdnPolicy.cacheMode, it defaults to CACHE_ALL_STATIC. @@ -22995,6 +23052,51 @@ class BackendServiceTlsSettings(proto.Message): if authenticationMode is not NONE. This field is a member of `oneof`_ ``_authentication_config``. + identity (str): + Assigns the Managed Identity for the BackendService + Workload. + + Use this property to configure the load balancer back-end to + use certificates and roots of trust provisioned by the + Managed Workload Identity system. + + The ``identity`` property is the fully-specified SPIFFE ID + to use in the SVID presented by the Load Balancer Workload. + + The SPIFFE ID must be a resource starting with the + ``trustDomain`` property value, followed by the path to the + Managed Workload Identity. + + Supported SPIFFE ID format: + + :: + + - ///ns//sa/ + + The Trust Domain within the Managed Identity must refer to a + valid Workload Identity Pool. The TrustConfig and + CertificateIssuanceConfig will be inherited from the + Workload Identity Pool. + + Restrictions: + + :: + + - If you set the `identity` property, you cannot manually set + the following fields: + - tlsSettings.sni + - tlsSettings.subjectAltNames + - tlsSettings.authenticationConfig + + When defining a ``identity`` for a RegionBackendServices, + the corresponding Workload Identity Pool must have a ca_pool + configured in the same region. + + The system will set up a + read-onlytlsSettings.authenticationConfig for the Managed + Identity. + + This field is a member of `oneof`_ ``_identity``. sni (str): Server Name Indication - see RFC3546 section 3.1. If set, the load balancer sends this string as the SNI hostname in @@ -23026,6 +23128,11 @@ class BackendServiceTlsSettings(proto.Message): number=408053481, optional=True, ) + identity: str = proto.Field( + proto.STRING, + number=401109182, + optional=True, + ) sni: str = proto.Field( proto.STRING, number=114030, @@ -26232,6 +26339,12 @@ class Type(proto.Enum): 16TB of memory. NETWORK_OPTIMIZED_C4N (147027572): CUD bucket for C4N (dual Diorite) machines. + NETWORK_OPTIMIZED_U4C (147044859): + CUD bucket for NETWORK_OPTIMIZED_U4C machines. + NETWORK_OPTIMIZED_U4P (147044872): + CUD bucket for NETWORK_OPTIMIZED_U4P machines. + NETWORK_OPTIMIZED_U4S (147044875): + CUD bucket for NETWORK_OPTIMIZED_U4S machines. STORAGE_OPTIMIZED_Z3 (316796085): No description available. TYPE_UNSPECIFIED (437714322): @@ -26281,6 +26394,9 @@ class Type(proto.Enum): MEMORY_OPTIMIZED_X4_960_12T = 424752410 MEMORY_OPTIMIZED_X4_960_16T = 424752534 NETWORK_OPTIMIZED_C4N = 147027572 + NETWORK_OPTIMIZED_U4C = 147044859 + NETWORK_OPTIMIZED_U4P = 147044872 + NETWORK_OPTIMIZED_U4S = 147044875 STORAGE_OPTIMIZED_Z3 = 316796085 TYPE_UNSPECIFIED = 437714322 @@ -39685,6 +39801,9 @@ class ForwardingRule(proto.Message): - global/addresses/address-name - address-name + The IP address can only be set at creation. Once set, it + cannot be updated. + The forwarding rule's target or backendService, and in most cases, also the loadBalancingScheme, determine the type of IP address that you can use. For detailed information, see @@ -39694,6 +39813,13 @@ class ForwardingRule(proto.Message): When reading an IPAddress, the API always returns the IP address number. + When creating a global external Passthrough Network Load + Balancer forwarding rule (a parent forwarding rule), you + must use theIPAddresses field, but the Google Cloud + generated child forwarding rules set the IPAddress field + instead. Refer to theavailabilityGroup field for further + details. + This field is a member of `oneof`_ ``_I_p_address``. I_p_protocol (str): The IP protocol to which this rule applies. @@ -39750,10 +39876,18 @@ class ForwardingRule(proto.Message): to this ForwardingRule. backend_service (str): Identifies the backend service to which the - forwarding rule sends traffic. Required for - internal and external passthrough Network Load - Balancers; must be omitted for all other load - balancer types. + forwarding rule sends traffic. + It is a required field for the following load + balancers: + + - Internal passthrough Network Load Balancers + - Backend service-based regional external + passthrough Network Load Balancers + - Global external passthrough Network Load + Balancers + + It cannot be set by other load balancer types + and protocol forwarding rules. This field is a member of `oneof`_ ``_backend_service``. base_forwarding_rule (str): @@ -39893,8 +40027,8 @@ class ForwardingRule(proto.Message): load_balancing_scheme (str): Specifies the forwarding rule type. - For more information about forwarding rules, - refer to Forwarding rule concepts. + For more information, refer to + Forwarding rule product and scheme table. Check the LoadBalancingScheme enum for the list of possible values. @@ -39937,6 +40071,16 @@ class ForwardingRule(proto.Message): 1-20 characters string with lowercase letters and numbers and must start with a letter. + For global external Passthrough Network Load Balancer + forwarding rules, the forwarding rule name must be 1-43 + characters long. For each global external Passthrough + Network Load Balancer forwarding rule (a parent forwarding + rule) that you create, Google Cloud generates two + output-only child forwarding rules that are named by + concatenating the parent forwarding rule name with the + ``-ag0`` and ``-ag1`` suffixes, respectively. Refer to + theavailabilityGroup field for further details. + This field is a member of `oneof`_ ``_name``. network (str): This field is not used for global external @@ -40000,8 +40144,9 @@ class ForwardingRule(proto.Message): port specifications for details. For external forwarding rules, two or more forwarding rules - cannot use the same [IPAddress, IPProtocol] pair, and cannot - have overlappingportRanges. + cannot use the same [IPAddress, IPProtocol] pair (specified + inIPAddress, IPAddresses, IPProtocol fields) if they have + overlapping portRanges. For internal forwarding rules within the same VPC network, two or more forwarding rules cannot use the same [IPAddress, @@ -40029,8 +40174,9 @@ class ForwardingRule(proto.Message): commas. The ports can be contiguous or discontiguous. For external forwarding rules, two or more forwarding rules - cannot use the same [IPAddress, IPProtocol] pair if they - share at least one port number. + cannot use the same [IPAddress, IPProtocol] pair (specified + inIPAddress, IPAddresses, IPProtocol fields) if they share + at least one port number. For internal forwarding rules within the same VPC network, two or more forwarding rules cannot use the same [IPAddress, @@ -40136,6 +40282,16 @@ class ForwardingRule(proto.Message): - For Private Service Connect forwarding rules that forward traffic to managed services, the target must be a service attachment. The target is not mutable once set as a service attachment. + The following load balancers cannot set the target field + (they should set the backendService field instead): + + :: + + - Internal passthrough Network Load Balancers + - Backend service-based regional external passthrough Network Load + Balancers + - Global external passthrough Network Load Balancers + This field is a member of `oneof`_ ``_target``. """ @@ -40239,8 +40395,8 @@ class IpVersion(proto.Enum): class LoadBalancingScheme(proto.Enum): r"""Specifies the forwarding rule type. - For more information about forwarding rules, refer to Forwarding - rule concepts. + For more information, refer to + Forwarding rule product and scheme table. Values: UNDEFINED_LOAD_BALANCING_SCHEME (0): @@ -40941,6 +41097,21 @@ class FutureReservation(proto.Message): reservation_name or a name_prefix. This field is a member of `oneof`_ ``_reservation_name``. + resource_metadata (google.cloud.compute_v1.types.ResourceMetadata): + Output only. Contains standard resource metadata for an + FutureReservation resource. It is populated for each + instance of the FutureReservation resource, and includes the + api_version the instance was retrieved through, and its + canonical resource_type name. + + This field is a member of `oneof`_ ``_resource_metadata``. + resource_name (str): + Name of the resource intended to be + delivered. Name should conform to RFC1035. This + will be the name of storage pool or Exapool for + persistent disk FRs. + + This field is a member of `oneof`_ ``_resource_name``. scheduling_type (str): Maintenance information for this reservation Check the SchedulingType enum for the list of @@ -40978,6 +41149,11 @@ class FutureReservation(proto.Message): Output only. [Output only] Status of the Future Reservation This field is a member of `oneof`_ ``_status``. + storage_pool_properties (google.cloud.compute_v1.types.FutureReservationStoragePoolProperties): + Storage pool details for the future + reservation. + + This field is a member of `oneof`_ ``_storage_pool_properties``. time_window (google.cloud.compute_v1.types.FutureReservationTimeWindow): Time window for this Future Reservation. @@ -41189,6 +41365,17 @@ class SchedulingType(proto.Enum): number=277311262, optional=True, ) + resource_metadata: "ResourceMetadata" = proto.Field( + proto.MESSAGE, + number=99063872, + optional=True, + message="ResourceMetadata", + ) + resource_name: str = proto.Field( + proto.STRING, + number=442550300, + optional=True, + ) scheduling_type: str = proto.Field( proto.STRING, number=199835397, @@ -41227,6 +41414,12 @@ class SchedulingType(proto.Enum): optional=True, message="FutureReservationStatus", ) + storage_pool_properties: "FutureReservationStoragePoolProperties" = proto.Field( + proto.MESSAGE, + number=71410546, + optional=True, + message="FutureReservationStoragePoolProperties", + ) time_window: "FutureReservationTimeWindow" = proto.Field( proto.MESSAGE, number=422983074, @@ -41413,6 +41606,11 @@ class FutureReservationStatus(proto.Message): auto_created_reservations (MutableSequence[str]): Output only. Fully qualified urls of the automatically created reservations at start_time. + exapool_provisioned_capacity_gb (google.cloud.compute_v1.types.StoragePoolExapoolProvisionedCapacityGb): + Output only. Exapool provisioned capacities + for each SKU type. + + This field is a member of `oneof`_ ``_exapool_provisioned_capacity_gb``. existing_matching_usage_info (google.cloud.compute_v1.types.FutureReservationStatusExistingMatchingUsageInfo): Output only. [Output Only] Represents the existing matching usage for the future reservation. @@ -41453,6 +41651,11 @@ class FutureReservationStatus(proto.Message): specific_sku_properties (google.cloud.compute_v1.types.FutureReservationStatusSpecificSKUProperties): This field is a member of `oneof`_ ``_specific_sku_properties``. + storage_pool_provisioned_capacity (google.cloud.compute_v1.types.FutureReservationStoragePoolProvisionedCapacity): + Output only. Storage pool provisioned + capacities for each SKU type. + + This field is a member of `oneof`_ ``_storage_pool_provisioned_capacity``. """ class AmendmentStatus(proto.Enum): @@ -41557,6 +41760,14 @@ class ProcurementStatus(proto.Enum): proto.STRING, number=140217006, ) + exapool_provisioned_capacity_gb: "StoragePoolExapoolProvisionedCapacityGb" = ( + proto.Field( + proto.MESSAGE, + number=345174240, + optional=True, + message="StoragePoolExapoolProvisionedCapacityGb", + ) + ) existing_matching_usage_info: "FutureReservationStatusExistingMatchingUsageInfo" = ( proto.Field( proto.MESSAGE, @@ -41594,6 +41805,12 @@ class ProcurementStatus(proto.Enum): message="FutureReservationStatusSpecificSKUProperties", ) ) + storage_pool_provisioned_capacity: "FutureReservationStoragePoolProvisionedCapacity" = proto.Field( + proto.MESSAGE, + number=135892964, + optional=True, + message="FutureReservationStoragePoolProvisionedCapacity", + ) class FutureReservationStatusExistingMatchingUsageInfo(proto.Message): @@ -41834,6 +42051,87 @@ class FutureReservationStatusSpecificSKUProperties(proto.Message): ) +class FutureReservationStoragePoolProperties(proto.Message): + r"""Storage pool properties for the future reservation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + requested_exapool_provisioned_capacity_gb (google.cloud.compute_v1.types.StoragePoolExapoolProvisionedCapacityGb): + Requested exapool provisioned capacity in + GiB. + + This field is a member of `oneof`_ ``_requested_exapool_provisioned_capacity_gb``. + requested_storage_pool_provisioned_capacity (google.cloud.compute_v1.types.FutureReservationStoragePoolProvisionedCapacity): + Requested storage pool provisioned capacity. + + This field is a member of `oneof`_ ``_requested_storage_pool_provisioned_capacity``. + storage_pool_type (str): + Type of the storage pool. + + This field is a member of `oneof`_ ``_storage_pool_type``. + """ + + requested_exapool_provisioned_capacity_gb: "StoragePoolExapoolProvisionedCapacityGb" = proto.Field( + proto.MESSAGE, + number=174982159, + optional=True, + message="StoragePoolExapoolProvisionedCapacityGb", + ) + requested_storage_pool_provisioned_capacity: "FutureReservationStoragePoolProvisionedCapacity" = proto.Field( + proto.MESSAGE, + number=326931283, + optional=True, + message="FutureReservationStoragePoolProvisionedCapacity", + ) + storage_pool_type: str = proto.Field( + proto.STRING, + number=285999289, + optional=True, + ) + + +class FutureReservationStoragePoolProvisionedCapacity(proto.Message): + r"""Storage pool provisioned capacities for each SKU type. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pool_provisioned_capacity_gb (int): + Size of the storage pool in GiB. + + This field is a member of `oneof`_ ``_pool_provisioned_capacity_gb``. + pool_provisioned_iops (int): + Provisioned IOPS of the storage pool. Only + relevant if the storage pool type is + hyperdisk-balanced. + + This field is a member of `oneof`_ ``_pool_provisioned_iops``. + pool_provisioned_throughput (int): + Provisioned throughput of the storage pool in + MiB/s. Only relevant if the storage pool type is + hyperdisk-balanced or hyperdisk-throughput. + + This field is a member of `oneof`_ ``_pool_provisioned_throughput``. + """ + + pool_provisioned_capacity_gb: int = proto.Field( + proto.INT64, + number=478537682, + optional=True, + ) + pool_provisioned_iops: int = proto.Field( + proto.INT64, + number=112092311, + optional=True, + ) + pool_provisioned_throughput: int = proto.Field( + proto.INT64, + number=169215640, + optional=True, + ) + + class FutureReservationTimeWindow(proto.Message): r""" @@ -52797,11 +53095,6 @@ class HealthStatus(proto.Message): class HealthState(proto.Enum): r"""Health state of the IPv4 address of the instance. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - HEALTHY - UNHEALTHY Values: UNDEFINED_HEALTH_STATE (0): @@ -52976,26 +53269,19 @@ class HealthStatusForNetworkEndpoint(proto.Message): class HealthState(proto.Enum): r"""Health state of the network endpoint determined based on the health checks configured. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - DRAINING - HEALTHY - UNHEALTHY - UNKNOWN Values: UNDEFINED_HEALTH_STATE (0): A value indicating that the enum field is not set. DRAINING (480455402): - No description available. + Endpoint is being drained. HEALTHY (439801213): - No description available. + Endpoint is healthy. UNHEALTHY (462118084): - No description available. + Endpoint is unhealthy. UNKNOWN (433141802): - No description available. + Health status of the endpoint is unknown. """ UNDEFINED_HEALTH_STATE = 0 @@ -60955,6 +61241,7 @@ class Instance(proto.Message): For example: zones/us-central1-f/machineTypes/custom-4-5120 + For a full list of restrictions, read theSpecifications for custom machine types. @@ -61716,6 +62003,12 @@ class InstanceFlexibilityPolicyInstanceSelection(proto.Message): created from these properties. This field only accepts a machine type names, for example ``n2-standard-4`` and not URLs or partial URLs. + min_cpu_platform (str): + Name of the minimum CPU platform to be used + by this instance selection. e.g. 'Intel Ice + Lake'. + + This field is a member of `oneof`_ ``_min_cpu_platform``. rank (int): Rank when prioritizing the shape flexibilities. The instance selections with rank @@ -61735,6 +62028,11 @@ class InstanceFlexibilityPolicyInstanceSelection(proto.Message): proto.STRING, number=79720065, ) + min_cpu_platform: str = proto.Field( + proto.STRING, + number=242912759, + optional=True, + ) rank: int = proto.Field( proto.INT64, number=3492908, @@ -62981,17 +63279,16 @@ class DefaultActionOnFailure(proto.Enum): repairing VMs in a MIG. - DO_NOTHING: MIG does not repair a failed VM. - Additional supported values which may be not listed in the enum - directly due to technical reasons: DO_NOTHING REPAIR - Values: UNDEFINED_DEFAULT_ACTION_ON_FAILURE (0): A value indicating that the enum field is not set. DO_NOTHING (451307513): - No description available. + MIG does not repair a failed VM. REPAIR (266277773): - No description available. + (default): MIG automatically repairs a failed + VM by recreating it. For more information, see + About repairing VMs in a MIG. """ UNDEFINED_DEFAULT_ACTION_ON_FAILURE = 0 @@ -100569,9 +100866,7 @@ class CurrentAction(proto.Enum): class InstanceStatus(proto.Enum): r"""Output only. [Output Only] The status of the instance. This field is - empty when the instance does not exist. Additional supported values - which may be not listed in the enum directly due to technical - reasons: STOPPING SUSPENDING + empty when the instance does not exist. Values: UNDEFINED_INSTANCE_STATUS (0): @@ -100600,11 +100895,12 @@ class InstanceStatus(proto.Enum): STOPPED (444276141): The instance has stopped successfully. STOPPING (350791796): - No description available. + The instance is currently stopping (either + being deleted or killed). SUSPENDED (51223995): The instance has suspended. SUSPENDING (514206246): - No description available. + The instance is suspending. TERMINATED (250018339): The instance has stopped (either by explicit action or underlying failure). @@ -105327,8 +105623,7 @@ class NetworkProfileNetworkFeatures(proto.Message): """ class AddressPurposes(proto.Enum): - r"""Additional supported values which may be not listed in the enum - directly due to technical reasons: PRIVATE_SERVICE_CONNECT + r""" Values: UNDEFINED_ADDRESS_PURPOSES (0): @@ -105354,7 +105649,10 @@ class AddressPurposes(proto.Enum): External IP automatically reserved for Cloud NAT. PRIVATE_SERVICE_CONNECT (48134724): - No description available. + A private network IP address that can be used + to configure Private Service Connect. This + purpose can be specified only forGLOBAL + addresses of Type INTERNAL SERVERLESS (270492508): A regional internal IP address range reserved for Serverless. @@ -106535,9 +106833,7 @@ class BgpBestPathSelectionMode(proto.Enum): class BgpInterRegionCost(proto.Enum): r"""Allows to define a preferred approach for handling inter-region cost in the selection process when using the STANDARD BGP best path - selection algorithm. Can be DEFAULT orADD_COST_TO_MED. Additional - supported values which may be not listed in the enum directly due to - technical reasons: ADD_COST_TO_MED DEFAULT + selection algorithm. Can be DEFAULT orADD_COST_TO_MED. Values: UNDEFINED_BGP_INTER_REGION_COST (0): @@ -118726,7 +119022,7 @@ class QuotaStatusWarning(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. @@ -119170,6 +119466,60 @@ class Reference(proto.Message): ) +class RegexRewrite(proto.Message): + r"""The spec for modifying the path using a regular expression. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + path_pattern (str): + Required. The regular expression used to match against the + URL path. It uses RE2 syntax with the following constraints: + + :: + + - Any single character operators + - Groups are allowed to have only submatch operator inside + - Groups are allowed only without any char repetition, e.g. + .* + - Any char repetition, e.g. .*, is + only allowed to be used in a single regex together with: + + + - Empty string operators + - Other repetitions + - Ranges + - Repetitions of ranges + + + - Ranges are only allowed to have: + + + - Character range + - Digits range + - Symbols listed in characters allowed for ranges + + This field is a member of `oneof`_ ``_path_pattern``. + path_substitution (str): + Required. Required when path pattern is + specified. Used to rewrite matching parts of the + path. + + This field is a member of `oneof`_ ``_path_substitution``. + """ + + path_pattern: str = proto.Field( + proto.STRING, + number=316473718, + optional=True, + ) + path_substitution: str = proto.Field( + proto.STRING, + number=268020951, + optional=True, + ) + + class Region(proto.Message): r"""Represents a Region resource. @@ -122549,6 +122899,14 @@ class Reservation(proto.Message): with Google Cloud managed services. This field is a member of `oneof`_ ``_reservation_sharing_policy``. + resource_metadata (google.cloud.compute_v1.types.ResourceMetadata): + Output only. [Output Only] Contains standard resource + metadata for an Allocation resource. It is populated for + each instance of the Allocation resource, and includes the + api_version the instance was retrieved through, and its + canonical resource_type name. + + This field is a member of `oneof`_ ``_resource_metadata``. resource_policies (MutableMapping[str, str]): Resource policies to be added to this reservation. The key is defined by user, and the @@ -122862,6 +123220,12 @@ class Status(proto.Enum): optional=True, message="AllocationReservationSharingPolicy", ) + resource_metadata: "ResourceMetadata" = proto.Field( + proto.MESSAGE, + number=99063872, + optional=True, + message="ResourceMetadata", + ) resource_policies: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -125298,6 +125662,40 @@ class ResourceGroupReference(proto.Message): ) +class ResourceMetadata(proto.Message): + r"""Standardized resource metadata common to all compute + resources. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + api_version (str): + The version of the API interface that this resource was + retrieved through. For example, ``"2025-01-01"`` or + ``"2025-01-01-preview"``. + + This field is a member of `oneof`_ ``_api_version``. + resource_type (str): + The canonical resource type name in the format of a resource + type as defined by `AIP-123 `__. + For example, ``"compute.googleapis.com/Instance"``. + + This field is a member of `oneof`_ ``_resource_type``. + """ + + api_version: str = proto.Field( + proto.STRING, + number=476021683, + optional=True, + ) + resource_type: str = proto.Field( + proto.STRING, + number=442752203, + optional=True, + ) + + class ResourcePoliciesScopedList(proto.Message): r""" @@ -135139,13 +135537,16 @@ class SecurityPolicyRuleRateLimitOptions(proto.Message): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, - the key type defaults to ALL. For "fairshare" action, this - value is limited to ALL i.e. a single rate limit threshold - is enforced for all the requests matching the rule. Check - the EnforceOnKey enum for the list of possible values. + For "fairshare" action, this value is limited to ALL i.e. a + single rate limit threshold is enforced for all the requests + matching the rule. Check the EnforceOnKey enum for the list + of possible values. This field is a member of `oneof`_ ``_enforce_on_key``. enforce_on_key_configs (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRuleRateLimitOptionsEnforceOnKeyConfig]): @@ -135226,12 +135627,15 @@ class EnforceOnKey(proto.Enum): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key - type defaults to ALL. For "fairshare" action, this value is - limited to ALL i.e. a single rate limit threshold is enforced for - all the requests matching the rule. + For "fairshare" action, this value is limited to ALL i.e. a single + rate limit threshold is enforced for all the requests matching the + rule. Values: UNDEFINED_ENFORCE_ON_KEY (0): @@ -135239,6 +135643,8 @@ class EnforceOnKey(proto.Enum): set. ALL (64897): No description available. + ASN (65116): + No description available. HTTP_COOKIE (494981627): No description available. HTTP_HEADER (91597348): @@ -135263,6 +135669,7 @@ class EnforceOnKey(proto.Enum): UNDEFINED_ENFORCE_ON_KEY = 0 ALL = 64897 + ASN = 65116 HTTP_COOKIE = 494981627 HTTP_HEADER = 91597348 HTTP_PATH = 311503228 @@ -135378,11 +135785,14 @@ class SecurityPolicyRuleRateLimitOptionsEnforceOnKeyConfig(proto.Message): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, - the key type defaults to ALL. Check the EnforceOnKeyType - enum for the list of possible values. + Check the EnforceOnKeyType enum for the list of possible + values. This field is a member of `oneof`_ ``_enforce_on_key_type``. """ @@ -135426,10 +135836,11 @@ class EnforceOnKeyType(proto.Enum): which is resolved based on "userIpRequestHeaders" configured with the security policy. If there is no "userIpRequestHeaders" configuration or an IP address cannot be resolved from it, the key type defaults toIP. - - - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the client - connects using HTTPS, HTTP/2 or HTTP/3. If not available, the key - type defaults to ALL. + - ASN: The autonomous system number of the originating + client. If not available, the key type defaults toALL. + - TLS_JA4_FINGERPRINT: JA4 TLS/SSL fingerprint if the + client connects using HTTPS, HTTP/2 or HTTP/3. If not available, the + key type defaults to ALL. Values: UNDEFINED_ENFORCE_ON_KEY_TYPE (0): @@ -135437,6 +135848,8 @@ class EnforceOnKeyType(proto.Enum): set. ALL (64897): No description available. + ASN (65116): + No description available. HTTP_COOKIE (494981627): No description available. HTTP_HEADER (91597348): @@ -135461,6 +135874,7 @@ class EnforceOnKeyType(proto.Enum): UNDEFINED_ENFORCE_ON_KEY_TYPE = 0 ALL = 64897 + ASN = 65116 HTTP_COOKIE = 494981627 HTTP_HEADER = 91597348 HTTP_PATH = 311503228 @@ -150515,7 +150929,7 @@ class TargetPool(proto.Message): The server-defined URL for the resource. This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool, and its failoverRatio - field is properly set to a value between [0, 1].backupPool + field is properly set to a value between [0, 1]. backupPool and failoverRatio together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or belowfailoverRatio, @@ -157758,6 +158172,13 @@ class UrlRewrite(proto.Message): be specified. This field is a member of `oneof`_ ``_path_template_rewrite``. + regex_rewrite (google.cloud.compute_v1.types.RegexRewrite): + The regex rewrite to be applied to the URL. + Only one ofpathPrefixRewrite, + pathTemplateRewrite, orregexRewrite may be + specified. + + This field is a member of `oneof`_ ``_regex_rewrite``. """ host_rewrite: str = proto.Field( @@ -157775,6 +158196,12 @@ class UrlRewrite(proto.Message): number=423409569, optional=True, ) + regex_rewrite: "RegexRewrite" = proto.Field( + proto.MESSAGE, + number=380801428, + optional=True, + message="RegexRewrite", + ) class UsableSubnetwork(proto.Message): @@ -160650,7 +161077,7 @@ class Warning(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. @@ -160824,7 +161251,7 @@ class Warnings(proto.Message): [Output Only] Metadata about this warning in key: value format. For example: - "data": [ { "key": "scope", "value": "zones/us-east1-d" } + "data": [ { "key": "scope", "value": "zones/us-east1-d" }] message (str): [Output Only] A human-readable description of the warning code. diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py index 5603dd68d905..5e288d0e6412 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py @@ -8229,6 +8229,7 @@ def test_insert_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { @@ -8945,6 +8946,7 @@ def test_patch_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { @@ -10355,6 +10357,7 @@ def test_update_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_future_reservations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_future_reservations.py index 6aa29740e9ef..af6eea96b905 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_future_reservations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_future_reservations.py @@ -4381,6 +4381,7 @@ def test_get_rest_call_success(request_type): planning_status="planning_status_value", reservation_mode="reservation_mode_value", reservation_name="reservation_name_value", + resource_name="resource_name_value", scheduling_type="scheduling_type_value", self_link="self_link_value", self_link_with_id="self_link_with_id_value", @@ -4419,6 +4420,7 @@ def test_get_rest_call_success(request_type): assert response.planning_status == "planning_status_value" assert response.reservation_mode == "reservation_mode_value" assert response.reservation_name == "reservation_name_value" + assert response.resource_name == "resource_name_value" assert response.scheduling_type == "scheduling_type_value" assert response.self_link == "self_link_value" assert response.self_link_with_id == "self_link_with_id_value" @@ -4563,6 +4565,11 @@ def test_insert_rest_call_success(request_type): "planning_status": "planning_status_value", "reservation_mode": "reservation_mode_value", "reservation_name": "reservation_name_value", + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, + "resource_name": "resource_name_value", "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", @@ -4590,6 +4597,11 @@ def test_insert_rest_call_success(request_type): "auto_created_reservations_value1", "auto_created_reservations_value2", ], + "exapool_provisioned_capacity_gb": { + "capacity_optimized": 1922, + "read_optimized": 1488, + "write_optimized": 1631, + }, "existing_matching_usage_info": { "count": 553, "timestamp": "timestamp_value", @@ -4616,6 +4628,16 @@ def test_insert_rest_call_success(request_type): "specific_sku_properties": { "source_instance_template_id": "source_instance_template_id_value" }, + "storage_pool_provisioned_capacity": { + "pool_provisioned_capacity_gb": 2976, + "pool_provisioned_iops": 2277, + "pool_provisioned_throughput": 2948, + }, + }, + "storage_pool_properties": { + "requested_exapool_provisioned_capacity_gb": {}, + "requested_storage_pool_provisioned_capacity": {}, + "storage_pool_type": "storage_pool_type_value", }, "time_window": {}, "zone": "zone_value", @@ -5049,6 +5071,11 @@ def test_update_rest_call_success(request_type): "planning_status": "planning_status_value", "reservation_mode": "reservation_mode_value", "reservation_name": "reservation_name_value", + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, + "resource_name": "resource_name_value", "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", @@ -5076,6 +5103,11 @@ def test_update_rest_call_success(request_type): "auto_created_reservations_value1", "auto_created_reservations_value2", ], + "exapool_provisioned_capacity_gb": { + "capacity_optimized": 1922, + "read_optimized": 1488, + "write_optimized": 1631, + }, "existing_matching_usage_info": { "count": 553, "timestamp": "timestamp_value", @@ -5102,6 +5134,16 @@ def test_update_rest_call_success(request_type): "specific_sku_properties": { "source_instance_template_id": "source_instance_template_id_value" }, + "storage_pool_provisioned_capacity": { + "pool_provisioned_capacity_gb": 2976, + "pool_provisioned_iops": 2277, + "pool_provisioned_throughput": 2948, + }, + }, + "storage_pool_properties": { + "requested_exapool_provisioned_capacity_gb": {}, + "requested_storage_pool_provisioned_capacity": {}, + "storage_pool_type": "storage_pool_type_value", }, "time_window": {}, "zone": "zone_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py index 2581929d0abb..976bbb6452f9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py @@ -5997,6 +5997,7 @@ def test_insert_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { @@ -6724,6 +6725,7 @@ def test_patch_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { @@ -7901,6 +7903,7 @@ def test_update_rest_call_success(request_type): "timeout_sec": 1185, "tls_settings": { "authentication_config": "authentication_config_value", + "identity": "identity_value", "sni": "sni_value", "subject_alt_names": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py index 9cb35b5744b1..63c112ce966c 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py @@ -3298,6 +3298,10 @@ def test_insert_rest_call_success(request_type): "reservation_sharing_policy": { "service_share_type": "service_share_type_value" }, + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, "resource_policies": {}, "resource_status": { "health_info": { @@ -3817,6 +3821,10 @@ def test_update_rest_call_success(request_type): "reservation_sharing_policy": { "service_share_type": "service_share_type_value" }, + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, "resource_policies": {}, "resource_status": { "health_info": { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py index c20d2c29e2c1..d87bf3099d11 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_url_maps.py @@ -4056,6 +4056,10 @@ def test_insert_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -4643,6 +4647,10 @@ def test_patch_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -5100,6 +5108,10 @@ def test_update_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -5561,6 +5573,10 @@ def test_validate_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py index cda399d2bce6..57aa2c440436 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py @@ -5470,6 +5470,10 @@ def test_insert_rest_call_success(request_type): "reservation_sharing_policy": { "service_share_type": "service_share_type_value" }, + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, "resource_policies": {}, "resource_status": { "health_info": { @@ -6901,6 +6905,10 @@ def test_update_rest_call_success(request_type): "reservation_sharing_policy": { "service_share_type": "service_share_type_value" }, + "resource_metadata": { + "api_version": "api_version_value", + "resource_type": "resource_type_value", + }, "resource_policies": {}, "resource_status": { "health_info": { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py index 62acf50a02be..308a548f0cfc 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_url_maps.py @@ -4914,6 +4914,10 @@ def test_insert_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -5741,6 +5745,10 @@ def test_patch_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6400,6 +6408,10 @@ def test_update_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6859,6 +6871,10 @@ def test_validate_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { diff --git a/packages/google-cloud-config/google/cloud/config_v1/types/config.py b/packages/google-cloud-config/google/cloud/config_v1/types/config.py index acddf9ecfa38..995bb75937f3 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/types/config.py +++ b/packages/google-cloud-config/google/cloud/config_v1/types/config.py @@ -197,9 +197,8 @@ class Deployment(proto.Message): Output only. Location of Terraform error logs in Google Cloud Storage. Format: ``gs://{bucket}/{object}``. artifacts_gcs_bucket (str): - Optional. User-defined location of Cloud Build logs and - artifacts in Google Cloud Storage. Format: - ``gs://{bucket}/{folder}`` + User-defined location of Cloud Build logs and artifacts in + Google Cloud Storage. Format: ``gs://{bucket}/{folder}`` A default bucket will be bootstrapped if the field is not set or empty. Default bucket format: @@ -233,8 +232,8 @@ class Deployment(proto.Message): This field is a member of `oneof`_ ``_import_existing_resources``. worker_pool (str): - Optional. The user-specified Cloud Build worker pool - resource in which the Cloud Build job will execute. Format: + The user-specified Cloud Build worker pool resource in which + the Cloud Build job will execute. Format: ``projects/{project}/locations/{location}/workerPools/{workerPoolId}``. If this field is unspecified, the default Cloud Build worker pool will be used. @@ -244,8 +243,8 @@ class Deployment(proto.Message): Output only. Current lock state of the deployment. tf_version_constraint (str): - Optional. The user-specified Terraform - version constraint. Example: "=1.3.10". + The user-specified Terraform version + constraint. Example: "=1.3.10". This field is a member of `oneof`_ ``_tf_version_constraint``. tf_version (str): @@ -1691,18 +1690,18 @@ class GitSource(proto.Message): Attributes: repo (str): - Optional. Repository URL. + Repository URL. Example: 'https://github.com/kubernetes/examples.git' This field is a member of `oneof`_ ``_repo``. directory (str): - Optional. Subdirectory inside the repository. + Subdirectory inside the repository. Example: 'staging/my-package' This field is a member of `oneof`_ ``_directory``. ref (str): - Optional. Git reference (e.g. branch or tag). + Git reference (e.g. branch or tag). This field is a member of `oneof`_ ``_ref``. """ @@ -1741,6 +1740,9 @@ class DeploymentOperationMetadata(proto.Message): logs (str): Output only. Location of Deployment operations logs in ``gs://{bucket}/{object}`` format. + apply_results_available (bool): + Output only. Indicating if early apply + results are available. """ class DeploymentStep(proto.Enum): @@ -1813,6 +1815,10 @@ class DeploymentStep(proto.Enum): proto.STRING, number=4, ) + apply_results_available: bool = proto.Field( + proto.BOOL, + number=5, + ) class Resource(proto.Message): @@ -2307,12 +2313,11 @@ class Preview(proto.Message): state (google.cloud.config_v1.types.Preview.State): Output only. Current state of the preview. deployment (str): - Optional. Optional deployment reference. If - specified, the preview will be performed using - the provided deployment's current state and use - any relevant fields from the deployment unless - explicitly specified in the preview create - request. + Optional. Deployment reference. If specified, + the preview will be performed using the provided + deployment's current state and use any relevant + fields from the deployment unless explicitly + specified in the preview create request. preview_mode (google.cloud.config_v1.types.Preview.PreviewMode): Optional. Current mode of preview. service_account (str): @@ -2320,11 +2325,11 @@ class Preview(proto.Message): be used when previewing resources. Format: ``projects/{projectID}/serviceAccounts/{serviceAccount}`` artifacts_gcs_bucket (str): - Optional. User-defined location of Cloud Build logs, - artifacts, and in Google Cloud Storage. Format: - ``gs://{bucket}/{folder}`` A default bucket will be - bootstrapped if the field is not set or empty Default Bucket - Format: ``gs://--blueprint-config`` + User-defined location of Cloud Build logs, artifacts, and in + Google Cloud Storage. Format: ``gs://{bucket}/{folder}`` A + default bucket will be bootstrapped if the field is not set + or empty Default Bucket Format: + ``gs://--blueprint-config`` Constraints: - The bucket needs to be in the same project as the @@ -2336,8 +2341,8 @@ class Preview(proto.Message): This field is a member of `oneof`_ ``_artifacts_gcs_bucket``. worker_pool (str): - Optional. The user-specified Worker Pool resource in which - the Cloud Build job will execute. Format + The user-specified Worker Pool resource in which the Cloud + Build job will execute. Format projects/{project}/locations/{location}/workerPools/{workerPoolId} If this field is unspecified, the default Cloud Build worker pool will be used. If omitted and deployment resource ref @@ -2372,8 +2377,8 @@ class Preview(proto.Message): set on the preview. It is in the format of "Major.Minor.Patch", for example, "1.3.10". tf_version_constraint (str): - Optional. The user-specified Terraform - version constraint. Example: "=1.3.10". + The user-specified Terraform version + constraint. Example: "=1.3.10". This field is a member of `oneof`_ ``_tf_version_constraint``. annotations (MutableMapping[str, str]): diff --git a/packages/google-cloud-container/google/cloud/container/__init__.py b/packages/google-cloud-container/google/cloud/container/__init__.py index 3c217158837a..1da85657d524 100644 --- a/packages/google-cloud-container/google/cloud/container/__init__.py +++ b/packages/google-cloud-container/google/cloud/container/__init__.py @@ -56,6 +56,7 @@ ClusterPolicyConfig, ClusterUpdate, ClusterUpgradeInfo, + CompleteControlPlaneUpgradeRequest, CompleteIPRotationRequest, CompleteNodePoolUpgradeRequest, CompliancePostureConfig, @@ -68,6 +69,7 @@ CreateClusterRequest, CreateNodePoolRequest, CustomImageConfig, + CustomImageInfo, DailyMaintenanceWindow, DatabaseEncryption, DatapathProvider, @@ -78,6 +80,7 @@ DeleteNodePoolRequest, DesiredAdditionalIPRangesConfig, DesiredEnterpriseConfig, + DiskIoScheduler, DisruptionBudget, DisruptionEvent, DnsCacheConfig, @@ -196,6 +199,8 @@ ResourceManagerTags, ResourceUsageExportConfig, RollbackNodePoolUpgradeRequest, + RollbackSafeUpgrade, + RollbackSafeUpgradeStatus, SandboxConfig, ScheduleUpgradeConfig, SecondaryBootDisk, @@ -283,6 +288,7 @@ "ClusterPolicyConfig", "ClusterUpdate", "ClusterUpgradeInfo", + "CompleteControlPlaneUpgradeRequest", "CompleteIPRotationRequest", "CompleteNodePoolUpgradeRequest", "CompliancePostureConfig", @@ -295,6 +301,7 @@ "CreateClusterRequest", "CreateNodePoolRequest", "CustomImageConfig", + "CustomImageInfo", "DailyMaintenanceWindow", "DatabaseEncryption", "DataplaneV2Config", @@ -304,6 +311,7 @@ "DeleteNodePoolRequest", "DesiredAdditionalIPRangesConfig", "DesiredEnterpriseConfig", + "DiskIoScheduler", "DisruptionBudget", "DisruptionEvent", "DnsCacheConfig", @@ -418,6 +426,8 @@ "ResourceManagerTags", "ResourceUsageExportConfig", "RollbackNodePoolUpgradeRequest", + "RollbackSafeUpgrade", + "RollbackSafeUpgradeStatus", "SandboxConfig", "ScheduleUpgradeConfig", "SecondaryBootDisk", diff --git a/packages/google-cloud-container/google/cloud/container_v1/__init__.py b/packages/google-cloud-container/google/cloud/container_v1/__init__.py index 10b1a8f93a84..29e3d7205c99 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1/__init__.py @@ -68,6 +68,7 @@ ClusterPolicyConfig, ClusterUpdate, ClusterUpgradeInfo, + CompleteControlPlaneUpgradeRequest, CompleteIPRotationRequest, CompleteNodePoolUpgradeRequest, CompliancePostureConfig, @@ -80,6 +81,7 @@ CreateClusterRequest, CreateNodePoolRequest, CustomImageConfig, + CustomImageInfo, DailyMaintenanceWindow, DatabaseEncryption, DatapathProvider, @@ -90,6 +92,7 @@ DeleteNodePoolRequest, DesiredAdditionalIPRangesConfig, DesiredEnterpriseConfig, + DiskIoScheduler, DisruptionBudget, DisruptionEvent, DnsCacheConfig, @@ -208,6 +211,8 @@ ResourceManagerTags, ResourceUsageExportConfig, RollbackNodePoolUpgradeRequest, + RollbackSafeUpgrade, + RollbackSafeUpgradeStatus, SandboxConfig, ScheduleUpgradeConfig, SecondaryBootDisk, @@ -378,6 +383,7 @@ def _get_version(dependency_name): "ClusterPolicyConfig", "ClusterUpdate", "ClusterUpgradeInfo", + "CompleteControlPlaneUpgradeRequest", "CompleteIPRotationRequest", "CompleteNodePoolUpgradeRequest", "CompliancePostureConfig", @@ -390,6 +396,7 @@ def _get_version(dependency_name): "CreateClusterRequest", "CreateNodePoolRequest", "CustomImageConfig", + "CustomImageInfo", "DNSConfig", "DailyMaintenanceWindow", "DatabaseEncryption", @@ -401,6 +408,7 @@ def _get_version(dependency_name): "DeleteNodePoolRequest", "DesiredAdditionalIPRangesConfig", "DesiredEnterpriseConfig", + "DiskIoScheduler", "DisruptionBudget", "DisruptionEvent", "DnsCacheConfig", @@ -518,6 +526,8 @@ def _get_version(dependency_name): "ResourceManagerTags", "ResourceUsageExportConfig", "RollbackNodePoolUpgradeRequest", + "RollbackSafeUpgrade", + "RollbackSafeUpgradeStatus", "SandboxConfig", "ScheduleUpgradeConfig", "SecondaryBootDisk", diff --git a/packages/google-cloud-container/google/cloud/container_v1/gapic_metadata.json b/packages/google-cloud-container/google/cloud/container_v1/gapic_metadata.json index 10e9c962f6fc..e7a9d7f78ed9 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/gapic_metadata.json +++ b/packages/google-cloud-container/google/cloud/container_v1/gapic_metadata.json @@ -20,6 +20,11 @@ "check_autopilot_compatibility" ] }, + "CompleteControlPlaneUpgrade": { + "methods": [ + "complete_control_plane_upgrade" + ] + }, "CompleteIPRotation": { "methods": [ "complete_ip_rotation" @@ -205,6 +210,11 @@ "check_autopilot_compatibility" ] }, + "CompleteControlPlaneUpgrade": { + "methods": [ + "complete_control_plane_upgrade" + ] + }, "CompleteIPRotation": { "methods": [ "complete_ip_rotation" @@ -390,6 +400,11 @@ "check_autopilot_compatibility" ] }, + "CompleteControlPlaneUpgrade": { + "methods": [ + "complete_control_plane_upgrade" + ] + }, "CompleteIPRotation": { "methods": [ "complete_ip_rotation" diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/async_client.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/async_client.py index 664da472e3a6..3e7ab6b47c5f 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/async_client.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/async_client.py @@ -5211,6 +5211,99 @@ async def sample_fetch_node_pool_upgrade_info(): # Done; return the response. return response + async def complete_control_plane_upgrade( + self, + request: Optional[ + Union[cluster_service.CompleteControlPlaneUpgradeRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cluster_service.Operation: + r"""CompleteControlPlaneUpgrade completes the + rollback-safe upgrade by performing the step two upgrade + for a specific cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import container_v1 + + async def sample_complete_control_plane_upgrade(): + # Create a client + client = container_v1.ClusterManagerAsyncClient() + + # Initialize request argument(s) + request = container_v1.CompleteControlPlaneUpgradeRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_control_plane_upgrade(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.container_v1.types.CompleteControlPlaneUpgradeRequest, dict]]): + The request object. CompleteControlPlaneUpgradeRequest + sets the name of target cluster to + complete upgrade. + 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.container_v1.types.Operation: + This operation resource represents + operations that may have happened or are + happening on the cluster. All fields are + output only. + + """ + # 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, cluster_service.CompleteControlPlaneUpgradeRequest): + request = cluster_service.CompleteControlPlaneUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.complete_control_plane_upgrade + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "ClusterManagerAsyncClient": return self diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/client.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/client.py index b505439c0ada..2662980d8d1f 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/client.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/client.py @@ -5615,6 +5615,99 @@ def sample_fetch_node_pool_upgrade_info(): # Done; return the response. return response + def complete_control_plane_upgrade( + self, + request: Optional[ + Union[cluster_service.CompleteControlPlaneUpgradeRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cluster_service.Operation: + r"""CompleteControlPlaneUpgrade completes the + rollback-safe upgrade by performing the step two upgrade + for a specific cluster. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import container_v1 + + def sample_complete_control_plane_upgrade(): + # Create a client + client = container_v1.ClusterManagerClient() + + # Initialize request argument(s) + request = container_v1.CompleteControlPlaneUpgradeRequest( + name="name_value", + ) + + # Make the request + response = client.complete_control_plane_upgrade(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.container_v1.types.CompleteControlPlaneUpgradeRequest, dict]): + The request object. CompleteControlPlaneUpgradeRequest + sets the name of target cluster to + complete upgrade. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.container_v1.types.Operation: + This operation resource represents + operations that may have happened or are + happening on the cluster. All fields are + output only. + + """ + # 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, cluster_service.CompleteControlPlaneUpgradeRequest): + request = cluster_service.CompleteControlPlaneUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.complete_control_plane_upgrade + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ClusterManagerClient": return self diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/base.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/base.py index 9b993d7c2939..09a7ddd69dc9 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/base.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/base.py @@ -415,6 +415,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.complete_control_plane_upgrade: gapic_v1.method.wrap_method( + self.complete_control_plane_upgrade, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -774,6 +779,15 @@ def fetch_node_pool_upgrade_info( ]: raise NotImplementedError() + @property + def complete_control_plane_upgrade( + self, + ) -> Callable[ + [cluster_service.CompleteControlPlaneUpgradeRequest], + Union[cluster_service.Operation, Awaitable[cluster_service.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc.py index 5c509d1c9d13..862c43240cd5 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc.py @@ -1349,6 +1349,38 @@ def fetch_node_pool_upgrade_info( ) return self._stubs["fetch_node_pool_upgrade_info"] + @property + def complete_control_plane_upgrade( + self, + ) -> Callable[ + [cluster_service.CompleteControlPlaneUpgradeRequest], cluster_service.Operation + ]: + r"""Return a callable for the complete control plane upgrade method over gRPC. + + CompleteControlPlaneUpgrade completes the + rollback-safe upgrade by performing the step two upgrade + for a specific cluster. + + Returns: + Callable[[~.CompleteControlPlaneUpgradeRequest], + ~.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 "complete_control_plane_upgrade" not in self._stubs: + self._stubs["complete_control_plane_upgrade"] = ( + self._logged_channel.unary_unary( + "/google.container.v1.ClusterManager/CompleteControlPlaneUpgrade", + request_serializer=cluster_service.CompleteControlPlaneUpgradeRequest.serialize, + response_deserializer=cluster_service.Operation.deserialize, + ) + ) + return self._stubs["complete_control_plane_upgrade"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc_asyncio.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc_asyncio.py index d8827e6e126e..69e4bcc131b9 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/grpc_asyncio.py @@ -1406,6 +1406,39 @@ def fetch_node_pool_upgrade_info( ) return self._stubs["fetch_node_pool_upgrade_info"] + @property + def complete_control_plane_upgrade( + self, + ) -> Callable[ + [cluster_service.CompleteControlPlaneUpgradeRequest], + Awaitable[cluster_service.Operation], + ]: + r"""Return a callable for the complete control plane upgrade method over gRPC. + + CompleteControlPlaneUpgrade completes the + rollback-safe upgrade by performing the step two upgrade + for a specific cluster. + + Returns: + Callable[[~.CompleteControlPlaneUpgradeRequest], + 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 "complete_control_plane_upgrade" not in self._stubs: + self._stubs["complete_control_plane_upgrade"] = ( + self._logged_channel.unary_unary( + "/google.container.v1.ClusterManager/CompleteControlPlaneUpgrade", + request_serializer=cluster_service.CompleteControlPlaneUpgradeRequest.serialize, + response_deserializer=cluster_service.Operation.deserialize, + ) + ) + return self._stubs["complete_control_plane_upgrade"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1679,6 +1712,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.complete_control_plane_upgrade: self._wrap_method( + self.complete_control_plane_upgrade, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py index 45a8ed425219..33246757e306 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest.py @@ -84,6 +84,14 @@ def post_check_autopilot_compatibility(self, response): logging.log(f"Received response: {response}") return response + def pre_complete_control_plane_upgrade(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_control_plane_upgrade(self, response): + logging.log(f"Received response: {response}") + return response + def pre_complete_ip_rotation(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -424,6 +432,55 @@ def post_check_autopilot_compatibility_with_metadata( """ return response, metadata + def pre_complete_control_plane_upgrade( + self, + request: cluster_service.CompleteControlPlaneUpgradeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cluster_service.CompleteControlPlaneUpgradeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for complete_control_plane_upgrade + + Override in a subclass to manipulate the request or metadata + before they are sent to the ClusterManager server. + """ + return request, metadata + + def post_complete_control_plane_upgrade( + self, response: cluster_service.Operation + ) -> cluster_service.Operation: + """Post-rpc interceptor for complete_control_plane_upgrade + + DEPRECATED. Please use the `post_complete_control_plane_upgrade_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ClusterManager server but before + it is returned to user code. This `post_complete_control_plane_upgrade` interceptor runs + before the `post_complete_control_plane_upgrade_with_metadata` interceptor. + """ + return response + + def post_complete_control_plane_upgrade_with_metadata( + self, + response: cluster_service.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[cluster_service.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for complete_control_plane_upgrade + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ClusterManager server but before it is returned to user code. + + We recommend only using this `post_complete_control_plane_upgrade_with_metadata` + interceptor in new development instead of the `post_complete_control_plane_upgrade` interceptor. + When both interceptors are used, this `post_complete_control_plane_upgrade_with_metadata` interceptor runs after the + `post_complete_control_plane_upgrade` interceptor. The (possibly modified) response returned by + `post_complete_control_plane_upgrade` will be passed to + `post_complete_control_plane_upgrade_with_metadata`. + """ + return response, metadata + def pre_complete_ip_rotation( self, request: cluster_service.CompleteIPRotationRequest, @@ -2413,6 +2470,168 @@ def __call__( ) return resp + class _CompleteControlPlaneUpgrade( + _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade, + ClusterManagerRestStub, + ): + def __hash__(self): + return hash("ClusterManagerRestTransport.CompleteControlPlaneUpgrade") + + @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: cluster_service.CompleteControlPlaneUpgradeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cluster_service.Operation: + r"""Call the complete control plane + upgrade method over HTTP. + + Args: + request (~.cluster_service.CompleteControlPlaneUpgradeRequest): + The request object. CompleteControlPlaneUpgradeRequest + sets the name of target cluster to + complete upgrade. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cluster_service.Operation: + This operation resource represents + operations that may have happened or are + happening on the cluster. All fields are + output only. + + """ + + http_options = _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade._get_http_options() + + request, metadata = self._interceptor.pre_complete_control_plane_upgrade( + request, metadata + ) + transcoded_request = _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade._get_transcoded_request( + http_options, request + ) + + body = _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade._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.container_v1.ClusterManagerClient.CompleteControlPlaneUpgrade", + extra={ + "serviceName": "google.container.v1.ClusterManager", + "rpcName": "CompleteControlPlaneUpgrade", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ClusterManagerRestTransport._CompleteControlPlaneUpgrade._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 = cluster_service.Operation() + pb_resp = cluster_service.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_complete_control_plane_upgrade(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_complete_control_plane_upgrade_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cluster_service.Operation.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.container_v1.ClusterManagerClient.complete_control_plane_upgrade", + extra={ + "serviceName": "google.container.v1.ClusterManager", + "rpcName": "CompleteControlPlaneUpgrade", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CompleteIPRotation( _BaseClusterManagerRestTransport._BaseCompleteIPRotation, ClusterManagerRestStub ): @@ -7642,6 +7861,18 @@ def check_autopilot_compatibility( self._session, self._host, self._interceptor ) # type: ignore + @property + def complete_control_plane_upgrade( + self, + ) -> Callable[ + [cluster_service.CompleteControlPlaneUpgradeRequest], cluster_service.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._CompleteControlPlaneUpgrade( + self._session, self._host, self._interceptor + ) # type: ignore + @property def complete_ip_rotation( self, diff --git a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest_base.py b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest_base.py index 3ea96e350699..c55e6949683a 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest_base.py +++ b/packages/google-cloud-container/google/cloud/container_v1/services/cluster_manager/transports/rest_base.py @@ -167,6 +167,68 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCompleteControlPlaneUpgrade: + 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/*/clusters/*}:completeControlPlaneUpgrade", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=projects/*/zones/*/clusters/*}:completeControlPlaneUpgrade", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cluster_service.CompleteControlPlaneUpgradeRequest.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( + _BaseClusterManagerRestTransport._BaseCompleteControlPlaneUpgrade._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCompleteIPRotation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-container/google/cloud/container_v1/types/__init__.py b/packages/google-cloud-container/google/cloud/container_v1/types/__init__.py index 9a7244bc408c..2e727f0f9f9a 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/types/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1/types/__init__.py @@ -45,6 +45,7 @@ ClusterPolicyConfig, ClusterUpdate, ClusterUpgradeInfo, + CompleteControlPlaneUpgradeRequest, CompleteIPRotationRequest, CompleteNodePoolUpgradeRequest, CompliancePostureConfig, @@ -57,6 +58,7 @@ CreateClusterRequest, CreateNodePoolRequest, CustomImageConfig, + CustomImageInfo, DailyMaintenanceWindow, DatabaseEncryption, DatapathProvider, @@ -67,6 +69,7 @@ DeleteNodePoolRequest, DesiredAdditionalIPRangesConfig, DesiredEnterpriseConfig, + DiskIoScheduler, DisruptionBudget, DisruptionEvent, DnsCacheConfig, @@ -185,6 +188,8 @@ ResourceManagerTags, ResourceUsageExportConfig, RollbackNodePoolUpgradeRequest, + RollbackSafeUpgrade, + RollbackSafeUpgradeStatus, SandboxConfig, ScheduleUpgradeConfig, SecondaryBootDisk, @@ -270,6 +275,7 @@ "ClusterPolicyConfig", "ClusterUpdate", "ClusterUpgradeInfo", + "CompleteControlPlaneUpgradeRequest", "CompleteIPRotationRequest", "CompleteNodePoolUpgradeRequest", "CompliancePostureConfig", @@ -282,6 +288,7 @@ "CreateClusterRequest", "CreateNodePoolRequest", "CustomImageConfig", + "CustomImageInfo", "DailyMaintenanceWindow", "DatabaseEncryption", "DataplaneV2Config", @@ -291,6 +298,7 @@ "DeleteNodePoolRequest", "DesiredAdditionalIPRangesConfig", "DesiredEnterpriseConfig", + "DiskIoScheduler", "DisruptionBudget", "DisruptionEvent", "DnsCacheConfig", @@ -405,6 +413,8 @@ "ResourceManagerTags", "ResourceUsageExportConfig", "RollbackNodePoolUpgradeRequest", + "RollbackSafeUpgrade", + "RollbackSafeUpgradeStatus", "SandboxConfig", "ScheduleUpgradeConfig", "SecondaryBootDisk", diff --git a/packages/google-cloud-container/google/cloud/container_v1/types/cluster_service.py b/packages/google-cloud-container/google/cloud/container_v1/types/cluster_service.py index f2c13fa6f296..47b8c931b573 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/types/cluster_service.py +++ b/packages/google-cloud-container/google/cloud/container_v1/types/cluster_service.py @@ -232,6 +232,7 @@ "Fleet", "ControlPlaneEndpointsConfig", "LocalNvmeSsdBlockConfig", + "DiskIoScheduler", "EphemeralStorageLocalSsdConfig", "ResourceManagerTags", "EnterpriseConfig", @@ -239,11 +240,15 @@ "BootDisk", "SecondaryBootDisk", "SecondaryBootDiskUpdateStrategy", + "RollbackSafeUpgrade", "FetchClusterUpgradeInfoRequest", "ClusterUpgradeInfo", + "RollbackSafeUpgradeStatus", "UpgradeDetails", "FetchNodePoolUpgradeInfoRequest", "NodePoolUpgradeInfo", + "CustomImageInfo", + "CompleteControlPlaneUpgradeRequest", "ScheduleUpgradeConfig", "GkeAutoUpgradeConfig", "NetworkTierConfig", @@ -431,7 +436,7 @@ class LinuxNodeConfig(proto.Message): net.netfilter.nf_conntrack_tcp_timeout_established net.netfilter.nf_conntrack_acct kernel.keys.maxkeys kernel.keys.maxbytes kernel.shmmni kernel.shmmax - kernel.shmall kernel.perf_event_paranoid + kernel.shmall kernel.core_pattern kernel.perf_event_paranoid kernel.sched_rt_runtime_us kernel.softlockup_panic kernel.yama.ptrace_scope kernel.kptr_restrict kernel.dmesg_restrict kernel.sysrq fs.aio-max-nr fs.file-max @@ -487,6 +492,12 @@ class LinuxNodeConfig(proto.Message): the node pool. This field is a member of `oneof`_ ``_accurate_time_config``. + node_vfio_config (google.cloud.container_v1.types.LinuxNodeConfig.NodeVfioConfig): + Optional. Contains VFIO-related + configurations for this node. + disk_io_scheduler (google.cloud.container_v1.types.DiskIoScheduler): + Optional. Controls the configuration for the + disk IO scheduler. """ class CgroupMode(proto.Enum): @@ -903,6 +914,37 @@ class AccurateTimeConfig(proto.Message): optional=True, ) + class NodeVfioConfig(proto.Message): + r"""Configuration settings for VFIO (Virtual Function I/O) on a + node. VFIO allows safe, unprivileged, userspace drivers to + access I/O devices. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dma_entry_limit (int): + Optional. Specifies the maximum number of DMA entries + (pages) that can be mapped by the VFIO IOMMU type 1 driver + for a container. This limit affects the total amount of host + memory that can be pinned for direct device access, which is + often critical for high-performance devices like TPUs and + GPUs. This setting corresponds to the kernel parameter at: + ``/sys/module/vfio_iommu_type1/parameters/dma_entry_limit``. + The default value in the kernel is ``65535``. Higher values + may be needed for workloads mapping large memory regions. + Supported values are integers between ``65535`` and + ``4194304``. + + This field is a member of `oneof`_ ``_dma_entry_limit``. + """ + + dma_entry_limit: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + sysctls: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -951,6 +993,16 @@ class AccurateTimeConfig(proto.Message): optional=True, message=AccurateTimeConfig, ) + node_vfio_config: NodeVfioConfig = proto.Field( + proto.MESSAGE, + number=15, + message=NodeVfioConfig, + ) + disk_io_scheduler: "DiskIoScheduler" = proto.Field( + proto.MESSAGE, + number=16, + message="DiskIoScheduler", + ) class WindowsNodeConfig(proto.Message): @@ -1342,9 +1394,12 @@ class CrashLoopBackOffConfig(proto.Message): class TopologyManager(proto.Message): - r"""TopologyManager defines the configuration options for - Topology Manager feature. See - https://kubernetes.io/docs/tasks/administer-cluster/topology-manager/ + r"""TopologyManager defines the configuration options for the + ```kubelet`` Topology Manager + component `__. + For more information about the supported machine types and versions + for the Topology Manager in GKE, see `Customizing node system + configuration `__. Attributes: policy (str): @@ -2725,12 +2780,17 @@ class Type(proto.Enum): Must consume from a specific reservation. Must specify key value fields for specifying the reservations. + ANY_RESERVATION_THEN_FAIL (4): + Consume any reservation available. If no + reservation is available, fail the node + creation. """ UNSPECIFIED = 0 NO_RESERVATION = 1 ANY_RESERVATION = 2 SPECIFIC_RESERVATION = 3 + ANY_RESERVATION_THEN_FAIL = 4 consume_reservation_type: Type = proto.Field( proto.ENUM, @@ -4776,6 +4836,17 @@ class Cluster(proto.Message): current_master_version (str): Output only. The current software version of the master endpoint. + current_emulated_version (str): + Output only. The current emulated version of + the master endpoint. The version is in minor + version format, e.g. 1.30. No value or empty + string means the cluster has no emulated + version. + rollback_safe_upgrade (google.cloud.container_v1.types.RollbackSafeUpgrade): + Optional. The rollback safe upgrade + information of the cluster. This field is used + when user manually triggers a rollback safe + upgrade. current_node_version (str): Output only. Deprecated, use `NodePools.version `__ @@ -5172,6 +5243,15 @@ class Status(proto.Enum): proto.STRING, number=104, ) + current_emulated_version: str = proto.Field( + proto.STRING, + number=167, + ) + rollback_safe_upgrade: "RollbackSafeUpgrade" = proto.Field( + proto.MESSAGE, + number=170, + message="RollbackSafeUpgrade", + ) current_node_version: str = proto.Field( proto.STRING, number=105, @@ -6218,6 +6298,9 @@ class ClusterUpdate(proto.Message): desired_control_plane_egress (google.cloud.container_v1.types.ControlPlaneEgress): The desired control plane egress control config for the cluster. + desired_rollback_safe_upgrade (google.cloud.container_v1.types.RollbackSafeUpgrade): + Optional. The desired rollback safe upgrade + configuration. desired_managed_opentelemetry_config (google.cloud.container_v1.types.ManagedOpenTelemetryConfig): The desired managed open telemetry configuration. @@ -6230,6 +6313,11 @@ class ClusterUpdate(proto.Message): desired_node_creation_config (google.cloud.container_v1.types.NodeCreationConfig): Optional. The desired NodeCreationConfig for the cluster. + desired_emulated_version (str): + Optional. The desired emulated version for + the cluster. + + This field is a member of `oneof`_ ``_desired_emulated_version``. """ desired_node_version: str = proto.Field( @@ -6619,6 +6707,11 @@ class ClusterUpdate(proto.Message): number=160, message="ControlPlaneEgress", ) + desired_rollback_safe_upgrade: "RollbackSafeUpgrade" = proto.Field( + proto.MESSAGE, + number=161, + message="RollbackSafeUpgrade", + ) desired_managed_opentelemetry_config: "ManagedOpenTelemetryConfig" = proto.Field( proto.MESSAGE, number=163, @@ -6639,6 +6732,11 @@ class ClusterUpdate(proto.Message): number=171, message="NodeCreationConfig", ) + desired_emulated_version: str = proto.Field( + proto.STRING, + number=182, + optional=True, + ) class AdditionalPodRangesConfig(proto.Message): @@ -7532,6 +7630,10 @@ class UpdateNodePoolRequest(proto.Message): to the chosen autoscaling profile. taint_config (google.cloud.container_v1.types.TaintConfig): The taint configuration for the node pool. + maintenance_policy (google.cloud.container_v1.types.NodePool.NodePoolMaintenancePolicy): + Optional. Specifies the maintenance policy + for the node pool, including maintenance + exclusion options. """ project_id: str = proto.Field( @@ -7719,6 +7821,11 @@ class UpdateNodePoolRequest(proto.Message): number=51, message="TaintConfig", ) + maintenance_policy: "NodePool.NodePoolMaintenancePolicy" = proto.Field( + proto.MESSAGE, + number=52, + message="NodePool.NodePoolMaintenancePolicy", + ) class SetNodePoolAutoscalingRequest(proto.Message): @@ -8896,8 +9003,8 @@ class NodePool(proto.Message): that can be run simultaneously on a node in the node pool. conditions (MutableSequence[google.cloud.container_v1.types.StatusCondition]): - Which conditions caused the current node pool - state. + Output only. Which conditions caused the + current node pool state. pod_ipv4_cidr_size (int): Output only. The pod CIDR block size per node in this node pool. @@ -8910,10 +9017,11 @@ class NodePool(proto.Message): Output only. Update info contains relevant information during a node pool update. etag (str): - This checksum is computed by the server based - on the value of node pool fields, and may be - sent on update requests to ensure the client has - an up-to-date value before proceeding. + Output only. This checksum is computed by the + server based on the value of node pool fields, + and may be sent on update requests to ensure the + client has an up-to-date value before + proceeding. queued_provisioning (google.cloud.container_v1.types.NodePool.QueuedProvisioning): Specifies the configuration of queued provisioning. @@ -8925,6 +9033,9 @@ class NodePool(proto.Message): maintenance_policy (google.cloud.container_v1.types.NodePool.NodePoolMaintenancePolicy): Optional. Specifies the maintenance policy for the node pool. + kubelet_cert_info (google.cloud.container_v1.types.NodePool.KubeletCertInfo): + Output only. Contains expiry information + about the kubelet certificate. """ class Status(proto.Enum): @@ -9315,6 +9426,27 @@ class NodePoolMaintenancePolicy(proto.Message): ) ) + class KubeletCertInfo(proto.Message): + r"""Contains expiry information about the kubelet certificate. + + Attributes: + tpm_bootstrap_cert_expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. + non_tpm_bootstrap_cert_expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. + """ + + tpm_bootstrap_cert_expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + non_tpm_bootstrap_cert_expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -9421,6 +9553,11 @@ class NodePoolMaintenancePolicy(proto.Message): number=118, message=NodePoolMaintenancePolicy, ) + kubelet_cert_info: KubeletCertInfo = proto.Field( + proto.MESSAGE, + number=119, + message=KubeletCertInfo, + ) class NodeManagement(proto.Message): @@ -11597,7 +11734,9 @@ class Channel(proto.Enum): Values: UNSPECIFIED (0): - No channel specified. + Deprecated: No channel specified. it will be + removed in the future, use RAPID, REGULAR, + STABLE or EXTENDED instead. RAPID (1): RAPID channel is offered on an early access basis for customers who want to test new @@ -12500,6 +12639,12 @@ class UpgradeEvent(proto.Message): The current version before the upgrade. target_version (str): The target version for the upgrade. + current_emulated_version (str): + Output only. The current emulated version + before the upgrade. + target_emulated_version (str): + Output only. The target emulated version for + the upgrade. resource (str): Optional relative path to the resource. For example in node pool upgrades, the relative path @@ -12528,6 +12673,14 @@ class UpgradeEvent(proto.Message): proto.STRING, number=5, ) + current_emulated_version: str = proto.Field( + proto.STRING, + number=7, + ) + target_emulated_version: str = proto.Field( + proto.STRING, + number=8, + ) resource: str = proto.Field( proto.STRING, number=6, @@ -12555,6 +12708,12 @@ class UpgradeInfoEvent(proto.Message): The current version before the upgrade. target_version (str): The target version for the upgrade. + current_emulated_version (str): + Output only. The current emulated version + before the upgrade. + target_emulated_version (str): + Output only. The target emulated version for + the upgrade. resource (str): Optional relative path to the resource. For example in node pool upgrades, the relative path @@ -12663,6 +12822,14 @@ class EventType(proto.Enum): proto.STRING, number=6, ) + current_emulated_version: str = proto.Field( + proto.STRING, + number=15, + ) + target_emulated_version: str = proto.Field( + proto.STRING, + number=16, + ) resource: str = proto.Field( proto.STRING, number=7, @@ -13117,6 +13284,8 @@ class Component(proto.Enum): kcp connection logs KCP_HPA (9): horizontal pod autoscaler decision logs + KCP_VPA (10): + vertical pod autoscaler decision logs """ COMPONENT_UNSPECIFIED = 0 @@ -13128,6 +13297,7 @@ class Component(proto.Enum): KCP_SSHD = 7 KCP_CONNECTION = 8 KCP_HPA = 9 + KCP_VPA = 10 enable_components: MutableSequence[Component] = proto.RepeatedField( proto.ENUM, @@ -13746,6 +13916,31 @@ class LocalNvmeSsdBlockConfig(proto.Message): ) +class DiskIoScheduler(proto.Message): + r"""DiskIoScheduler contains the configuration for the disk IO + scheduler. + + Attributes: + node_system_io_scheduler (str): + Optional. Configures the IO scheduler for the boot disk or + ephemeral lssd that runs node system workloads. Supported + values are ``mq-deadline``, ``bfq``, ``kyber``, ``none``. + node_attached_disk_io_scheduler (str): + Optional. Configures the IO scheduler for the attached + disks. Supported values are ``mq-deadline``, ``bfq``, + ``kyber``, ``none``. + """ + + node_system_io_scheduler: str = proto.Field( + proto.STRING, + number=1, + ) + node_attached_disk_io_scheduler: str = proto.Field( + proto.STRING, + number=2, + ) + + class EphemeralStorageLocalSsdConfig(proto.Message): r"""EphemeralStorageLocalSsdConfig contains configuration for the node ephemeral storage using Local SSDs. @@ -14001,6 +14196,24 @@ class SecondaryBootDiskUpdateStrategy(proto.Message): """ +class RollbackSafeUpgrade(proto.Message): + r"""RollbackSafeUpgrade is the configuration for the rollback + safe upgrade. + + Attributes: + control_plane_soak_duration (google.protobuf.duration_pb2.Duration): + Optional. A user-defined period for the + cluster remains in the rollbackable state. ex: + {seconds: 21600}. + """ + + control_plane_soak_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class FetchClusterUpgradeInfoRequest(proto.Message): r"""FetchClusterUpgradeInfoRequest fetches the upgrade information of a cluster. @@ -14060,6 +14273,9 @@ class ClusterUpgradeInfo(proto.Message): extended support timestamp. This field is a member of `oneof`_ ``_end_of_extended_support_timestamp``. + rollback_safe_upgrade_status (google.cloud.container_v1.types.RollbackSafeUpgradeStatus): + Output only. The cluster's rollback-safe + upgrade status. """ class AutoUpgradeStatus(proto.Enum): @@ -14155,6 +14371,58 @@ class AutoUpgradePausedReason(proto.Enum): number=6, optional=True, ) + rollback_safe_upgrade_status: "RollbackSafeUpgradeStatus" = proto.Field( + proto.MESSAGE, + number=9, + message="RollbackSafeUpgradeStatus", + ) + + +class RollbackSafeUpgradeStatus(proto.Message): + r"""RollbackSafeUpgradeStatus contains the rollback-safe upgrade + status of a cluster. + + Attributes: + mode (google.cloud.container_v1.types.RollbackSafeUpgradeStatus.Mode): + Output only. The mode of the rollback-safe + upgrade. + control_plane_upgrade_rollback_end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The rollback-safe mode + expiration time. + previous_version (str): + Output only. The GKE version that the cluster + previously used before step-one upgrade. + """ + + class Mode(proto.Enum): + r"""Mode indicates the mode of the rollback-safe upgrade. + + Values: + MODE_UNSPECIFIED (0): + MODE_UNSPECIFIED means it's in regular upgrade mode. + KCP_MINOR_UPGRADE_ROLLBACK_SAFE_MODE (1): + KCP_MINOR_UPGRADE_ROLLBACK_SAFE_MODE means it's in + rollback-safe mode after a KCP minor version step-one + upgrade. + """ + + MODE_UNSPECIFIED = 0 + KCP_MINOR_UPGRADE_ROLLBACK_SAFE_MODE = 1 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + control_plane_upgrade_rollback_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + previous_version: str = proto.Field( + proto.STRING, + number=3, + ) class UpgradeDetails(proto.Message): @@ -14181,6 +14449,12 @@ class UpgradeDetails(proto.Message): The version after the upgrade. start_type (google.cloud.container_v1.types.UpgradeDetails.StartType): The start type of the upgrade. + initial_emulated_version (str): + Output only. The emulated version before the + upgrade. + target_emulated_version (str): + Output only. The emulated version after the + upgrade. """ class State(proto.Enum): @@ -14251,6 +14525,14 @@ class StartType(proto.Enum): number=6, enum=StartType, ) + initial_emulated_version: str = proto.Field( + proto.STRING, + number=7, + ) + target_emulated_version: str = proto.Field( + proto.STRING, + number=8, + ) class FetchNodePoolUpgradeInfoRequest(proto.Message): @@ -14312,6 +14594,9 @@ class NodePoolUpgradeInfo(proto.Message): of extended support timestamp. This field is a member of `oneof`_ ``_end_of_extended_support_timestamp``. + custom_image_info (google.cloud.container_v1.types.CustomImageInfo): + Output only. Upgrade info for the node pool + specific to the usage of custom images. """ class AutoUpgradeStatus(proto.Enum): @@ -14398,6 +14683,50 @@ class AutoUpgradePausedReason(proto.Enum): number=7, optional=True, ) + custom_image_info: "CustomImageInfo" = proto.Field( + proto.MESSAGE, + number=8, + message="CustomImageInfo", + ) + + +class CustomImageInfo(proto.Message): + r"""Contains the custom image info for a node pool. + + Attributes: + upgrade_message (str): + Output only. The human-readable upgrade + message for the custom image. + """ + + upgrade_message: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteControlPlaneUpgradeRequest(proto.Message): + r"""CompleteControlPlaneUpgradeRequest sets the name of target + cluster to complete upgrade. + + Attributes: + name (str): + Required. The name (project, location, cluster) of the + cluster to complete upgrade. Specified in the format + ``projects/*/locations/*/clusters/*``. + version (str): + Optional. API request version that initiates + this operation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) class ScheduleUpgradeConfig(proto.Message): diff --git a/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_async.py b/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_async.py new file mode 100644 index 000000000000..09a442f911d9 --- /dev/null +++ b/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_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 CompleteControlPlaneUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-container + + +# [START container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_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 container_v1 + + +async def sample_complete_control_plane_upgrade(): + # Create a client + client = container_v1.ClusterManagerAsyncClient() + + # Initialize request argument(s) + request = container_v1.CompleteControlPlaneUpgradeRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_control_plane_upgrade(request=request) + + # Handle the response + print(response) + + +# [END container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_async] diff --git a/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_sync.py b/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_sync.py new file mode 100644 index 000000000000..e753cbcb2b0f --- /dev/null +++ b/packages/google-cloud-container/samples/generated_samples/container_v1_generated_cluster_manager_complete_control_plane_upgrade_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 CompleteControlPlaneUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-container + + +# [START container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_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 container_v1 + + +def sample_complete_control_plane_upgrade(): + # Create a client + client = container_v1.ClusterManagerClient() + + # Initialize request argument(s) + request = container_v1.CompleteControlPlaneUpgradeRequest( + name="name_value", + ) + + # Make the request + response = client.complete_control_plane_upgrade(request=request) + + # Handle the response + print(response) + + +# [END container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_sync] diff --git a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json index e8e77fefd649..897aa0d382f8 100644 --- a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json +++ b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json @@ -343,6 +343,159 @@ ], "title": "container_v1_generated_cluster_manager_check_autopilot_compatibility_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.container_v1.ClusterManagerAsyncClient", + "shortName": "ClusterManagerAsyncClient" + }, + "fullName": "google.cloud.container_v1.ClusterManagerAsyncClient.complete_control_plane_upgrade", + "method": { + "fullName": "google.container.v1.ClusterManager.CompleteControlPlaneUpgrade", + "service": { + "fullName": "google.container.v1.ClusterManager", + "shortName": "ClusterManager" + }, + "shortName": "CompleteControlPlaneUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.container_v1.types.CompleteControlPlaneUpgradeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.container_v1.types.Operation", + "shortName": "complete_control_plane_upgrade" + }, + "description": "Sample for CompleteControlPlaneUpgrade", + "file": "container_v1_generated_cluster_manager_complete_control_plane_upgrade_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_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": "container_v1_generated_cluster_manager_complete_control_plane_upgrade_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.container_v1.ClusterManagerClient", + "shortName": "ClusterManagerClient" + }, + "fullName": "google.cloud.container_v1.ClusterManagerClient.complete_control_plane_upgrade", + "method": { + "fullName": "google.container.v1.ClusterManager.CompleteControlPlaneUpgrade", + "service": { + "fullName": "google.container.v1.ClusterManager", + "shortName": "ClusterManager" + }, + "shortName": "CompleteControlPlaneUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.container_v1.types.CompleteControlPlaneUpgradeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.container_v1.types.Operation", + "shortName": "complete_control_plane_upgrade" + }, + "description": "Sample for CompleteControlPlaneUpgrade", + "file": "container_v1_generated_cluster_manager_complete_control_plane_upgrade_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "container_v1_generated_ClusterManager_CompleteControlPlaneUpgrade_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": "container_v1_generated_cluster_manager_complete_control_plane_upgrade_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-container/tests/unit/gapic/container_v1/test_cluster_manager.py b/packages/google-cloud-container/tests/unit/gapic/container_v1/test_cluster_manager.py index 3044b4f085da..72c64e1ff4e2 100644 --- a/packages/google-cloud-container/tests/unit/gapic/container_v1/test_cluster_manager.py +++ b/packages/google-cloud-container/tests/unit/gapic/container_v1/test_cluster_manager.py @@ -1734,6 +1734,7 @@ def test_get_cluster(request_type, transport: str = "grpc"): endpoint="endpoint_value", initial_cluster_version="initial_cluster_version_value", current_master_version="current_master_version_value", + current_emulated_version="current_emulated_version_value", current_node_version="current_node_version_value", create_time="create_time_value", status=cluster_service.Cluster.Status.PROVISIONING, @@ -1778,6 +1779,7 @@ def test_get_cluster(request_type, transport: str = "grpc"): assert response.endpoint == "endpoint_value" assert response.initial_cluster_version == "initial_cluster_version_value" assert response.current_master_version == "current_master_version_value" + assert response.current_emulated_version == "current_emulated_version_value" assert response.current_node_version == "current_node_version_value" assert response.create_time == "create_time_value" assert response.status == cluster_service.Cluster.Status.PROVISIONING @@ -1948,6 +1950,7 @@ async def test_get_cluster_async(request_type, transport: str = "grpc_asyncio"): endpoint="endpoint_value", initial_cluster_version="initial_cluster_version_value", current_master_version="current_master_version_value", + current_emulated_version="current_emulated_version_value", current_node_version="current_node_version_value", create_time="create_time_value", status=cluster_service.Cluster.Status.PROVISIONING, @@ -1993,6 +1996,7 @@ async def test_get_cluster_async(request_type, transport: str = "grpc_asyncio"): assert response.endpoint == "endpoint_value" assert response.initial_cluster_version == "initial_cluster_version_value" assert response.current_master_version == "current_master_version_value" + assert response.current_emulated_version == "current_emulated_version_value" assert response.current_node_version == "current_node_version_value" assert response.create_time == "create_time_value" assert response.status == cluster_service.Cluster.Status.PROVISIONING @@ -14991,6 +14995,307 @@ async def test_fetch_node_pool_upgrade_info_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + cluster_service.CompleteControlPlaneUpgradeRequest(), + {}, + ], +) +def test_complete_control_plane_upgrade(request_type, transport: str = "grpc"): + client = ClusterManagerClient( + 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.complete_control_plane_upgrade), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = cluster_service.Operation( + name="name_value", + zone="zone_value", + operation_type=cluster_service.Operation.Type.CREATE_CLUSTER, + status=cluster_service.Operation.Status.PENDING, + detail="detail_value", + status_message="status_message_value", + self_link="self_link_value", + target_link="target_link_value", + location="location_value", + start_time="start_time_value", + end_time="end_time_value", + ) + response = client.complete_control_plane_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = cluster_service.CompleteControlPlaneUpgradeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cluster_service.Operation) + assert response.name == "name_value" + assert response.zone == "zone_value" + assert response.operation_type == cluster_service.Operation.Type.CREATE_CLUSTER + assert response.status == cluster_service.Operation.Status.PENDING + assert response.detail == "detail_value" + assert response.status_message == "status_message_value" + assert response.self_link == "self_link_value" + assert response.target_link == "target_link_value" + assert response.location == "location_value" + assert response.start_time == "start_time_value" + assert response.end_time == "end_time_value" + + +def test_complete_control_plane_upgrade_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 = ClusterManagerClient( + 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 = cluster_service.CompleteControlPlaneUpgradeRequest( + name="name_value", + version="version_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.complete_control_plane_upgrade(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cluster_service.CompleteControlPlaneUpgradeRequest( + name="name_value", + version="version_value", + ) + assert args[0] == request_msg + + +def test_complete_control_plane_upgrade_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ClusterManagerClient( + 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.complete_control_plane_upgrade + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.complete_control_plane_upgrade + ] = mock_rpc + request = {} + client.complete_control_plane_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.complete_control_plane_upgrade(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_complete_control_plane_upgrade_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 = ClusterManagerAsyncClient( + 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.complete_control_plane_upgrade + 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.complete_control_plane_upgrade + ] = mock_rpc + + request = {} + await client.complete_control_plane_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.complete_control_plane_upgrade(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", + [ + cluster_service.CompleteControlPlaneUpgradeRequest(), + {}, + ], +) +async def test_complete_control_plane_upgrade_async( + request_type, transport: str = "grpc_asyncio" +): + client = ClusterManagerAsyncClient( + 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.complete_control_plane_upgrade), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cluster_service.Operation( + name="name_value", + zone="zone_value", + operation_type=cluster_service.Operation.Type.CREATE_CLUSTER, + status=cluster_service.Operation.Status.PENDING, + detail="detail_value", + status_message="status_message_value", + self_link="self_link_value", + target_link="target_link_value", + location="location_value", + start_time="start_time_value", + end_time="end_time_value", + ) + ) + response = await client.complete_control_plane_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = cluster_service.CompleteControlPlaneUpgradeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, cluster_service.Operation) + assert response.name == "name_value" + assert response.zone == "zone_value" + assert response.operation_type == cluster_service.Operation.Type.CREATE_CLUSTER + assert response.status == cluster_service.Operation.Status.PENDING + assert response.detail == "detail_value" + assert response.status_message == "status_message_value" + assert response.self_link == "self_link_value" + assert response.target_link == "target_link_value" + assert response.location == "location_value" + assert response.start_time == "start_time_value" + assert response.end_time == "end_time_value" + + +def test_complete_control_plane_upgrade_field_headers(): + client = ClusterManagerClient( + 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 = cluster_service.CompleteControlPlaneUpgradeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + call.return_value = cluster_service.Operation() + client.complete_control_plane_upgrade(request) + + # Establish that the 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_complete_control_plane_upgrade_field_headers_async(): + client = ClusterManagerAsyncClient( + 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 = cluster_service.CompleteControlPlaneUpgradeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cluster_service.Operation() + ) + await client.complete_control_plane_upgrade(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_list_clusters_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -19714,48 +20019,176 @@ def test_fetch_node_pool_upgrade_info_rest_flattened(): "name": "projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4" } - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # 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 = cluster_service.NodePoolUpgradeInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_node_pool_upgrade_info(**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/*/clusters/*/nodePools/*}:fetchNodePoolUpgradeInfo" + % client.transport._host, + args[1], + ) + + +def test_fetch_node_pool_upgrade_info_rest_flattened_error(transport: str = "rest"): + client = ClusterManagerClient( + 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.fetch_node_pool_upgrade_info( + cluster_service.FetchNodePoolUpgradeInfoRequest(), + name="name_value", + ) + + +def test_complete_control_plane_upgrade_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 = ClusterManagerClient( + 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.complete_control_plane_upgrade + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.complete_control_plane_upgrade + ] = mock_rpc + + request = {} + client.complete_control_plane_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.complete_control_plane_upgrade(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_complete_control_plane_upgrade_rest_required_fields( + request_type=cluster_service.CompleteControlPlaneUpgradeRequest, +): + transport_class = transports.ClusterManagerRestTransport + + 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() + ).complete_control_plane_upgrade._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() + ).complete_control_plane_upgrade._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 = ClusterManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cluster_service.Operation() + # 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 = cluster_service.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = cluster_service.NodePoolUpgradeInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response_value._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.fetch_node_pool_upgrade_info(**mock_args) + response = client.complete_control_plane_upgrade(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/v1/{name=projects/*/locations/*/clusters/*/nodePools/*}:fetchNodePoolUpgradeInfo" - % client.transport._host, - args[1], - ) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -def test_fetch_node_pool_upgrade_info_rest_flattened_error(transport: str = "rest"): - client = ClusterManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_complete_control_plane_upgrade_rest_unset_required_fields(): + transport = transports.ClusterManagerRestTransport( + 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.fetch_node_pool_upgrade_info( - cluster_service.FetchNodePoolUpgradeInfoRequest(), - name="name_value", - ) + unset_fields = transport.complete_control_plane_upgrade._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) def test_credentials_transport_error(): @@ -20620,6 +21053,28 @@ def test_fetch_node_pool_upgrade_info_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_complete_control_plane_upgrade_empty_call_grpc(): + client = ClusterManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + call.return_value = cluster_service.Operation() + client.complete_control_plane_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cluster_service.CompleteControlPlaneUpgradeRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = ClusterManagerAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -20691,6 +21146,7 @@ async def test_get_cluster_empty_call_grpc_asyncio(): endpoint="endpoint_value", initial_cluster_version="initial_cluster_version_value", current_master_version="current_master_version_value", + current_emulated_version="current_emulated_version_value", current_node_version="current_node_version_value", create_time="create_time_value", status=cluster_service.Cluster.Status.PROVISIONING, @@ -21887,6 +22343,44 @@ async def test_fetch_node_pool_upgrade_info_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_complete_control_plane_upgrade_empty_call_grpc_asyncio(): + client = ClusterManagerAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + cluster_service.Operation( + name="name_value", + zone="zone_value", + operation_type=cluster_service.Operation.Type.CREATE_CLUSTER, + status=cluster_service.Operation.Status.PENDING, + detail="detail_value", + status_message="status_message_value", + self_link="self_link_value", + target_link="target_link_value", + location="location_value", + start_time="start_time_value", + end_time="end_time_value", + ) + ) + await client.complete_control_plane_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cluster_service.CompleteControlPlaneUpgradeRequest() + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = ClusterManagerClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -22090,6 +22584,7 @@ def test_get_cluster_rest_call_success(request_type): endpoint="endpoint_value", initial_cluster_version="initial_cluster_version_value", current_master_version="current_master_version_value", + current_emulated_version="current_emulated_version_value", current_node_version="current_node_version_value", create_time="create_time_value", status=cluster_service.Cluster.Status.PROVISIONING, @@ -22139,6 +22634,7 @@ def test_get_cluster_rest_call_success(request_type): assert response.endpoint == "endpoint_value" assert response.initial_cluster_version == "initial_cluster_version_value" assert response.current_master_version == "current_master_version_value" + assert response.current_emulated_version == "current_emulated_version_value" assert response.current_node_version == "current_node_version_value" assert response.create_time == "create_time_value" assert response.status == cluster_service.Cluster.Status.PROVISIONING @@ -27229,6 +27725,159 @@ def test_fetch_node_pool_upgrade_info_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_complete_control_plane_upgrade_rest_bad_request( + request_type=cluster_service.CompleteControlPlaneUpgradeRequest, +): + client = ClusterManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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.complete_control_plane_upgrade(request) + + +@pytest.mark.parametrize( + "request_type", + [ + cluster_service.CompleteControlPlaneUpgradeRequest, + dict, + ], +) +def test_complete_control_plane_upgrade_rest_call_success(request_type): + client = ClusterManagerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/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 = cluster_service.Operation( + name="name_value", + zone="zone_value", + operation_type=cluster_service.Operation.Type.CREATE_CLUSTER, + status=cluster_service.Operation.Status.PENDING, + detail="detail_value", + status_message="status_message_value", + self_link="self_link_value", + target_link="target_link_value", + location="location_value", + start_time="start_time_value", + end_time="end_time_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 = cluster_service.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.complete_control_plane_upgrade(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, cluster_service.Operation) + assert response.name == "name_value" + assert response.zone == "zone_value" + assert response.operation_type == cluster_service.Operation.Type.CREATE_CLUSTER + assert response.status == cluster_service.Operation.Status.PENDING + assert response.detail == "detail_value" + assert response.status_message == "status_message_value" + assert response.self_link == "self_link_value" + assert response.target_link == "target_link_value" + assert response.location == "location_value" + assert response.start_time == "start_time_value" + assert response.end_time == "end_time_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_control_plane_upgrade_rest_interceptors(null_interceptor): + transport = transports.ClusterManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ClusterManagerRestInterceptor(), + ) + client = ClusterManagerClient(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.ClusterManagerRestInterceptor, + "post_complete_control_plane_upgrade", + ) as post, + mock.patch.object( + transports.ClusterManagerRestInterceptor, + "post_complete_control_plane_upgrade_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.ClusterManagerRestInterceptor, + "pre_complete_control_plane_upgrade", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = cluster_service.CompleteControlPlaneUpgradeRequest.pb( + cluster_service.CompleteControlPlaneUpgradeRequest() + ) + 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 = cluster_service.Operation.to_json(cluster_service.Operation()) + req.return_value.content = return_value + + request = cluster_service.CompleteControlPlaneUpgradeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cluster_service.Operation() + post_with_metadata.return_value = cluster_service.Operation(), metadata + + client.complete_control_plane_upgrade( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_initialize_client_w_rest(): client = ClusterManagerClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -27956,6 +28605,27 @@ def test_fetch_node_pool_upgrade_info_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_complete_control_plane_upgrade_empty_call_rest(): + client = ClusterManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.complete_control_plane_upgrade), "__call__" + ) as call: + client.complete_control_plane_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = cluster_service.CompleteControlPlaneUpgradeRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ClusterManagerClient( @@ -28025,6 +28695,7 @@ def test_cluster_manager_base_transport(): "check_autopilot_compatibility", "fetch_cluster_upgrade_info", "fetch_node_pool_upgrade_info", + "complete_control_plane_upgrade", ) for method in methods: with pytest.raises(NotImplementedError): @@ -28414,6 +29085,9 @@ def test_cluster_manager_client_transport_session_collision(transport_name): session1 = client1.transport.fetch_node_pool_upgrade_info._session session2 = client2.transport.fetch_node_pool_upgrade_info._session assert session1 != session2 + session1 = client1.transport.complete_control_plane_upgrade._session + session2 = client2.transport.complete_control_plane_upgrade._session + assert session1 != session2 def test_cluster_manager_grpc_transport_channel(): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py index ea74ab00c83e..4d902a7b305a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py @@ -88,6 +88,9 @@ class StreamAssistRequest(proto.Message): user_metadata (google.cloud.discoveryengine_v1.types.AssistUserMetadata): Optional. Information about the user initiating the query. + agents_spec (google.cloud.discoveryengine_v1.types.StreamAssistRequest.AgentsSpec): + Optional. Specification of agents that are + used to serve the request. tools_spec (google.cloud.discoveryengine_v1.types.StreamAssistRequest.ToolsSpec): Optional. Specification of tools that are used to serve the request. @@ -96,6 +99,41 @@ class StreamAssistRequest(proto.Message): configuration for the request. """ + class AgentsSpec(proto.Message): + r"""Specification of agents that are used to serve the request. + + Attributes: + agent_specs (MutableSequence[google.cloud.discoveryengine_v1.types.StreamAssistRequest.AgentsSpec.AgentSpec]): + Optional. Specification of agents that are + used to serve the request. + """ + + class AgentSpec(proto.Message): + r"""Specification of an agent. + + Attributes: + agent_id (str): + Required. ID to identify the agent resource serving the + request. + + This field must conform to + `RFC-1034 `__ with a + length limit of 63 characters. + """ + + agent_id: str = proto.Field( + proto.STRING, + number=1, + ) + + agent_specs: MutableSequence["StreamAssistRequest.AgentsSpec.AgentSpec"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="StreamAssistRequest.AgentsSpec.AgentSpec", + ) + ) + class ToolsSpec(proto.Message): r"""Specification of tools that are used to serve the request. @@ -233,6 +271,11 @@ class GenerationSpec(proto.Message): number=6, message="AssistUserMetadata", ) + agents_spec: AgentsSpec = proto.Field( + proto.MESSAGE, + number=22, + message=AgentsSpec, + ) tools_spec: ToolsSpec = proto.Field( proto.MESSAGE, number=18, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/assistant_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/assistant_service.py index 149059337c7e..136742217735 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/assistant_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/types/assistant_service.py @@ -96,6 +96,9 @@ class StreamAssistRequest(proto.Message): user_metadata (google.cloud.discoveryengine_v1beta.types.AssistUserMetadata): Optional. Information about the user initiating the query. + agents_spec (google.cloud.discoveryengine_v1beta.types.StreamAssistRequest.AgentsSpec): + Optional. Specification of agents that are + used to serve the request. tools_spec (google.cloud.discoveryengine_v1beta.types.StreamAssistRequest.ToolsSpec): Optional. Specification of tools that are used to serve the request. @@ -104,6 +107,41 @@ class StreamAssistRequest(proto.Message): configuration for the request. """ + class AgentsSpec(proto.Message): + r"""Specification of agents that are used to serve the request. + + Attributes: + agent_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.StreamAssistRequest.AgentsSpec.AgentSpec]): + Optional. Specification of agents that are + used to serve the request. + """ + + class AgentSpec(proto.Message): + r"""Specification of an agent. + + Attributes: + agent_id (str): + Required. ID to identify the agent resource serving the + request. + + This field must conform to + `RFC-1034 `__ with a + length limit of 63 characters. + """ + + agent_id: str = proto.Field( + proto.STRING, + number=1, + ) + + agent_specs: MutableSequence["StreamAssistRequest.AgentsSpec.AgentSpec"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="StreamAssistRequest.AgentsSpec.AgentSpec", + ) + ) + class ToolsSpec(proto.Message): r"""Specification of tools that are used to serve the request. @@ -243,6 +281,11 @@ class GenerationSpec(proto.Message): number=6, message="AssistUserMetadata", ) + agents_spec: AgentsSpec = proto.Field( + proto.MESSAGE, + number=22, + message=AgentsSpec, + ) tools_spec: ToolsSpec = proto.Field( proto.MESSAGE, number=18, diff --git a/packages/google-cloud-pubsub/google/pubsub/__init__.py b/packages/google-cloud-pubsub/google/pubsub/__init__.py index 12f7ead4de77..e416a621c132 100644 --- a/packages/google-cloud-pubsub/google/pubsub/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub/__init__.py @@ -32,6 +32,7 @@ BigQueryConfig, BigtableConfig, CloudStorageConfig, + Compression, CreateSnapshotRequest, DeadLetterPolicy, DeleteSnapshotRequest, @@ -83,6 +84,7 @@ ) from google.pubsub_v1.types.schema import ( CommitSchemaRequest, + CompiledProtoSchema, CreateSchemaRequest, DeleteSchemaRequest, DeleteSchemaRevisionRequest, @@ -113,6 +115,7 @@ "BigQueryConfig", "BigtableConfig", "CloudStorageConfig", + "Compression", "CreateSnapshotRequest", "DeadLetterPolicy", "DeleteSnapshotRequest", @@ -162,6 +165,7 @@ "UpdateSubscriptionRequest", "UpdateTopicRequest", "CommitSchemaRequest", + "CompiledProtoSchema", "CreateSchemaRequest", "DeleteSchemaRequest", "DeleteSchemaRevisionRequest", diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py b/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py index c9f985983172..c9c492b6f2c4 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/__init__.py @@ -47,6 +47,7 @@ BigQueryConfig, BigtableConfig, CloudStorageConfig, + Compression, CreateSnapshotRequest, DeadLetterPolicy, DeleteSnapshotRequest, @@ -98,6 +99,7 @@ ) from .types.schema import ( CommitSchemaRequest, + CompiledProtoSchema, CreateSchemaRequest, DeleteSchemaRequest, DeleteSchemaRevisionRequest, @@ -209,6 +211,8 @@ def _get_version(dependency_name): "BigtableConfig", "CloudStorageConfig", "CommitSchemaRequest", + "CompiledProtoSchema", + "Compression", "CreateSchemaRequest", "CreateSnapshotRequest", "DeadLetterPolicy", diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/async_client.py b/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/async_client.py index 587a7a50a198..30e5c108625b 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/async_client.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/async_client.py @@ -330,6 +330,8 @@ async def sample_create_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.CreateSchemaRequest( @@ -824,6 +826,8 @@ async def sample_commit_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.CommitSchemaRequest( @@ -1288,6 +1292,8 @@ async def sample_validate_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.ValidateSchemaRequest( diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/client.py b/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/client.py index e576525eca1f..7033c620464e 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/client.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/services/schema_service/client.py @@ -774,6 +774,8 @@ def sample_create_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.CreateSchemaRequest( @@ -1256,6 +1258,8 @@ def sample_commit_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.CommitSchemaRequest( @@ -1708,6 +1712,8 @@ def sample_validate_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b'compiled_bytes_blob' schema.name = "name_value" request = pubsub_v1.ValidateSchemaRequest( diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/async_client.py b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/async_client.py index 3f18f6abc55f..49932d356aaa 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/async_client.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/async_client.py @@ -365,9 +365,10 @@ async def sample_create_subscription(): Args: request (Optional[Union[google.pubsub_v1.types.Subscription, dict]]): The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. name (:class:`str`): Required. Identifier. The name of the subscription. It must have the format @@ -439,10 +440,10 @@ async def sample_create_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. @@ -558,10 +559,10 @@ async def sample_get_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. @@ -689,10 +690,10 @@ async def sample_update_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/client.py b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/client.py index 91cacecf0c28..f84e38103688 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/client.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/client.py @@ -864,9 +864,10 @@ def sample_create_subscription(): Args: request (Union[google.pubsub_v1.types.Subscription, dict]): The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. name (str): Required. Identifier. The name of the subscription. It must have the format @@ -938,10 +939,10 @@ def sample_create_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. @@ -1054,10 +1055,10 @@ def sample_get_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. @@ -1182,10 +1183,10 @@ def sample_update_subscription(): Returns: google.pubsub_v1.types.Subscription: - A subscription resource. If none of push_config, bigquery_config, or - cloud_storage_config is set, then the subscriber will - pull and ack messages using API methods. At most one - of these fields may be set. + A subscription resource. If none of push_config, bigquery_config, + cloud_storage_config, or bigtable_config is set, then + the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. """ # Create or coerce a protobuf request object. diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/transports/rest.py b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/transports/rest.py index 3d7f9c785fae..2d7544dfc8f0 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/transports/rest.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/services/subscriber/transports/rest.py @@ -1189,9 +1189,10 @@ def __call__( Args: request (~.pubsub.Subscription): The request object. A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1203,9 +1204,10 @@ def __call__( Returns: ~.pubsub.Subscription: A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. """ @@ -1730,9 +1732,10 @@ def __call__( Returns: ~.pubsub.Subscription: A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. """ @@ -2885,9 +2888,10 @@ def __call__( Returns: ~.pubsub.Subscription: A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, - then the subscriber will pull and ack messages using API - methods. At most one of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will + pull and ack messages using API methods. At most one of + these fields may be set. """ diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py index 712a8589824f..565aaa43ce52 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/__init__.py @@ -21,6 +21,7 @@ BigQueryConfig, BigtableConfig, CloudStorageConfig, + Compression, CreateSnapshotRequest, DeadLetterPolicy, DeleteSnapshotRequest, @@ -72,6 +73,7 @@ ) from .schema import ( CommitSchemaRequest, + CompiledProtoSchema, CreateSchemaRequest, DeleteSchemaRequest, DeleteSchemaRevisionRequest, @@ -105,6 +107,7 @@ "BigQueryConfig", "BigtableConfig", "CloudStorageConfig", + "Compression", "CreateSnapshotRequest", "DeadLetterPolicy", "DeleteSnapshotRequest", @@ -154,6 +157,7 @@ "UpdateSubscriptionRequest", "UpdateTopicRequest", "CommitSchemaRequest", + "CompiledProtoSchema", "CreateSchemaRequest", "DeleteSchemaRequest", "DeleteSchemaRevisionRequest", diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py index 2387da0ff6d0..77572a373949 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/pubsub.py @@ -34,6 +34,7 @@ "PlatformLogsSettings", "IngestionFailureEvent", "JavaScriptUDF", + "Compression", "AIInference", "MessageTransform", "Topic", @@ -259,6 +260,12 @@ class State(proto.Enum): The Kinesis stream does not exist. CONSUMER_NOT_FOUND (5): The Kinesis consumer does not exist. + CONFLICTING_REGION_CONSTRAINTS (6): + Indicates an error state where the ingestion + source cannot be processed because the selected + ingestion region is not permitted by the + Regional Access Boundary (RAB) restrictions on + the project's service account. """ STATE_UNSPECIFIED = 0 @@ -267,6 +274,7 @@ class State(proto.Enum): PUBLISH_PERMISSION_DENIED = 3 STREAM_NOT_FOUND = 4 CONSUMER_NOT_FOUND = 5 + CONFLICTING_REGION_CONSTRAINTS = 6 state: "IngestionDataSourceSettings.AwsKinesis.State" = proto.Field( proto.ENUM, @@ -364,6 +372,12 @@ class State(proto.Enum): TOO_MANY_OBJECTS (5): The Cloud Storage bucket has too many objects, ingestion will be paused. + CONFLICTING_REGION_CONSTRAINTS (8): + Indicates an error state where the ingestion + source cannot be processed because the selected + ingestion region is not permitted by the + Regional Access Boundary (RAB) restrictions on + the project's service account. """ STATE_UNSPECIFIED = 0 @@ -372,6 +386,7 @@ class State(proto.Enum): PUBLISH_PERMISSION_DENIED = 3 BUCKET_NOT_FOUND = 4 TOO_MANY_OBJECTS = 5 + CONFLICTING_REGION_CONSTRAINTS = 8 class TextFormat(proto.Message): r"""Configuration for reading Cloud Storage data in text format. Each @@ -509,6 +524,12 @@ class State(proto.Enum): RESOURCE_GROUP_NOT_FOUND (7): The provided Event Hubs resource group couldn't be found. + CONFLICTING_REGION_CONSTRAINTS (8): + Indicates an error state where the ingestion + source cannot be processed because the selected + ingestion region is not permitted by the + Regional Access Boundary (RAB) restrictions on + the project's service account. """ STATE_UNSPECIFIED = 0 @@ -519,6 +540,7 @@ class State(proto.Enum): EVENT_HUB_NOT_FOUND = 5 SUBSCRIPTION_NOT_FOUND = 6 RESOURCE_GROUP_NOT_FOUND = 7 + CONFLICTING_REGION_CONSTRAINTS = 8 state: "IngestionDataSourceSettings.AzureEventHubs.State" = proto.Field( proto.ENUM, @@ -601,6 +623,12 @@ class State(proto.Enum): The provided MSK cluster wasn't found. TOPIC_NOT_FOUND (5): The provided topic wasn't found. + CONFLICTING_REGION_CONSTRAINTS (6): + Indicates an error state where the ingestion + source cannot be processed because the selected + ingestion region is not permitted by the + Regional Access Boundary (RAB) restrictions on + the project's service account. """ STATE_UNSPECIFIED = 0 @@ -609,6 +637,7 @@ class State(proto.Enum): PUBLISH_PERMISSION_DENIED = 3 CLUSTER_NOT_FOUND = 4 TOPIC_NOT_FOUND = 5 + CONFLICTING_REGION_CONSTRAINTS = 6 state: "IngestionDataSourceSettings.AwsMsk.State" = proto.Field( proto.ENUM, @@ -680,6 +709,12 @@ class State(proto.Enum): The provided cluster wasn't found. TOPIC_NOT_FOUND (6): The provided topic wasn't found. + CONFLICTING_REGION_CONSTRAINTS (7): + Indicates an error state where the ingestion + source cannot be processed because the selected + ingestion region is not permitted by the + Regional Access Boundary (RAB) restrictions on + the project's service account. """ STATE_UNSPECIFIED = 0 @@ -689,6 +724,7 @@ class State(proto.Enum): UNREACHABLE_BOOTSTRAP_SERVER = 4 CLUSTER_NOT_FOUND = 5 TOPIC_NOT_FOUND = 6 + CONFLICTING_REGION_CONSTRAINTS = 7 state: "IngestionDataSourceSettings.ConfluentCloud.State" = proto.Field( proto.ENUM, @@ -1352,6 +1388,60 @@ class JavaScriptUDF(proto.Message): ) +class Compression(proto.Message): + r"""Configuration for compressing/decompressing message data + using a user-specified compression algorithm. + + Attributes: + compression_algorithm (google.pubsub_v1.types.Compression.CompressionAlgorithm): + Required. Specifies the compression algorithm + to use. + compression_mode (google.pubsub_v1.types.Compression.CompressionMode): + Required. Specifies whether to compress or + decompress the message. + """ + + class CompressionAlgorithm(proto.Enum): + r"""The compression algorithm to use. + + Values: + COMPRESSION_ALGORITHM_UNSPECIFIED (0): + Unspecified algorithm. + ZLIB (1): + ZLIB compression. + """ + + COMPRESSION_ALGORITHM_UNSPECIFIED = 0 + ZLIB = 1 + + class CompressionMode(proto.Enum): + r"""The mode of the compression SMT. + + Values: + COMPRESSION_MODE_UNSPECIFIED (0): + Unspecified mode. + COMPRESS (1): + Compress. + DECOMPRESS (2): + Decompress. + """ + + COMPRESSION_MODE_UNSPECIFIED = 0 + COMPRESS = 1 + DECOMPRESS = 2 + + compression_algorithm: CompressionAlgorithm = proto.Field( + proto.ENUM, + number=1, + enum=CompressionAlgorithm, + ) + compression_mode: CompressionMode = proto.Field( + proto.ENUM, + number=2, + enum=CompressionMode, + ) + + class AIInference(proto.Message): r"""Configuration for making inference requests against Vertex AI models. @@ -1432,6 +1522,10 @@ class MessageTransform(proto.Message): JavaScriptUDF's are specified on a resource, each must have a unique ``function_name``. + This field is a member of `oneof`_ ``transform``. + compression (google.pubsub_v1.types.Compression): + Optional. Compression/Decompression. + This field is a member of `oneof`_ ``transform``. ai_inference (google.pubsub_v1.types.AIInference): Optional. AI Inference. Specifies the Vertex @@ -1454,6 +1548,12 @@ class MessageTransform(proto.Message): oneof="transform", message="JavaScriptUDF", ) + compression: "Compression" = proto.Field( + proto.MESSAGE, + number=7, + oneof="transform", + message="Compression", + ) ai_inference: "AIInference" = proto.Field( proto.MESSAGE, number=6, @@ -1527,16 +1627,11 @@ class Topic(proto.Message): messages published to the topic. Transforms are applied in the order specified. tags (MutableMapping[str, str]): - Optional. Input only. Immutable. Tag - keys/values directly bound to this resource. For - example: - - "123/environment": "production", - "123/costCenter": "marketing" - See - https://docs.cloud.google.com/pubsub/docs/tags - for more information on using tags with Pub/Sub - resources. + Optional. Input only. Immutable. Tag keys/values directly + bound to this resource. For example: "123/environment": + "production", "123/costCenter": "marketing" See + https://{$universe.dns_names.final_documentation_domain}/pubsub/docs/tags + for more information on using tags with Pub/Sub resources. """ class State(proto.Enum): @@ -1978,9 +2073,9 @@ class DetachSubscriptionResponse(proto.Message): class Subscription(proto.Message): r"""A subscription resource. If none of ``push_config``, - ``bigquery_config``, or ``cloud_storage_config`` is set, then the - subscriber will pull and ack messages using API methods. At most one - of these fields may be set. + ``bigquery_config``, ``cloud_storage_config``, or + ``bigtable_config`` is set, then the subscriber will pull and ack + messages using API methods. At most one of these fields may be set. Attributes: name (str): @@ -2149,16 +2244,11 @@ class Subscription(proto.Message): subscribers. Transforms are applied in the order specified. tags (MutableMapping[str, str]): - Optional. Input only. Immutable. Tag - keys/values directly bound to this resource. For - example: - - "123/environment": "production", - "123/costCenter": "marketing" - See - https://docs.cloud.google.com/pubsub/docs/tags - for more information on using tags with Pub/Sub - resources. + Optional. Input only. Immutable. Tag keys/values directly + bound to this resource. For example: "123/environment": + "production", "123/costCenter": "marketing" See + https://{$universe.dns_names.final_documentation_domain}/pubsub/docs/tags + for more information on using tags with Pub/Sub resources. """ class State(proto.Enum): @@ -2587,12 +2677,15 @@ class BigQueryConfig(proto.Message): columns while all other message properties (other than data) are written to a JSON object in the attributes column. drop_unknown_fields (bool): - Optional. When true and use_topic_schema is true, any fields - that are a part of the topic schema that are not part of the - BigQuery table schema are dropped when writing to BigQuery. + Optional. If true and ``use_topic_schema`` is true, drops + any fields that are part of the topic schema that are not + part of the BigQuery table schema when writing to BigQuery. Otherwise, the schemas must be kept in sync and any messages with extra fields are not written and remain in the - subscription's backlog. + subscription's backlog. If true and ``use_table_schema`` is + true, drops any fields in the message that are not part of + the BigQuery table schema when writing to BigQuery. + Otherwise, the write to BigQuery will fail. state (google.pubsub_v1.types.BigQueryConfig.State): Output only. An output-only field that indicates whether or not the subscription can @@ -2685,12 +2778,13 @@ class State(proto.Enum): class BigtableConfig(proto.Message): - r"""Configuration for a Bigtable subscription. The Pub/Sub - message will be written to a Bigtable row as follows: + r"""Configuration for a Bigtable subscription. The Pub/Sub message will + be written to a Bigtable row as follows: - - row key: subscription name and message ID delimited by #. - - columns: message bytes written to a single column family - "data" with an empty-string column qualifier. + - row key: subscription name, message ID hash, and message ID + delimited by ``#``. + - columns: message bytes written to a single column family ``data`` + with an empty-string column qualifier. - cell timestamp: the message publish timestamp. Attributes: @@ -2738,16 +2832,17 @@ class State(proto.Enum): The subscription can actively send messages to Bigtable. NOT_FOUND (2): - Cannot write to Bigtable because the - instance, table, or app profile does not exist. + Unused in the current implementation. + Placeholder for future use. APP_PROFILE_MISCONFIGURED (3): - Cannot write to Bigtable because the app - profile is not configured for single-cluster - routing. + Unused in the current implementation. + Placeholder for future use. PERMISSION_DENIED (4): Cannot write to Bigtable because of permission denied errors. This can happen if: + - The Bigtable instance, table, or app profile does not + exist. - The Pub/Sub service agent has not been granted the `appropriate Bigtable IAM permission bigtable.tables.mutateRows <{$universe.dns_names.final_documentation_domain}/bigtable/docs/access-control#permissions>`__ @@ -2755,10 +2850,10 @@ class State(proto.Enum): project (`instructions <{$universe.dns_names.final_documentation_domain}/service-usage/docs/enable-disable>`__) SCHEMA_MISMATCH (5): - Cannot write to Bigtable because of a missing - column family ("data") or if there is no - structured row key for the subscription name + - message ID. + Cannot write to Bigtable because of a missing column family + (``data``), or if there is no structured row key for the + subscription name + message ID, if because the app profile + is not configured for single-cluster routing. IN_TRANSIT_LOCATION_RESTRICTION (6): Cannot write to the destination because enforce_in_transit is set to true and the destination locations are not in the @@ -3587,16 +3682,11 @@ class CreateSnapshotRequest(proto.Message): Optional. See `Creating and managing labels `__. tags (MutableMapping[str, str]): - Optional. Input only. Immutable. Tag - keys/values directly bound to this resource. For - example: - - "123/environment": "production", - "123/costCenter": "marketing" - See - https://docs.cloud.google.com/pubsub/docs/tags - for more information on using tags with Pub/Sub - resources. + Optional. Input only. Immutable. Tag keys/values directly + bound to this resource. For example: "123/environment": + "production", "123/costCenter": "marketing" See + https://{$universe.dns_names.final_documentation_domain}/pubsub/docs/tags + for more information on using tags with Pub/Sub resources. """ name: str = proto.Field( diff --git a/packages/google-cloud-pubsub/google/pubsub_v1/types/schema.py b/packages/google-cloud-pubsub/google/pubsub_v1/types/schema.py index 1c88e9dc4f0b..ce4601f464f1 100644 --- a/packages/google-cloud-pubsub/google/pubsub_v1/types/schema.py +++ b/packages/google-cloud-pubsub/google/pubsub_v1/types/schema.py @@ -40,6 +40,7 @@ "ValidateSchemaResponse", "ValidateMessageRequest", "ValidateMessageResponse", + "CompiledProtoSchema", }, ) @@ -86,6 +87,8 @@ class Encoding(proto.Enum): class Schema(proto.Message): r"""A schema resource. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: name (str): Required. Name of the schema. Format is @@ -96,6 +99,12 @@ class Schema(proto.Message): The definition of the schema. This should contain a string representing the full definition of the schema that is a valid schema definition of the type specified in ``type``. + compiled_proto_schema (google.pubsub_v1.types.CompiledProtoSchema): + Optional. Configuration for a schema provided as a + pre-compiled Protocol Buffer FileDescriptorSet. The ``type`` + field above must be set to PROTOCOL_BUFFER. + + This field is a member of `oneof`_ ``configuration``. revision_id (str): Output only. Immutable. The revision ID of the schema. @@ -133,6 +142,12 @@ class Type(proto.Enum): proto.STRING, number=3, ) + compiled_proto_schema: "CompiledProtoSchema" = proto.Field( + proto.MESSAGE, + number=8, + oneof="configuration", + message="CompiledProtoSchema", + ) revision_id: str = proto.Field( proto.STRING, number=4, @@ -509,4 +524,26 @@ class ValidateMessageResponse(proto.Message): r"""Response for the ``ValidateMessage`` method. Empty for now.""" +class CompiledProtoSchema(proto.Message): + r"""Configuration specific to compiled Protocol Buffer schemas. + + Attributes: + root_message (str): + Required. The name of the root message type + in the schema. + compiled_bytes (bytes): + Required. The compiled FileDescriptorSet + binary. + """ + + root_message: str = proto.Field( + proto.STRING, + number=1, + ) + compiled_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py index c5332d583604..f55021b1b90d 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_async.py @@ -40,6 +40,8 @@ async def sample_commit_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.CommitSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py index 7ba3ec8f4b0d..a9cc67d837c2 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_commit_schema_sync.py @@ -40,6 +40,8 @@ def sample_commit_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.CommitSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py index e691dd63cb13..65320b7a1346 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_async.py @@ -40,6 +40,8 @@ async def sample_create_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.CreateSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py index 7a71d471d765..5401083fd565 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_create_schema_sync.py @@ -40,6 +40,8 @@ def sample_create_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.CreateSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py index c3d7364f733e..4fe9b2ce9215 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_async.py @@ -40,6 +40,8 @@ async def sample_validate_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.ValidateSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py index 8bb19180ecce..80322153aba8 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py +++ b/packages/google-cloud-pubsub/samples/generated_samples/pubsub_v1_generated_schema_service_validate_schema_sync.py @@ -40,6 +40,8 @@ def sample_validate_schema(): # Initialize request argument(s) schema = pubsub_v1.Schema() + schema.compiled_proto_schema.root_message = "root_message_value" + schema.compiled_proto_schema.compiled_bytes = b"compiled_bytes_blob" schema.name = "name_value" request = pubsub_v1.ValidateSchemaRequest( diff --git a/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json b/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json index e3941f955762..80a0edbfaf0f 100644 --- a/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json +++ b/packages/google-cloud-pubsub/samples/generated_samples/snippet_metadata_google.pubsub.v1.json @@ -1515,12 +1515,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_CommitSchema_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1530,18 +1530,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -1599,12 +1599,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_CommitSchema_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1614,18 +1614,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -1688,12 +1688,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_CreateSchema_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1703,18 +1703,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -1776,12 +1776,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_CreateSchema_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -1791,18 +1791,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -2990,12 +2990,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_ValidateSchema_async", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -3005,18 +3005,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], @@ -3074,12 +3074,12 @@ "regionTag": "pubsub_v1_generated_SchemaService_ValidateSchema_sync", "segments": [ { - "end": 55, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 57, "start": 27, "type": "SHORT" }, @@ -3089,18 +3089,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-pubsub/tests/unit/gapic/pubsub_v1/test_schema_service.py b/packages/google-cloud-pubsub/tests/unit/gapic/pubsub_v1/test_schema_service.py index c835f6ad582f..94d8daf34ed6 100644 --- a/packages/google-cloud-pubsub/tests/unit/gapic/pubsub_v1/test_schema_service.py +++ b/packages/google-cloud-pubsub/tests/unit/gapic/pubsub_v1/test_schema_service.py @@ -7603,6 +7603,10 @@ def test_create_schema_rest_call_success(request_type): "name": "name_value", "type_": 1, "definition": "definition_value", + "compiled_proto_schema": { + "root_message": "root_message_value", + "compiled_bytes": b"compiled_bytes_blob", + }, "revision_id": "revision_id_value", "revision_create_time": {"seconds": 751, "nanos": 543}, } 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 9bfa5348b510..d7b8995ef7e0 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 @@ -38,6 +38,8 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + DisableRapidCacheMetadata, + DisableRapidCacheRequest, FindingCategory, FindingSeverity, FindingSummary, @@ -106,6 +108,8 @@ "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "DisableRapidCacheMetadata", + "DisableRapidCacheRequest", "FindingSummary", "Folder", "GetAnywhereCacheRequest", 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 c7c21acb441a..929c80160d79 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 @@ -50,6 +50,8 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + DisableRapidCacheMetadata, + DisableRapidCacheRequest, FindingCategory, FindingSeverity, FindingSummary, @@ -200,6 +202,8 @@ def _get_version(dependency_name): "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "DisableRapidCacheMetadata", + "DisableRapidCacheRequest", "FindingCategory", "FindingSeverity", "FindingSummary", 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 e1de166ce830..0d03b42fa30f 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 @@ -50,6 +50,11 @@ "disable_anywhere_cache" ] }, + "DisableRapidCache": { + "methods": [ + "disable_rapid_cache" + ] + }, "GetAnywhereCache": { "methods": [ "get_anywhere_cache" @@ -245,6 +250,11 @@ "disable_anywhere_cache" ] }, + "DisableRapidCache": { + "methods": [ + "disable_rapid_cache" + ] + }, "GetAnywhereCache": { "methods": [ "get_anywhere_cache" @@ -440,6 +450,11 @@ "disable_anywhere_cache" ] }, + "DisableRapidCache": { + "methods": [ + "disable_rapid_cache" + ] + }, "GetAnywhereCache": { "methods": [ "get_anywhere_cache" 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 7deaf04ea99d..bcb7edbfc1e3 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 @@ -3152,6 +3152,140 @@ async def sample_update_rapid_cache(): # Done; return the response. return response + async def disable_rapid_cache( + self, + request: Optional[Union[storage_control.DisableRapidCacheRequest, 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"""Disables a Rapid Cache instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional 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_disable_rapid_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableRapidCacheRequest( + name="name_value", + ) + + # Make the request + operation = await client.disable_rapid_cache(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.storage_control_v2.types.DisableRapidCacheRequest, dict]]): + The request object. Request message for + DisableRapidCache. + name (:class:`str`): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/rapidCaches/{rapid_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.storage_control_v2.types.RapidCache` + A Rapid Cache Instance. + + """ + # 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.DisableRapidCacheRequest): + request = storage_control.DisableRapidCacheRequest(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.disable_rapid_cache + ] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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, + storage_control.RapidCache, + metadata_type=storage_control.DisableRapidCacheMetadata, + ) + + # Done; return the response. + return response + async def get_rapid_cache( self, request: Optional[Union[storage_control.GetRapidCacheRequest, dict]] = None, 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 f5c59a32503c..5276374ffa5d 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 @@ -3707,6 +3707,137 @@ def sample_update_rapid_cache(): # Done; return the response. return response + def disable_rapid_cache( + self, + request: Optional[Union[storage_control.DisableRapidCacheRequest, 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"""Disables a Rapid Cache instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional 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_disable_rapid_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableRapidCacheRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_rapid_cache(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.storage_control_v2.types.DisableRapidCacheRequest, dict]): + The request object. Request message for + DisableRapidCache. + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/rapidCaches/{rapid_cache}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.storage_control_v2.types.RapidCache` + A Rapid Cache Instance. + + """ + # 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.DisableRapidCacheRequest): + request = storage_control.DisableRapidCacheRequest(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.disable_rapid_cache] + + header_params = {} + + routing_param_regex = re.compile( + "^(?Pprojects/[^/]+/buckets/[^/]+)(?:/.*)?$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("bucket"): + header_params["bucket"] = regex_match.group("bucket") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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, + storage_control.RapidCache, + metadata_type=storage_control.DisableRapidCacheMetadata, + ) + + # Done; return the response. + return response + def get_rapid_cache( self, request: Optional[Union[storage_control.GetRapidCacheRequest, dict]] = None, 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 41f0f0c7ee92..e2b5851b97a4 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 @@ -435,6 +435,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.disable_rapid_cache: gapic_v1.method.wrap_method( + self.disable_rapid_cache, + default_timeout=None, + client_info=client_info, + ), self.get_rapid_cache: gapic_v1.method.wrap_method( self.get_rapid_cache, default_timeout=None, @@ -866,6 +871,15 @@ def update_rapid_cache( ]: raise NotImplementedError() + @property + def disable_rapid_cache( + self, + ) -> Callable[ + [storage_control.DisableRapidCacheRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def get_rapid_cache( self, 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 5e1791f9d586..097afedb456b 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 @@ -942,6 +942,32 @@ def update_rapid_cache( ) return self._stubs["update_rapid_cache"] + @property + def disable_rapid_cache( + self, + ) -> Callable[[storage_control.DisableRapidCacheRequest], operations_pb2.Operation]: + r"""Return a callable for the disable rapid cache method over gRPC. + + Disables a Rapid Cache instance. + + Returns: + Callable[[~.DisableRapidCacheRequest], + ~.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 "disable_rapid_cache" not in self._stubs: + self._stubs["disable_rapid_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DisableRapidCache", + request_serializer=storage_control.DisableRapidCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["disable_rapid_cache"] + @property def get_rapid_cache( self, 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 f00944f525df..831c69e59868 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 @@ -974,6 +974,34 @@ def update_rapid_cache( ) return self._stubs["update_rapid_cache"] + @property + def disable_rapid_cache( + self, + ) -> Callable[ + [storage_control.DisableRapidCacheRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the disable rapid cache method over gRPC. + + Disables a Rapid Cache instance. + + Returns: + Callable[[~.DisableRapidCacheRequest], + 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 "disable_rapid_cache" not in self._stubs: + self._stubs["disable_rapid_cache"] = self._logged_channel.unary_unary( + "/google.storage.control.v2.StorageControl/DisableRapidCache", + request_serializer=storage_control.DisableRapidCacheRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["disable_rapid_cache"] + @property def get_rapid_cache( self, @@ -1809,6 +1837,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.disable_rapid_cache: self._wrap_method( + self.disable_rapid_cache, + default_timeout=None, + client_info=client_info, + ), self.get_rapid_cache: self._wrap_method( self.get_rapid_cache, default_timeout=None, 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 6511a1d7626b..aa0846a0492c 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 @@ -131,6 +131,14 @@ def post_disable_anywhere_cache(self, response): logging.log(f"Received response: {response}") return response + def pre_disable_rapid_cache(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_rapid_cache(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_anywhere_cache(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1931,6 +1939,24 @@ def __call__( "Method DisableAnywhereCache is not available over REST transport" ) + class _DisableRapidCache( + _BaseStorageControlRestTransport._BaseDisableRapidCache, StorageControlRestStub + ): + def __hash__(self): + return hash("StorageControlRestTransport.DisableRapidCache") + + def __call__( + self, + request: storage_control.DisableRapidCacheRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + raise NotImplementedError( + "Method DisableRapidCache is not available over REST transport" + ) + class _GetAnywhereCache( _BaseStorageControlRestTransport._BaseGetAnywhereCache, StorageControlRestStub ): @@ -4730,6 +4756,14 @@ def disable_anywhere_cache( # In C++ this would require a dynamic_cast return self._DisableAnywhereCache(self._session, self._host, self._interceptor) # type: ignore + @property + def disable_rapid_cache( + self, + ) -> Callable[[storage_control.DisableRapidCacheRequest], 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._DisableRapidCache(self._session, self._host, self._interceptor) # type: ignore + @property def get_anywhere_cache( 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 558f4f646d75..c1dc159bb819 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 @@ -274,6 +274,10 @@ class _BaseDisableAnywhereCache: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + class _BaseDisableRapidCache: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + class _BaseGetAnywhereCache: 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 da2c4c3eed4c..43bd02b15741 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 @@ -27,6 +27,8 @@ DeleteFolderRequest, DeleteManagedFolderRequest, DisableAnywhereCacheRequest, + DisableRapidCacheMetadata, + DisableRapidCacheRequest, FindingCategory, FindingSeverity, FindingSummary, @@ -93,6 +95,8 @@ "DeleteFolderRequest", "DeleteManagedFolderRequest", "DisableAnywhereCacheRequest", + "DisableRapidCacheMetadata", + "DisableRapidCacheRequest", "FindingSummary", "Folder", "GetAnywhereCacheRequest", 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 62055113d00d..00b6813b5294 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 @@ -56,6 +56,7 @@ "CreateRapidCacheMetadata", "UpdateAnywhereCacheMetadata", "UpdateRapidCacheMetadata", + "DisableRapidCacheMetadata", "AnywhereCache", "CreateAnywhereCacheRequest", "UpdateAnywhereCacheRequest", @@ -68,6 +69,7 @@ "RapidCache", "CreateRapidCacheRequest", "UpdateRapidCacheRequest", + "DisableRapidCacheRequest", "GetRapidCacheRequest", "ListRapidCachesRequest", "ListRapidCachesResponse", @@ -1547,6 +1549,55 @@ class UpdateRapidCacheMetadata(proto.Message): ) +class DisableRapidCacheMetadata(proto.Message): + r"""Message returned in the metadata field of the Operation + resource for DeleteRapidCache operation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + common_metadata (google.cloud.storage_control_v2.types.CommonLongRunningOperationMetadata): + Generic metadata for the long running + operation. + rapid_cache_id (str): + Rapid Cache ID. + + This field is a member of `oneof`_ ``_rapid_cache_id``. + zone (str): + The zone in which the cache instance is + running. For example, us-central1-a. + + This field is a member of `oneof`_ ``_zone``. + cache_type (str): + Optional. The type of cache. Either rapid + cache or rapid cache ultra. + + This field is a member of `oneof`_ ``_cache_type``. + """ + + common_metadata: "CommonLongRunningOperationMetadata" = proto.Field( + proto.MESSAGE, + number=1, + message="CommonLongRunningOperationMetadata", + ) + rapid_cache_id: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + cache_type: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + class AnywhereCache(proto.Message): r"""An Anywhere Cache Instance. @@ -2024,6 +2075,30 @@ class UpdateRapidCacheRequest(proto.Message): ) +class DisableRapidCacheRequest(proto.Message): + r"""Request message for DisableRapidCache. + + Attributes: + name (str): + Required. The name field in the request should be: + ``projects/{project}/buckets/{bucket}/rapidCaches/{rapid_cache}`` + request_id (str): + Optional. A unique identifier for this request. UUID is the + recommended format, but other formats are still accepted. + This request is only idempotent if a ``request_id`` is + provided. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + class GetRapidCacheRequest(proto.Message): r"""Request message for GetRapidCache. 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 2357e70ae448..69b59832d14b 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 @@ -1335,6 +1335,167 @@ ], "title": "storage_v2_generated_storage_control_disable_anywhere_cache_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient", + "shortName": "StorageControlAsyncClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlAsyncClient.disable_rapid_cache", + "method": { + "fullName": "google.storage.control.v2.StorageControl.DisableRapidCache", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "DisableRapidCache" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.DisableRapidCacheRequest" + }, + { + "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": "disable_rapid_cache" + }, + "description": "Sample for DisableRapidCache", + "file": "storage_v2_generated_storage_control_disable_rapid_cache_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_DisableRapidCache_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": "storage_v2_generated_storage_control_disable_rapid_cache_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.storage_control_v2.StorageControlClient", + "shortName": "StorageControlClient" + }, + "fullName": "google.cloud.storage_control_v2.StorageControlClient.disable_rapid_cache", + "method": { + "fullName": "google.storage.control.v2.StorageControl.DisableRapidCache", + "service": { + "fullName": "google.storage.control.v2.StorageControl", + "shortName": "StorageControl" + }, + "shortName": "DisableRapidCache" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.storage_control_v2.types.DisableRapidCacheRequest" + }, + { + "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": "disable_rapid_cache" + }, + "description": "Sample for DisableRapidCache", + "file": "storage_v2_generated_storage_control_disable_rapid_cache_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "storage_v2_generated_StorageControl_DisableRapidCache_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": "storage_v2_generated_storage_control_disable_rapid_cache_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_async.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_async.py new file mode 100644 index 000000000000..3a0761576726 --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_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 DisableRapidCache +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_DisableRapidCache_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_disable_rapid_cache(): + # Create a client + client = storage_control_v2.StorageControlAsyncClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableRapidCacheRequest( + name="name_value", + ) + + # Make the request + operation = await client.disable_rapid_cache(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_DisableRapidCache_async] diff --git a/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_sync.py b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_sync.py new file mode 100644 index 000000000000..1c990ec0fc2b --- /dev/null +++ b/packages/google-cloud-storage-control/samples/generated_samples/storage_v2_generated_storage_control_disable_rapid_cache_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 DisableRapidCache +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It 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_DisableRapidCache_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_disable_rapid_cache(): + # Create a client + client = storage_control_v2.StorageControlClient() + + # Initialize request argument(s) + request = storage_control_v2.DisableRapidCacheRequest( + name="name_value", + ) + + # Make the request + operation = client.disable_rapid_cache(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END storage_v2_generated_StorageControl_DisableRapidCache_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 0a5e9213d350..12c0539644df 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 @@ -8374,6 +8374,287 @@ async def test_update_rapid_cache_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + storage_control.DisableRapidCacheRequest(), + {}, + ], +) +def test_disable_rapid_cache(request_type, transport: str = "grpc"): + client = StorageControlClient( + 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.disable_rapid_cache), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.disable_rapid_cache(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = storage_control.DisableRapidCacheRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_disable_rapid_cache_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", + ) + + # 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.DisableRapidCacheRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_rapid_cache), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.disable_rapid_cache(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableRapidCacheRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_disable_rapid_cache_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached 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() + + # Ensure method has been cached + assert ( + client._transport.disable_rapid_cache in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.disable_rapid_cache] = ( + mock_rpc + ) + request = {} + client.disable_rapid_cache(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.disable_rapid_cache(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_disable_rapid_cache_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() + + # Ensure method has been cached + assert ( + client._client._transport.disable_rapid_cache + 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.disable_rapid_cache + ] = mock_rpc + + request = {} + await client.disable_rapid_cache(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.disable_rapid_cache(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", + [ + storage_control.DisableRapidCacheRequest(), + {}, + ], +) +async def test_disable_rapid_cache_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.disable_rapid_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") + ) + response = await client.disable_rapid_cache(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = storage_control.DisableRapidCacheRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_disable_rapid_cache_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.disable_rapid_cache), "__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.disable_rapid_cache( + 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_disable_rapid_cache_flattened_error(): + client = StorageControlClient( + 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.disable_rapid_cache( + storage_control.DisableRapidCacheRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_rapid_cache_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.disable_rapid_cache), "__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.disable_rapid_cache( + 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_disable_rapid_cache_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.disable_rapid_cache( + storage_control.DisableRapidCacheRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ @@ -16498,6 +16779,16 @@ def test_update_rapid_cache_rest_no_http_options(): client.update_rapid_cache(request) +def test_disable_rapid_cache_rest_no_http_options(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = storage_control.DisableRapidCacheRequest() + with pytest.raises(RuntimeError): + client.disable_rapid_cache(request) + + def test_get_rapid_cache_rest_no_http_options(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19345,6 +19636,19 @@ def test_update_rapid_cache_rest_error(): ) +def test_disable_rapid_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_rapid_cache({}) + assert "Method DisableRapidCache is not available over REST transport" in str( + not_implemented_error.value + ) + + def test_get_rapid_cache_rest_error(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -20019,6 +20323,28 @@ def test_update_rapid_cache_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_disable_rapid_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_rapid_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_rapid_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableRapidCacheRequest() + assert args[0] == request_msg + + # This 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_rapid_cache_empty_call_grpc(): @@ -21017,6 +21343,35 @@ def test_update_rapid_cache_routing_parameters_request_1_grpc(): ) +def test_disable_rapid_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_rapid_cache), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.disable_rapid_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.DisableRapidCacheRequest( + **{"name": "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_rapid_cache_routing_parameters_request_1_grpc(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21935,6 +22290,32 @@ async def test_update_rapid_cache_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_disable_rapid_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_rapid_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.disable_rapid_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableRapidCacheRequest() + assert args[0] == request_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 @@ -23191,6 +23572,39 @@ async def test_update_rapid_cache_routing_parameters_request_1_grpc_asyncio(): ) +@pytest.mark.asyncio +async def test_disable_rapid_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_rapid_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.disable_rapid_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.DisableRapidCacheRequest( + **{"name": "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_get_rapid_cache_routing_parameters_request_1_grpc_asyncio(): client = StorageControlAsyncClient( @@ -24672,6 +25086,18 @@ def test_update_rapid_cache_rest_error(): ) +def test_disable_rapid_cache_rest_error(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.disable_rapid_cache({}) + assert "Method DisableRapidCache is not available over REST transport" in str( + not_implemented_error.value + ) + + def test_get_rapid_cache_rest_error(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -27226,6 +27652,27 @@ def test_update_rapid_cache_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_disable_rapid_cache_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.disable_rapid_cache), "__call__" + ) as call: + client.disable_rapid_cache(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = storage_control.DisableRapidCacheRequest() + assert args[0] == request_msg + + # This 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_rapid_cache_empty_call_rest(): @@ -28186,6 +28633,34 @@ def test_update_rapid_cache_routing_parameters_request_1_rest(): ) +def test_disable_rapid_cache_routing_parameters_request_1_rest(): + client = StorageControlClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_rapid_cache), "__call__" + ) as call: + client.disable_rapid_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.DisableRapidCacheRequest( + **{"name": "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_rapid_cache_routing_parameters_request_1_rest(): client = StorageControlClient( credentials=ga_credentials.AnonymousCredentials(), @@ -28515,6 +28990,7 @@ def test_storage_control_base_transport(): "list_anywhere_caches", "create_rapid_cache", "update_rapid_cache", + "disable_rapid_cache", "get_rapid_cache", "list_rapid_caches", "get_project_intelligence_config", @@ -28889,6 +29365,9 @@ def test_storage_control_client_transport_session_collision(transport_name): session1 = client1.transport.update_rapid_cache._session session2 = client2.transport.update_rapid_cache._session assert session1 != session2 + session1 = client1.transport.disable_rapid_cache._session + session2 = client2.transport.disable_rapid_cache._session + assert session1 != session2 session1 = client1.transport.get_rapid_cache._session session2 = client2.transport.get_rapid_cache._session assert session1 != session2 diff --git a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/async_client.py b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/async_client.py index 4fe8484958d3..2069e858929e 100644 --- a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/async_client.py +++ b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/async_client.py @@ -474,6 +474,10 @@ async def sample_get_document(): Example: ``documents/docs.cloud.google.com/storage/docs/creating-buckets`` + The name must not exceed 500 characters; values longer + than 500 characters will result in an + ``INVALID_ARGUMENT`` error. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -487,9 +491,10 @@ async def sample_get_document(): Returns: google.developer_knowledge_v1.types.Document: - A Document represents a piece of - content from the Developer Knowledge - corpus. + A Document represents a page of + documentation in the Developer Knowledge + corpus, like the page at + https://docs.cloud.google.com/storage/docs/creating-buckets. """ # Create or coerce a protobuf request object. diff --git a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/client.py b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/client.py index 529e50faf03e..5726bc43a384 100644 --- a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/client.py +++ b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/client.py @@ -898,6 +898,10 @@ def sample_get_document(): Example: ``documents/docs.cloud.google.com/storage/docs/creating-buckets`` + The name must not exceed 500 characters; values longer + than 500 characters will result in an + ``INVALID_ARGUMENT`` error. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -911,9 +915,10 @@ def sample_get_document(): Returns: google.developer_knowledge_v1.types.Document: - A Document represents a piece of - content from the Developer Knowledge - corpus. + A Document represents a page of + documentation in the Developer Knowledge + corpus, like the page at + https://docs.cloud.google.com/storage/docs/creating-buckets. """ # Create or coerce a protobuf request object. diff --git a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/transports/rest.py b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/transports/rest.py index 7c81cefd4251..de116aef8431 100644 --- a/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/transports/rest.py +++ b/packages/google-developer-knowledge/google/developer_knowledge_v1/services/developer_knowledge/transports/rest.py @@ -777,9 +777,10 @@ def __call__( Returns: ~.developerknowledge.Document: - A Document represents a piece of - content from the Developer Knowledge - corpus. + A Document represents a page of + documentation in the Developer Knowledge + corpus, like the page at + https://docs.cloud.google.com/storage/docs/creating-buckets. """ diff --git a/packages/google-developer-knowledge/google/developer_knowledge_v1/types/developerknowledge.py b/packages/google-developer-knowledge/google/developer_knowledge_v1/types/developerknowledge.py index 88ac00058ec9..d67a601dc35b 100644 --- a/packages/google-developer-knowledge/google/developer_knowledge_v1/types/developerknowledge.py +++ b/packages/google-developer-knowledge/google/developer_knowledge_v1/types/developerknowledge.py @@ -82,8 +82,9 @@ class DocumentView(proto.Enum): class Document(proto.Message): - r"""A Document represents a piece of content from the Developer - Knowledge corpus. + r"""A Document represents a page of documentation in the + Developer Knowledge corpus, like the page at + https://docs.cloud.google.com/storage/docs/creating-buckets. Attributes: name (str): @@ -163,9 +164,10 @@ class SearchDocumentChunksRequest(proto.Message): Attributes: query (str): - Required. Provides the raw query string - provided by the user, such as "How to create a - Cloud Storage bucket?". + Required. Provides the raw query string provided by the + user, such as "How to create a Cloud Storage bucket?". The + query must not exceed 500 characters; values longer than 500 + characters will result in an ``INVALID_ARGUMENT`` error. page_size (int): Optional. Specifies the maximum number of results to return. The service may return fewer @@ -191,6 +193,8 @@ class SearchDocumentChunksRequest(proto.Message): Supported fields for filtering: + - ``content_length_bytes`` (INTEGER): The length of the + ``Document.content`` field in bytes. - ``data_source`` (STRING): The source of the document, e.g. ``docs.cloud.google.com``. See https://developers.google.com/knowledge/reference/corpus-reference @@ -202,6 +206,9 @@ class SearchDocumentChunksRequest(proto.Message): - ``uri`` (STRING): The document URI, e.g. ``https://docs.cloud.google.com/bigquery/docs/tables``. + INTEGER fields support ``=``, ``<``, ``<=``, ``>``, and + ``>=`` operators. + STRING fields support ``=`` (equals) and ``!=`` (not equals) operators for **exact match** on the whole string. Partial match, prefix match, and regexp match are not supported. @@ -222,6 +229,8 @@ class SearchDocumentChunksRequest(proto.Message): Examples: + - Filter by ``Document.content_length_bytes``: + ``content_length_bytes < 50000`` - ``data_source = "docs.cloud.google.com" OR data_source = "firebase.google.com"`` - ``data_source != "firebase.google.com"`` - ``update_time < "2024-01-01T00:00:00Z"`` @@ -268,9 +277,9 @@ class SearchDocumentChunksResponse(proto.Message): [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments] to retrieve the full document content. next_page_token (str): - Optional. Provides a token that can be sent as - ``page_token`` to retrieve the next page. If this field is - omitted, there are no subsequent pages. + Provides a token that can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. """ @property @@ -297,6 +306,9 @@ class GetDocumentRequest(proto.Message): Required. Specifies the name of the document to retrieve. Format: ``documents/{uri_without_scheme}`` Example: ``documents/docs.cloud.google.com/storage/docs/creating-buckets`` + + The name must not exceed 500 characters; values longer than + 500 characters will result in an ``INVALID_ARGUMENT`` error. view (google.developer_knowledge_v1.types.DocumentView): Optional. Specifies the [DocumentView][google.developers.knowledge.v1.DocumentView] @@ -329,6 +341,9 @@ class BatchGetDocumentsRequest(proto.Message): Format: ``documents/{uri_without_scheme}`` Example: ``documents/docs.cloud.google.com/storage/docs/creating-buckets`` + + Each name must not exceed 500 characters; values longer than + 500 characters will result in an ``INVALID_ARGUMENT`` error. view (google.developer_knowledge_v1.types.DocumentView): Optional. Specifies the [DocumentView][google.developers.knowledge.v1.DocumentView] @@ -518,6 +533,9 @@ class DocumentChunk(proto.Message): or [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments]. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: parent (str): Output only. Contains the resource name of the document this @@ -551,6 +569,12 @@ class DocumentChunk(proto.Message): or [DeveloperKnowledge.BatchGetDocuments][google.developers.knowledge.v1.DeveloperKnowledge.BatchGetDocuments] to fetch the full document content. + relevance_score (float): + Output only. Represents the relevance score of the chunk to + the search query. Higher score indicates higher chunk + relevance. The score is in range [0.0, 1.0]. + + This field is a member of `oneof`_ ``_relevance_score``. """ parent: str = proto.Field( @@ -570,6 +594,11 @@ class DocumentChunk(proto.Message): number=4, message="Document", ) + relevance_score: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-areainsights/google/maps/areainsights_v1/types/area_insights_service.py b/packages/google-maps-areainsights/google/maps/areainsights_v1/types/area_insights_service.py index 41418d6d0056..259802d5a22b 100644 --- a/packages/google-maps-areainsights/google/maps/areainsights_v1/types/area_insights_service.py +++ b/packages/google-maps-areainsights/google/maps/areainsights_v1/types/area_insights_service.py @@ -376,8 +376,14 @@ class Region(proto.Message): Attributes: place (str): - The unique identifier of a specific - geographic region. + The `place + ID `__ + of the geographic region. Not all region types are + supported; see documentation for details. + + **Format:** Must be in the format ``places/PLACE_ID``, where + ``PLACE_ID`` is the unique identifier of a place. For + example: ``places/ChIJPV4oX_65j4ARVW8IJ6IJUYs``. This field is a member of `oneof`_ ``region``. """ diff --git a/packages/google-maps-mapmanagement/docs/index.rst b/packages/google-maps-mapmanagement/docs/index.rst index 2de3f530cd28..0fab87cae7f2 100644 --- a/packages/google-maps-mapmanagement/docs/index.rst +++ b/packages/google-maps-mapmanagement/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Map Management. +By default, you will get version ``mapmanagement_v2beta``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference mapmanagement_v2beta/services_ mapmanagement_v2beta/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + mapmanagement_v2/services_ + mapmanagement_v2/types_ + Changelog --------- diff --git a/packages/google-maps-mapmanagement/docs/mapmanagement_v2/map_management.rst b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/map_management.rst new file mode 100644 index 000000000000..13e12113500d --- /dev/null +++ b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/map_management.rst @@ -0,0 +1,10 @@ +MapManagement +------------------------------- + +.. automodule:: google.maps.mapmanagement_v2.services.map_management + :members: + :inherited-members: + +.. automodule:: google.maps.mapmanagement_v2.services.map_management.pagers + :members: + :inherited-members: diff --git a/packages/google-maps-mapmanagement/docs/mapmanagement_v2/services_.rst b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/services_.rst new file mode 100644 index 000000000000..4b5b8c3c70a9 --- /dev/null +++ b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Mapmanagement v2 API +============================================= +.. toctree:: + :maxdepth: 2 + + map_management diff --git a/packages/google-maps-mapmanagement/docs/mapmanagement_v2/types_.rst b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/types_.rst new file mode 100644 index 000000000000..32e5c7223308 --- /dev/null +++ b/packages/google-maps-mapmanagement/docs/mapmanagement_v2/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Mapmanagement v2 API +========================================== + +.. automodule:: google.maps.mapmanagement_v2.types + :members: + :show-inheritance: diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/__init__.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/__init__.py new file mode 100644 index 000000000000..50a563a6b29e --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/__init__.py @@ -0,0 +1,176 @@ +# -*- 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 sys + +import google.api_core as api_core + +from google.maps.mapmanagement_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + +from importlib import metadata + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__ = { + "google.maps.mapmanagement_v2.services.map_management", + "google.maps.mapmanagement_v2.types.map_management_service", +} + + +from .services.map_management import MapManagementAsyncClient, MapManagementClient +from .types.map_management_service import ( + CreateMapConfigRequest, + CreateMapContextConfigRequest, + CreateStyleConfigRequest, + DeleteMapConfigRequest, + DeleteMapContextConfigRequest, + DeleteStyleConfigRequest, + GetMapConfigRequest, + GetMapContextConfigRequest, + GetStyleConfigRequest, + ListMapConfigsRequest, + ListMapConfigsResponse, + ListMapContextConfigsRequest, + ListMapContextConfigsResponse, + ListStyleConfigsRequest, + ListStyleConfigsResponse, + MapConfig, + MapContextConfig, + MapFeatures, + MapRenderingType, + StyleConfig, + StyleConfigView, + UpdateMapConfigRequest, + UpdateMapContextConfigRequest, + UpdateStyleConfigRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.maps.mapmanagement_v2") # type: ignore + api_core.check_dependency_versions("google.maps.mapmanagement_v2") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.maps.mapmanagement_v2" + if sys.version_info < (3, 10): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "6.33.5" -> (6, 33, 5) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "6.33.5" + _next_supported_version_tuple = (6, 33, 5) + _recommendation = " (we recommend 7.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "MapManagementAsyncClient", + "CreateMapConfigRequest", + "CreateMapContextConfigRequest", + "CreateStyleConfigRequest", + "DeleteMapConfigRequest", + "DeleteMapContextConfigRequest", + "DeleteStyleConfigRequest", + "GetMapConfigRequest", + "GetMapContextConfigRequest", + "GetStyleConfigRequest", + "ListMapConfigsRequest", + "ListMapConfigsResponse", + "ListMapContextConfigsRequest", + "ListMapContextConfigsResponse", + "ListStyleConfigsRequest", + "ListStyleConfigsResponse", + "MapConfig", + "MapContextConfig", + "MapFeatures", + "MapManagementClient", + "MapRenderingType", + "StyleConfig", + "StyleConfigView", + "UpdateMapConfigRequest", + "UpdateMapContextConfigRequest", + "UpdateStyleConfigRequest", +) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_metadata.json b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_metadata.json new file mode 100644 index 000000000000..baa92d5c79ba --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_metadata.json @@ -0,0 +1,253 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.mapmanagement_v2", + "protoPackage": "google.maps.mapmanagement.v2", + "schema": "1.0", + "services": { + "MapManagement": { + "clients": { + "grpc": { + "libraryClient": "MapManagementClient", + "rpcs": { + "CreateMapConfig": { + "methods": [ + "create_map_config" + ] + }, + "CreateMapContextConfig": { + "methods": [ + "create_map_context_config" + ] + }, + "CreateStyleConfig": { + "methods": [ + "create_style_config" + ] + }, + "DeleteMapConfig": { + "methods": [ + "delete_map_config" + ] + }, + "DeleteMapContextConfig": { + "methods": [ + "delete_map_context_config" + ] + }, + "DeleteStyleConfig": { + "methods": [ + "delete_style_config" + ] + }, + "GetMapConfig": { + "methods": [ + "get_map_config" + ] + }, + "GetMapContextConfig": { + "methods": [ + "get_map_context_config" + ] + }, + "GetStyleConfig": { + "methods": [ + "get_style_config" + ] + }, + "ListMapConfigs": { + "methods": [ + "list_map_configs" + ] + }, + "ListMapContextConfigs": { + "methods": [ + "list_map_context_configs" + ] + }, + "ListStyleConfigs": { + "methods": [ + "list_style_configs" + ] + }, + "UpdateMapConfig": { + "methods": [ + "update_map_config" + ] + }, + "UpdateMapContextConfig": { + "methods": [ + "update_map_context_config" + ] + }, + "UpdateStyleConfig": { + "methods": [ + "update_style_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "MapManagementAsyncClient", + "rpcs": { + "CreateMapConfig": { + "methods": [ + "create_map_config" + ] + }, + "CreateMapContextConfig": { + "methods": [ + "create_map_context_config" + ] + }, + "CreateStyleConfig": { + "methods": [ + "create_style_config" + ] + }, + "DeleteMapConfig": { + "methods": [ + "delete_map_config" + ] + }, + "DeleteMapContextConfig": { + "methods": [ + "delete_map_context_config" + ] + }, + "DeleteStyleConfig": { + "methods": [ + "delete_style_config" + ] + }, + "GetMapConfig": { + "methods": [ + "get_map_config" + ] + }, + "GetMapContextConfig": { + "methods": [ + "get_map_context_config" + ] + }, + "GetStyleConfig": { + "methods": [ + "get_style_config" + ] + }, + "ListMapConfigs": { + "methods": [ + "list_map_configs" + ] + }, + "ListMapContextConfigs": { + "methods": [ + "list_map_context_configs" + ] + }, + "ListStyleConfigs": { + "methods": [ + "list_style_configs" + ] + }, + "UpdateMapConfig": { + "methods": [ + "update_map_config" + ] + }, + "UpdateMapContextConfig": { + "methods": [ + "update_map_context_config" + ] + }, + "UpdateStyleConfig": { + "methods": [ + "update_style_config" + ] + } + } + }, + "rest": { + "libraryClient": "MapManagementClient", + "rpcs": { + "CreateMapConfig": { + "methods": [ + "create_map_config" + ] + }, + "CreateMapContextConfig": { + "methods": [ + "create_map_context_config" + ] + }, + "CreateStyleConfig": { + "methods": [ + "create_style_config" + ] + }, + "DeleteMapConfig": { + "methods": [ + "delete_map_config" + ] + }, + "DeleteMapContextConfig": { + "methods": [ + "delete_map_context_config" + ] + }, + "DeleteStyleConfig": { + "methods": [ + "delete_style_config" + ] + }, + "GetMapConfig": { + "methods": [ + "get_map_config" + ] + }, + "GetMapContextConfig": { + "methods": [ + "get_map_context_config" + ] + }, + "GetStyleConfig": { + "methods": [ + "get_style_config" + ] + }, + "ListMapConfigs": { + "methods": [ + "list_map_configs" + ] + }, + "ListMapContextConfigs": { + "methods": [ + "list_map_context_configs" + ] + }, + "ListStyleConfigs": { + "methods": [ + "list_style_configs" + ] + }, + "UpdateMapConfig": { + "methods": [ + "update_map_config" + ] + }, + "UpdateMapContextConfig": { + "methods": [ + "update_map_context_config" + ] + }, + "UpdateStyleConfig": { + "methods": [ + "update_style_config" + ] + } + } + } + } + } + } +} diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_version.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_version.py new file mode 100644 index 000000000000..075b8773ece3 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/py.typed b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/py.typed new file mode 100644 index 000000000000..5f145cf0cb15 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-mapmanagement package uses inline types. diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/__init__.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/__init__.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/__init__.py new file mode 100644 index 000000000000..ac3105eaf740 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/__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 MapManagementAsyncClient +from .client import MapManagementClient + +__all__ = ( + "MapManagementClient", + "MapManagementAsyncClient", +) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/async_client.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/async_client.py new file mode 100644 index 000000000000..7edfa668f497 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/async_client.py @@ -0,0 +1,2196 @@ +# -*- 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.maps.mapmanagement_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +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.maps.mapmanagement_v2.services.map_management import pagers +from google.maps.mapmanagement_v2.types import map_management_service + +from .client import MapManagementClient +from .transports.base import DEFAULT_CLIENT_INFO, MapManagementTransport +from .transports.grpc_asyncio import MapManagementGrpcAsyncIOTransport + +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 MapManagementAsyncClient: + """The Map Management API uses your inputs to create and manage Google + Cloud based styling resources for Google Maps. + + Using this API, you can can create and manage MapConfigs (Map IDs), + StyleConfigs (JSON-based styling), and MapContextConfigs + (associations between styles, datasets, and map variants). + + This API offers features through three channels: + + - ``v2alpha``: Experimental features. + - ``v2beta``: Preview features, recommended for early adoption. + - ``v2``: General Availability (GA) features. + + Capabilities described here are generally available across both the + v2alpha and v2beta endpoints. + """ + + _client: MapManagementClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = MapManagementClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = MapManagementClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = MapManagementClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = MapManagementClient._DEFAULT_UNIVERSE + + dataset_path = staticmethod(MapManagementClient.dataset_path) + parse_dataset_path = staticmethod(MapManagementClient.parse_dataset_path) + map_config_path = staticmethod(MapManagementClient.map_config_path) + parse_map_config_path = staticmethod(MapManagementClient.parse_map_config_path) + map_context_config_path = staticmethod(MapManagementClient.map_context_config_path) + parse_map_context_config_path = staticmethod( + MapManagementClient.parse_map_context_config_path + ) + style_config_path = staticmethod(MapManagementClient.style_config_path) + parse_style_config_path = staticmethod(MapManagementClient.parse_style_config_path) + common_billing_account_path = staticmethod( + MapManagementClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + MapManagementClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(MapManagementClient.common_folder_path) + parse_common_folder_path = staticmethod( + MapManagementClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + MapManagementClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + MapManagementClient.parse_common_organization_path + ) + common_project_path = staticmethod(MapManagementClient.common_project_path) + parse_common_project_path = staticmethod( + MapManagementClient.parse_common_project_path + ) + common_location_path = staticmethod(MapManagementClient.common_location_path) + parse_common_location_path = staticmethod( + MapManagementClient.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: + MapManagementAsyncClient: The constructed client. + """ + sa_info_func = ( + MapManagementClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(MapManagementAsyncClient, 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: + MapManagementAsyncClient: The constructed client. + """ + sa_file_func = ( + MapManagementClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(MapManagementAsyncClient, 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 MapManagementClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> MapManagementTransport: + """Returns the transport used by the client instance. + + Returns: + MapManagementTransport: 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 = MapManagementClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, MapManagementTransport, Callable[..., MapManagementTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the map management 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,MapManagementTransport,Callable[..., MapManagementTransport]]]): + 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 MapManagementTransport 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 = MapManagementClient( + 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.maps.mapmanagement_v2.MapManagementAsyncClient`.", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "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.maps.mapmanagement.v2.MapManagement", + "credentialsType": None, + }, + ) + + async def create_map_config( + self, + request: Optional[ + Union[map_management_service.CreateMapConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + map_config: Optional[map_management_service.MapConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapConfig: + r"""Creates a MapConfig in 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.maps import mapmanagement_v2 + + async def sample_create_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateMapConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.CreateMapConfigRequest, dict]]): + The request object. Request to create a MapConfig. + parent (:class:`str`): + Required. Parent project that will own the MapConfig. + Format: ``projects/{$my-project-id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + map_config (:class:`google.maps.mapmanagement_v2.types.MapConfig`): + Required. The MapConfig to create. + This corresponds to the ``map_config`` 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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, map_config] + 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, map_management_service.CreateMapConfigRequest): + request = map_management_service.CreateMapConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if map_config is not None: + request.map_config = map_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_map_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_map_config( + self, + request: Optional[ + Union[map_management_service.GetMapConfigRequest, 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]]] = (), + ) -> map_management_service.MapConfig: + r"""Gets a MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_get_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.GetMapConfigRequest, dict]]): + The request object. Request to get a MapConfig. + name (:class:`str`): + Required. Resource name of the MapConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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, map_management_service.GetMapConfigRequest): + request = map_management_service.GetMapConfigRequest(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_map_config + ] + + # 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_map_configs( + self, + request: Optional[ + Union[map_management_service.ListMapConfigsRequest, 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.ListMapConfigsAsyncPager: + r"""Lists MapConfigs 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.maps import mapmanagement_v2 + + async def sample_list_map_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.ListMapConfigsRequest, dict]]): + The request object. Request to list MapConfigs. + parent (:class:`str`): + Required. Parent project that owns the MapConfigs. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.mapmanagement_v2.services.map_management.pagers.ListMapConfigsAsyncPager: + Response to list MapConfigs. + + 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, map_management_service.ListMapConfigsRequest): + request = map_management_service.ListMapConfigsRequest(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_map_configs + ] + + # 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.ListMapConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_map_config( + self, + request: Optional[ + Union[map_management_service.UpdateMapConfigRequest, dict] + ] = None, + *, + map_config: Optional[map_management_service.MapConfig] = 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]]] = (), + ) -> map_management_service.MapConfig: + r"""Updates a MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_update_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateMapConfigRequest( + ) + + # Make the request + response = await client.update_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.UpdateMapConfigRequest, dict]]): + The request object. Request to update a MapConfig. + map_config (:class:`google.maps.mapmanagement_v2.types.MapConfig`): + Required. The MapConfig to update. + + The MapConfig's ``name`` field is used to identify the + MapConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``map_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The specific field to update for the + MapConfig. If not specified, the MapConfig will be + updated in its entirety. Valid fields are: + + - ``display_name`` + - ``description`` + - ``map_features`` + + 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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 = [map_config, 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, map_management_service.UpdateMapConfigRequest): + request = map_management_service.UpdateMapConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if map_config is not None: + request.map_config = map_config + 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_map_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("map_config.name", request.map_config.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_map_config( + self, + request: Optional[ + Union[map_management_service.DeleteMapConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = 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 MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_delete_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_map_config(request=request) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.DeleteMapConfigRequest, dict]]): + The request object. Request to delete a MapConfig. If the + MapConfig has any child + MapContextConfigs, those will be deleted + as well. + name (:class:`str`): + Required. Resource name of the MapConfig to delete. + Format: ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Optional. If set to true, any + MapContextConfigs from this MapConfig + will also be deleted. (Otherwise, the + request will only work if the MapConfig + has no MapContextConfigs.) + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, force] + 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, map_management_service.DeleteMapConfigRequest): + request = map_management_service.DeleteMapConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_map_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_style_config( + self, + request: Optional[ + Union[map_management_service.CreateStyleConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + style_config: Optional[map_management_service.StyleConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.StyleConfig: + r"""Creates a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_create_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateStyleConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.CreateStyleConfigRequest, dict]]): + The request object. Request to create a StyleConfig. + parent (:class:`str`): + Required. Parent project that will own the StyleConfig. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + style_config (:class:`google.maps.mapmanagement_v2.types.StyleConfig`): + Required. The StyleConfig to create. + This corresponds to the ``style_config`` 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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, style_config] + 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, map_management_service.CreateStyleConfigRequest): + request = map_management_service.CreateStyleConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if style_config is not None: + request.style_config = style_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_style_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_style_config( + self, + request: Optional[ + Union[map_management_service.GetStyleConfigRequest, 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]]] = (), + ) -> map_management_service.StyleConfig: + r"""Gets a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_get_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetStyleConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.GetStyleConfigRequest, dict]]): + The request object. Request to get a StyleConfig. + name (:class:`str`): + Required. Resource name of the StyleConfig. Format: + ``projects/{project}/styleConfigs/{style_config}`` + + 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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, map_management_service.GetStyleConfigRequest): + request = map_management_service.GetStyleConfigRequest(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_style_config + ] + + # 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_style_configs( + self, + request: Optional[ + Union[map_management_service.ListStyleConfigsRequest, 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.ListStyleConfigsAsyncPager: + r"""Lists StyleConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_list_style_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListStyleConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_style_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.ListStyleConfigsRequest, dict]]): + The request object. Request to list StyleConfigs. + parent (:class:`str`): + Required. Parent project that owns the StyleConfigs. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.mapmanagement_v2.services.map_management.pagers.ListStyleConfigsAsyncPager: + Response to list StyleConfigs. + + 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, map_management_service.ListStyleConfigsRequest): + request = map_management_service.ListStyleConfigsRequest(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_style_configs + ] + + # 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.ListStyleConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_style_config( + self, + request: Optional[ + Union[map_management_service.UpdateStyleConfigRequest, dict] + ] = None, + *, + style_config: Optional[map_management_service.StyleConfig] = 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]]] = (), + ) -> map_management_service.StyleConfig: + r"""Updates a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_update_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateStyleConfigRequest( + ) + + # Make the request + response = await client.update_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.UpdateStyleConfigRequest, dict]]): + The request object. Request to update a StyleConfig. + style_config (:class:`google.maps.mapmanagement_v2.types.StyleConfig`): + Required. The StyleConfig to update. + + The StyleConfig's ``name`` field is used to identify the + StyleConfig to update. Format: + ``projects/{project}/styleConfigs/{style_config}`` + + This corresponds to the ``style_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. If not + specified, the StyleConfig will be updated in its + entirety. Valid fields are: + + - ``display_name`` + - ``description`` + - ``json_style_sheet`` + + 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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 = [style_config, 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, map_management_service.UpdateStyleConfigRequest): + request = map_management_service.UpdateStyleConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if style_config is not None: + request.style_config = style_config + 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_style_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("style_config.name", request.style_config.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_style_config( + self, + request: Optional[ + Union[map_management_service.DeleteStyleConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_delete_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteStyleConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_style_config(request=request) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.DeleteStyleConfigRequest, dict]]): + The request object. Request to delete a StyleConfig. + name (:class:`str`): + Required. Resource name of the StyleConfig to delete. + Format: + ``projects/{project}/styleConfigs/{style_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, map_management_service.DeleteStyleConfigRequest): + request = map_management_service.DeleteStyleConfigRequest(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_style_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_map_context_config( + self, + request: Optional[ + Union[map_management_service.CreateMapContextConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + map_context_config: Optional[map_management_service.MapContextConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Creates a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_create_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ['PHOTOREALISTIC3D'] + + request = mapmanagement_v2.CreateMapContextConfigRequest( + parent="parent_value", + map_context_config=map_context_config, + ) + + # Make the request + response = await client.create_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.CreateMapContextConfigRequest, dict]]): + The request object. Request to create a MapContextConfig. + parent (:class:`str`): + Required. Parent MapConfig that will own the + MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + map_context_config (:class:`google.maps.mapmanagement_v2.types.MapContextConfig`): + Required. The MapContextConfig to + create. + + This corresponds to the ``map_context_config`` 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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, map_context_config] + 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, map_management_service.CreateMapContextConfigRequest + ): + request = map_management_service.CreateMapContextConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if map_context_config is not None: + request.map_context_config = map_context_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_map_context_config( + self, + request: Optional[ + Union[map_management_service.GetMapContextConfigRequest, 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]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Gets a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_get_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapContextConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.GetMapContextConfigRequest, dict]]): + The request object. Request to get a MapContextConfig. + name (:class:`str`): + Required. Resource name of the MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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, map_management_service.GetMapContextConfigRequest): + request = map_management_service.GetMapContextConfigRequest(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_map_context_config + ] + + # 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_map_context_configs( + self, + request: Optional[ + Union[map_management_service.ListMapContextConfigsRequest, 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.ListMapContextConfigsAsyncPager: + r"""Lists MapContextConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_list_map_context_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapContextConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_context_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.ListMapContextConfigsRequest, dict]]): + The request object. Request to list MapContextConfigs. + parent (:class:`str`): + Required. Parent MapConfig that owns the + MapContextConfigs. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + 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.maps.mapmanagement_v2.services.map_management.pagers.ListMapContextConfigsAsyncPager: + Response to list MapContextConfigs. + + 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, map_management_service.ListMapContextConfigsRequest): + request = map_management_service.ListMapContextConfigsRequest(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_map_context_configs + ] + + # 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.ListMapContextConfigsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_map_context_config( + self, + request: Optional[ + Union[map_management_service.UpdateMapContextConfigRequest, dict] + ] = None, + *, + map_context_config: Optional[map_management_service.MapContextConfig] = 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]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Updates a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_update_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ['PHOTOREALISTIC3D'] + + request = mapmanagement_v2.UpdateMapContextConfigRequest( + map_context_config=map_context_config, + ) + + # Make the request + response = await client.update_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.UpdateMapContextConfigRequest, dict]]): + The request object. Request to update a MapContextConfig. + map_context_config (:class:`google.maps.mapmanagement_v2.types.MapContextConfig`): + Required. The MapContextConfig to update. + + The MapContextConfig's ``name`` field is used to + identify the MapContextConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + This corresponds to the ``map_context_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. If not + specified, the MapContextConfig will be updated in its + entirety. Valid fields are: + + - ``display_name`` + - ``alias`` + - ``map_variants`` + - ``style_config`` + - ``dataset`` + + 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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 = [map_context_config, 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, map_management_service.UpdateMapContextConfigRequest + ): + request = map_management_service.UpdateMapContextConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if map_context_config is not None: + request.map_context_config = map_context_config + 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_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("map_context_config.name", request.map_context_config.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_map_context_config( + self, + request: Optional[ + Union[map_management_service.DeleteMapContextConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + async def sample_delete_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapContextConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_map_context_config(request=request) + + Args: + request (Optional[Union[google.maps.mapmanagement_v2.types.DeleteMapContextConfigRequest, dict]]): + The request object. Request to delete a MapContextConfig. + name (:class:`str`): + Required. Resource name of the MapContextConfig to + delete. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, map_management_service.DeleteMapContextConfigRequest + ): + request = map_management_service.DeleteMapContextConfigRequest(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_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "MapManagementAsyncClient": + 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__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("MapManagementAsyncClient",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/client.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/client.py new file mode 100644 index 000000000000..bc4b61190742 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/client.py @@ -0,0 +1,2644 @@ +# -*- 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.maps.mapmanagement_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +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.maps.mapmanagement_v2.services.map_management import pagers +from google.maps.mapmanagement_v2.types import map_management_service + +from .transports.base import DEFAULT_CLIENT_INFO, MapManagementTransport +from .transports.grpc import MapManagementGrpcTransport +from .transports.grpc_asyncio import MapManagementGrpcAsyncIOTransport +from .transports.rest import MapManagementRestTransport + + +class MapManagementClientMeta(type): + """Metaclass for the MapManagement 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[MapManagementTransport]] + _transport_registry["grpc"] = MapManagementGrpcTransport + _transport_registry["grpc_asyncio"] = MapManagementGrpcAsyncIOTransport + _transport_registry["rest"] = MapManagementRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[MapManagementTransport]: + """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 MapManagementClient(metaclass=MapManagementClientMeta): + """The Map Management API uses your inputs to create and manage Google + Cloud based styling resources for Google Maps. + + Using this API, you can can create and manage MapConfigs (Map IDs), + StyleConfigs (JSON-based styling), and MapContextConfigs + (associations between styles, datasets, and map variants). + + This API offers features through three channels: + + - ``v2alpha``: Experimental features. + - ``v2beta``: Preview features, recommended for early adoption. + - ``v2``: General Availability (GA) features. + + Capabilities described here are generally available across both the + v2alpha and v2beta endpoints. + """ + + @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 = "mapmanagement.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "mapmanagement.{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: + MapManagementClient: 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: + MapManagementClient: 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) -> MapManagementTransport: + """Returns the transport used by the client instance. + + Returns: + MapManagementTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def dataset_path( + project: str, + dataset: str, + ) -> str: + """Returns a fully-qualified dataset string.""" + return "projects/{project}/datasets/{dataset}".format( + project=project, + dataset=dataset, + ) + + @staticmethod + def parse_dataset_path(path: str) -> Dict[str, str]: + """Parses a dataset path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/datasets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def map_config_path( + project: str, + map_config: str, + ) -> str: + """Returns a fully-qualified map_config string.""" + return "projects/{project}/mapConfigs/{map_config}".format( + project=project, + map_config=map_config, + ) + + @staticmethod + def parse_map_config_path(path: str) -> Dict[str, str]: + """Parses a map_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/mapConfigs/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def map_context_config_path( + project: str, + map_config: str, + map_context_config: str, + ) -> str: + """Returns a fully-qualified map_context_config string.""" + return "projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}".format( + project=project, + map_config=map_config, + map_context_config=map_context_config, + ) + + @staticmethod + def parse_map_context_config_path(path: str) -> Dict[str, str]: + """Parses a map_context_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/mapConfigs/(?P.+?)/mapContextConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def style_config_path( + project: str, + style_config: str, + ) -> str: + """Returns a fully-qualified style_config string.""" + return "projects/{project}/styleConfigs/{style_config}".format( + project=project, + style_config=style_config, + ) + + @staticmethod + def parse_style_config_path(path: str) -> Dict[str, str]: + """Parses a style_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/styleConfigs/(?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 = MapManagementClient._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 = MapManagementClient._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 = MapManagementClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = MapManagementClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = MapManagementClient._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 = MapManagementClient._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, MapManagementTransport, Callable[..., MapManagementTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the map management 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,MapManagementTransport,Callable[..., MapManagementTransport]]]): + 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 MapManagementTransport 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 = ( + MapManagementClient._read_environment_variables() + ) + self._client_cert_source = MapManagementClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = MapManagementClient._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, MapManagementTransport) + if transport_provided: + # transport is a MapManagementTransport 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(MapManagementTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or MapManagementClient._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[MapManagementTransport], Callable[..., MapManagementTransport] + ] = ( + MapManagementClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., MapManagementTransport], 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.maps.mapmanagement_v2.MapManagementClient`.", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "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.maps.mapmanagement.v2.MapManagement", + "credentialsType": None, + }, + ) + + def create_map_config( + self, + request: Optional[ + Union[map_management_service.CreateMapConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + map_config: Optional[map_management_service.MapConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapConfig: + r"""Creates a MapConfig in 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.maps import mapmanagement_v2 + + def sample_create_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateMapConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.CreateMapConfigRequest, dict]): + The request object. Request to create a MapConfig. + parent (str): + Required. Parent project that will own the MapConfig. + Format: ``projects/{$my-project-id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + map_config (google.maps.mapmanagement_v2.types.MapConfig): + Required. The MapConfig to create. + This corresponds to the ``map_config`` 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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, map_config] + 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, map_management_service.CreateMapConfigRequest): + request = map_management_service.CreateMapConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if map_config is not None: + request.map_config = map_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_map_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_map_config( + self, + request: Optional[ + Union[map_management_service.GetMapConfigRequest, 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]]] = (), + ) -> map_management_service.MapConfig: + r"""Gets a MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_get_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.GetMapConfigRequest, dict]): + The request object. Request to get a MapConfig. + name (str): + Required. Resource name of the MapConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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, map_management_service.GetMapConfigRequest): + request = map_management_service.GetMapConfigRequest(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_map_config] + + # 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_map_configs( + self, + request: Optional[ + Union[map_management_service.ListMapConfigsRequest, 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.ListMapConfigsPager: + r"""Lists MapConfigs 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.maps import mapmanagement_v2 + + def sample_list_map_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.ListMapConfigsRequest, dict]): + The request object. Request to list MapConfigs. + parent (str): + Required. Parent project that owns the MapConfigs. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.mapmanagement_v2.services.map_management.pagers.ListMapConfigsPager: + Response to list MapConfigs. + + 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, map_management_service.ListMapConfigsRequest): + request = map_management_service.ListMapConfigsRequest(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_map_configs] + + # 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.ListMapConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_map_config( + self, + request: Optional[ + Union[map_management_service.UpdateMapConfigRequest, dict] + ] = None, + *, + map_config: Optional[map_management_service.MapConfig] = 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]]] = (), + ) -> map_management_service.MapConfig: + r"""Updates a MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_update_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateMapConfigRequest( + ) + + # Make the request + response = client.update_map_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.UpdateMapConfigRequest, dict]): + The request object. Request to update a MapConfig. + map_config (google.maps.mapmanagement_v2.types.MapConfig): + Required. The MapConfig to update. + + The MapConfig's ``name`` field is used to identify the + MapConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``map_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The specific field to update for the + MapConfig. If not specified, the MapConfig will be + updated in its entirety. Valid fields are: + + - ``display_name`` + - ``description`` + - ``map_features`` + + 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.maps.mapmanagement_v2.types.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + # 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 = [map_config, 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, map_management_service.UpdateMapConfigRequest): + request = map_management_service.UpdateMapConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if map_config is not None: + request.map_config = map_config + 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_map_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("map_config.name", request.map_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_map_config( + self, + request: Optional[ + Union[map_management_service.DeleteMapConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = 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 MapConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_delete_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_map_config(request=request) + + Args: + request (Union[google.maps.mapmanagement_v2.types.DeleteMapConfigRequest, dict]): + The request object. Request to delete a MapConfig. If the + MapConfig has any child + MapContextConfigs, those will be deleted + as well. + name (str): + Required. Resource name of the MapConfig to delete. + Format: ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Optional. If set to true, any + MapContextConfigs from this MapConfig + will also be deleted. (Otherwise, the + request will only work if the MapConfig + has no MapContextConfigs.) + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, force] + 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, map_management_service.DeleteMapConfigRequest): + request = map_management_service.DeleteMapConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_map_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_style_config( + self, + request: Optional[ + Union[map_management_service.CreateStyleConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + style_config: Optional[map_management_service.StyleConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.StyleConfig: + r"""Creates a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_create_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateStyleConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.CreateStyleConfigRequest, dict]): + The request object. Request to create a StyleConfig. + parent (str): + Required. Parent project that will own the StyleConfig. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + style_config (google.maps.mapmanagement_v2.types.StyleConfig): + Required. The StyleConfig to create. + This corresponds to the ``style_config`` 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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, style_config] + 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, map_management_service.CreateStyleConfigRequest): + request = map_management_service.CreateStyleConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if style_config is not None: + request.style_config = style_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_style_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_style_config( + self, + request: Optional[ + Union[map_management_service.GetStyleConfigRequest, 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]]] = (), + ) -> map_management_service.StyleConfig: + r"""Gets a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_get_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetStyleConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.GetStyleConfigRequest, dict]): + The request object. Request to get a StyleConfig. + name (str): + Required. Resource name of the StyleConfig. Format: + ``projects/{project}/styleConfigs/{style_config}`` + + 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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, map_management_service.GetStyleConfigRequest): + request = map_management_service.GetStyleConfigRequest(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_style_config] + + # 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_style_configs( + self, + request: Optional[ + Union[map_management_service.ListStyleConfigsRequest, 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.ListStyleConfigsPager: + r"""Lists StyleConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_list_style_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListStyleConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_style_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.ListStyleConfigsRequest, dict]): + The request object. Request to list StyleConfigs. + parent (str): + Required. Parent project that owns the StyleConfigs. + Format: ``projects/{project}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.maps.mapmanagement_v2.services.map_management.pagers.ListStyleConfigsPager: + Response to list StyleConfigs. + + 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, map_management_service.ListStyleConfigsRequest): + request = map_management_service.ListStyleConfigsRequest(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_style_configs] + + # 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.ListStyleConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_style_config( + self, + request: Optional[ + Union[map_management_service.UpdateStyleConfigRequest, dict] + ] = None, + *, + style_config: Optional[map_management_service.StyleConfig] = 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]]] = (), + ) -> map_management_service.StyleConfig: + r"""Updates a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_update_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateStyleConfigRequest( + ) + + # Make the request + response = client.update_style_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.UpdateStyleConfigRequest, dict]): + The request object. Request to update a StyleConfig. + style_config (google.maps.mapmanagement_v2.types.StyleConfig): + Required. The StyleConfig to update. + + The StyleConfig's ``name`` field is used to identify the + StyleConfig to update. Format: + ``projects/{project}/styleConfigs/{style_config}`` + + This corresponds to the ``style_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If not + specified, the StyleConfig will be updated in its + entirety. Valid fields are: + + - ``display_name`` + - ``description`` + - ``json_style_sheet`` + + 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.maps.mapmanagement_v2.types.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + # 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 = [style_config, 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, map_management_service.UpdateStyleConfigRequest): + request = map_management_service.UpdateStyleConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if style_config is not None: + request.style_config = style_config + 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_style_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("style_config.name", request.style_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_style_config( + self, + request: Optional[ + Union[map_management_service.DeleteStyleConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a StyleConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_delete_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteStyleConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_style_config(request=request) + + Args: + request (Union[google.maps.mapmanagement_v2.types.DeleteStyleConfigRequest, dict]): + The request object. Request to delete a StyleConfig. + name (str): + Required. Resource name of the StyleConfig to delete. + Format: + ``projects/{project}/styleConfigs/{style_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, map_management_service.DeleteStyleConfigRequest): + request = map_management_service.DeleteStyleConfigRequest(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_style_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_map_context_config( + self, + request: Optional[ + Union[map_management_service.CreateMapContextConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + map_context_config: Optional[map_management_service.MapContextConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Creates a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_create_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ['PHOTOREALISTIC3D'] + + request = mapmanagement_v2.CreateMapContextConfigRequest( + parent="parent_value", + map_context_config=map_context_config, + ) + + # Make the request + response = client.create_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.CreateMapContextConfigRequest, dict]): + The request object. Request to create a MapContextConfig. + parent (str): + Required. Parent MapConfig that will own the + MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + map_context_config (google.maps.mapmanagement_v2.types.MapContextConfig): + Required. The MapContextConfig to + create. + + This corresponds to the ``map_context_config`` 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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, map_context_config] + 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, map_management_service.CreateMapContextConfigRequest + ): + request = map_management_service.CreateMapContextConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if map_context_config is not None: + request.map_context_config = map_context_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_map_context_config( + self, + request: Optional[ + Union[map_management_service.GetMapContextConfigRequest, 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]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Gets a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_get_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapContextConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.GetMapContextConfigRequest, dict]): + The request object. Request to get a MapContextConfig. + name (str): + Required. Resource name of the MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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, map_management_service.GetMapContextConfigRequest): + request = map_management_service.GetMapContextConfigRequest(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_map_context_config] + + # 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_map_context_configs( + self, + request: Optional[ + Union[map_management_service.ListMapContextConfigsRequest, 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.ListMapContextConfigsPager: + r"""Lists MapContextConfigs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_list_map_context_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapContextConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_context_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.ListMapContextConfigsRequest, dict]): + The request object. Request to list MapContextConfigs. + parent (str): + Required. Parent MapConfig that owns the + MapContextConfigs. Format: + ``projects/{project}/mapConfigs/{map_config}`` + + 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.maps.mapmanagement_v2.services.map_management.pagers.ListMapContextConfigsPager: + Response to list MapContextConfigs. + + 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, map_management_service.ListMapContextConfigsRequest): + request = map_management_service.ListMapContextConfigsRequest(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_map_context_configs] + + # 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.ListMapContextConfigsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_map_context_config( + self, + request: Optional[ + Union[map_management_service.UpdateMapContextConfigRequest, dict] + ] = None, + *, + map_context_config: Optional[map_management_service.MapContextConfig] = 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]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Updates a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_update_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ['PHOTOREALISTIC3D'] + + request = mapmanagement_v2.UpdateMapContextConfigRequest( + map_context_config=map_context_config, + ) + + # Make the request + response = client.update_map_context_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.mapmanagement_v2.types.UpdateMapContextConfigRequest, dict]): + The request object. Request to update a MapContextConfig. + map_context_config (google.maps.mapmanagement_v2.types.MapContextConfig): + Required. The MapContextConfig to update. + + The MapContextConfig's ``name`` field is used to + identify the MapContextConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + This corresponds to the ``map_context_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If not + specified, the MapContextConfig will be updated in its + entirety. Valid fields are: + + - ``display_name`` + - ``alias`` + - ``map_variants`` + - ``style_config`` + - ``dataset`` + + 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.maps.mapmanagement_v2.types.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + # 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 = [map_context_config, 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, map_management_service.UpdateMapContextConfigRequest + ): + request = map_management_service.UpdateMapContextConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if map_context_config is not None: + request.map_context_config = map_context_config + 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_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("map_context_config.name", request.map_context_config.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_map_context_config( + self, + request: Optional[ + Union[map_management_service.DeleteMapContextConfigRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a MapContextConfig. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import mapmanagement_v2 + + def sample_delete_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapContextConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_map_context_config(request=request) + + Args: + request (Union[google.maps.mapmanagement_v2.types.DeleteMapContextConfigRequest, dict]): + The request object. Request to delete a MapContextConfig. + name (str): + Required. Resource name of the MapContextConfig to + delete. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, map_management_service.DeleteMapContextConfigRequest + ): + request = map_management_service.DeleteMapContextConfigRequest(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_map_context_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "MapManagementClient": + 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() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("MapManagementClient",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/pagers.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/pagers.py new file mode 100644 index 000000000000..9689f737d47b --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/pagers.py @@ -0,0 +1,519 @@ +# -*- 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.maps.mapmanagement_v2.types import map_management_service + + +class ListMapConfigsPager: + """A pager for iterating through ``list_map_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListMapConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``map_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMapConfigs`` requests and continue to iterate + through the ``map_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListMapConfigsResponse` + 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[..., map_management_service.ListMapConfigsResponse], + request: map_management_service.ListMapConfigsRequest, + response: map_management_service.ListMapConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListMapConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListMapConfigsResponse): + 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 = map_management_service.ListMapConfigsRequest(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[map_management_service.ListMapConfigsResponse]: + 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[map_management_service.MapConfig]: + for page in self.pages: + yield from page.map_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMapConfigsAsyncPager: + """A pager for iterating through ``list_map_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListMapConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``map_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMapConfigs`` requests and continue to iterate + through the ``map_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListMapConfigsResponse` + 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[map_management_service.ListMapConfigsResponse]], + request: map_management_service.ListMapConfigsRequest, + response: map_management_service.ListMapConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListMapConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListMapConfigsResponse): + 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 = map_management_service.ListMapConfigsRequest(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[map_management_service.ListMapConfigsResponse]: + 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[map_management_service.MapConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.map_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListStyleConfigsPager: + """A pager for iterating through ``list_style_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListStyleConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``style_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListStyleConfigs`` requests and continue to iterate + through the ``style_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListStyleConfigsResponse` + 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[..., map_management_service.ListStyleConfigsResponse], + request: map_management_service.ListStyleConfigsRequest, + response: map_management_service.ListStyleConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListStyleConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListStyleConfigsResponse): + 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 = map_management_service.ListStyleConfigsRequest(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[map_management_service.ListStyleConfigsResponse]: + 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[map_management_service.StyleConfig]: + for page in self.pages: + yield from page.style_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListStyleConfigsAsyncPager: + """A pager for iterating through ``list_style_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListStyleConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``style_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListStyleConfigs`` requests and continue to iterate + through the ``style_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListStyleConfigsResponse` + 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[map_management_service.ListStyleConfigsResponse] + ], + request: map_management_service.ListStyleConfigsRequest, + response: map_management_service.ListStyleConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListStyleConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListStyleConfigsResponse): + 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 = map_management_service.ListStyleConfigsRequest(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[map_management_service.ListStyleConfigsResponse]: + 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[map_management_service.StyleConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.style_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMapContextConfigsPager: + """A pager for iterating through ``list_map_context_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``map_context_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMapContextConfigs`` requests and continue to iterate + through the ``map_context_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse` + 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[..., map_management_service.ListMapContextConfigsResponse], + request: map_management_service.ListMapContextConfigsRequest, + response: map_management_service.ListMapContextConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListMapContextConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse): + 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 = map_management_service.ListMapContextConfigsRequest(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[map_management_service.ListMapContextConfigsResponse]: + 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[map_management_service.MapContextConfig]: + for page in self.pages: + yield from page.map_context_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMapContextConfigsAsyncPager: + """A pager for iterating through ``list_map_context_configs`` requests. + + This class thinly wraps an initial + :class:`google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``map_context_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMapContextConfigs`` requests and continue to iterate + through the ``map_context_configs`` field on the + corresponding responses. + + All the usual :class:`google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse` + 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[map_management_service.ListMapContextConfigsResponse] + ], + request: map_management_service.ListMapContextConfigsRequest, + response: map_management_service.ListMapContextConfigsResponse, + *, + 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.maps.mapmanagement_v2.types.ListMapContextConfigsRequest): + The initial request object. + response (google.maps.mapmanagement_v2.types.ListMapContextConfigsResponse): + 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 = map_management_service.ListMapContextConfigsRequest(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[map_management_service.ListMapContextConfigsResponse]: + 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[map_management_service.MapContextConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.map_context_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/README.rst b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/README.rst new file mode 100644 index 000000000000..d383f1d88b83 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``MapManagementTransport`` is the ABC for all transports. + +- public child ``MapManagementGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``MapManagementGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseMapManagementRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``MapManagementRestTransport`` 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-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/__init__.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/__init__.py new file mode 100644 index 000000000000..0321a937f3a1 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/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 MapManagementTransport +from .grpc import MapManagementGrpcTransport +from .grpc_asyncio import MapManagementGrpcAsyncIOTransport +from .rest import MapManagementRestInterceptor, MapManagementRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[MapManagementTransport]] +_transport_registry["grpc"] = MapManagementGrpcTransport +_transport_registry["grpc_asyncio"] = MapManagementGrpcAsyncIOTransport +_transport_registry["rest"] = MapManagementRestTransport + +__all__ = ( + "MapManagementTransport", + "MapManagementGrpcTransport", + "MapManagementGrpcAsyncIOTransport", + "MapManagementRestTransport", + "MapManagementRestInterceptor", +) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/base.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/base.py new file mode 100644 index 000000000000..5ff6a33a62e3 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/base.py @@ -0,0 +1,406 @@ +# -*- 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 +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.mapmanagement_v2 import gapic_version as package_version +from google.maps.mapmanagement_v2.types import map_management_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class MapManagementTransport(abc.ABC): + """Abstract transport class for MapManagement.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "mapmanagement.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: 'mapmanagement.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.create_map_config: gapic_v1.method.wrap_method( + self.create_map_config, + default_timeout=None, + client_info=client_info, + ), + self.get_map_config: gapic_v1.method.wrap_method( + self.get_map_config, + default_timeout=None, + client_info=client_info, + ), + self.list_map_configs: gapic_v1.method.wrap_method( + self.list_map_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_map_config: gapic_v1.method.wrap_method( + self.update_map_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_map_config: gapic_v1.method.wrap_method( + self.delete_map_config, + default_timeout=None, + client_info=client_info, + ), + self.create_style_config: gapic_v1.method.wrap_method( + self.create_style_config, + default_timeout=None, + client_info=client_info, + ), + self.get_style_config: gapic_v1.method.wrap_method( + self.get_style_config, + default_timeout=None, + client_info=client_info, + ), + self.list_style_configs: gapic_v1.method.wrap_method( + self.list_style_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_style_config: gapic_v1.method.wrap_method( + self.update_style_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_style_config: gapic_v1.method.wrap_method( + self.delete_style_config, + default_timeout=None, + client_info=client_info, + ), + self.create_map_context_config: gapic_v1.method.wrap_method( + self.create_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.get_map_context_config: gapic_v1.method.wrap_method( + self.get_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.list_map_context_configs: gapic_v1.method.wrap_method( + self.list_map_context_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_map_context_config: gapic_v1.method.wrap_method( + self.update_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_map_context_config: gapic_v1.method.wrap_method( + self.delete_map_context_config, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_map_config( + self, + ) -> Callable[ + [map_management_service.CreateMapConfigRequest], + Union[ + map_management_service.MapConfig, + Awaitable[map_management_service.MapConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_map_config( + self, + ) -> Callable[ + [map_management_service.GetMapConfigRequest], + Union[ + map_management_service.MapConfig, + Awaitable[map_management_service.MapConfig], + ], + ]: + raise NotImplementedError() + + @property + def list_map_configs( + self, + ) -> Callable[ + [map_management_service.ListMapConfigsRequest], + Union[ + map_management_service.ListMapConfigsResponse, + Awaitable[map_management_service.ListMapConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_map_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapConfigRequest], + Union[ + map_management_service.MapConfig, + Awaitable[map_management_service.MapConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_map_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_style_config( + self, + ) -> Callable[ + [map_management_service.CreateStyleConfigRequest], + Union[ + map_management_service.StyleConfig, + Awaitable[map_management_service.StyleConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_style_config( + self, + ) -> Callable[ + [map_management_service.GetStyleConfigRequest], + Union[ + map_management_service.StyleConfig, + Awaitable[map_management_service.StyleConfig], + ], + ]: + raise NotImplementedError() + + @property + def list_style_configs( + self, + ) -> Callable[ + [map_management_service.ListStyleConfigsRequest], + Union[ + map_management_service.ListStyleConfigsResponse, + Awaitable[map_management_service.ListStyleConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_style_config( + self, + ) -> Callable[ + [map_management_service.UpdateStyleConfigRequest], + Union[ + map_management_service.StyleConfig, + Awaitable[map_management_service.StyleConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_style_config( + self, + ) -> Callable[ + [map_management_service.DeleteStyleConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_map_context_config( + self, + ) -> Callable[ + [map_management_service.CreateMapContextConfigRequest], + Union[ + map_management_service.MapContextConfig, + Awaitable[map_management_service.MapContextConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_map_context_config( + self, + ) -> Callable[ + [map_management_service.GetMapContextConfigRequest], + Union[ + map_management_service.MapContextConfig, + Awaitable[map_management_service.MapContextConfig], + ], + ]: + raise NotImplementedError() + + @property + def list_map_context_configs( + self, + ) -> Callable[ + [map_management_service.ListMapContextConfigsRequest], + Union[ + map_management_service.ListMapContextConfigsResponse, + Awaitable[map_management_service.ListMapContextConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_map_context_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapContextConfigRequest], + Union[ + map_management_service.MapContextConfig, + Awaitable[map_management_service.MapContextConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_map_context_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapContextConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("MapManagementTransport",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc.py new file mode 100644 index 000000000000..dd72af4da155 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc.py @@ -0,0 +1,778 @@ +# -*- 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.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.maps.mapmanagement_v2.types import map_management_service + +from .base import DEFAULT_CLIENT_INFO, MapManagementTransport + +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.maps.mapmanagement.v2.MapManagement", + "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.maps.mapmanagement.v2.MapManagement", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MapManagementGrpcTransport(MapManagementTransport): + """gRPC backend transport for MapManagement. + + The Map Management API uses your inputs to create and manage Google + Cloud based styling resources for Google Maps. + + Using this API, you can can create and manage MapConfigs (Map IDs), + StyleConfigs (JSON-based styling), and MapContextConfigs + (associations between styles, datasets, and map variants). + + This API offers features through three channels: + + - ``v2alpha``: Experimental features. + - ``v2beta``: Preview features, recommended for early adoption. + - ``v2``: General Availability (GA) features. + + Capabilities described here are generally available across both the + v2alpha and v2beta endpoints. + + 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 = "mapmanagement.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: 'mapmanagement.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] = {} + + 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 = "mapmanagement.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_map_config( + self, + ) -> Callable[ + [map_management_service.CreateMapConfigRequest], + map_management_service.MapConfig, + ]: + r"""Return a callable for the create map config method over gRPC. + + Creates a MapConfig in a project. + + Returns: + Callable[[~.CreateMapConfigRequest], + ~.MapConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["create_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateMapConfig", + request_serializer=map_management_service.CreateMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["create_map_config"] + + @property + def get_map_config( + self, + ) -> Callable[ + [map_management_service.GetMapConfigRequest], map_management_service.MapConfig + ]: + r"""Return a callable for the get map config method over gRPC. + + Gets a MapConfig. + + Returns: + Callable[[~.GetMapConfigRequest], + ~.MapConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["get_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetMapConfig", + request_serializer=map_management_service.GetMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["get_map_config"] + + @property + def list_map_configs( + self, + ) -> Callable[ + [map_management_service.ListMapConfigsRequest], + map_management_service.ListMapConfigsResponse, + ]: + r"""Return a callable for the list map configs method over gRPC. + + Lists MapConfigs for a project. + + Returns: + Callable[[~.ListMapConfigsRequest], + ~.ListMapConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_configs" not in self._stubs: + self._stubs["list_map_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListMapConfigs", + request_serializer=map_management_service.ListMapConfigsRequest.serialize, + response_deserializer=map_management_service.ListMapConfigsResponse.deserialize, + ) + return self._stubs["list_map_configs"] + + @property + def update_map_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapConfigRequest], + map_management_service.MapConfig, + ]: + r"""Return a callable for the update map config method over gRPC. + + Updates a MapConfig. + + Returns: + Callable[[~.UpdateMapConfigRequest], + ~.MapConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["update_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateMapConfig", + request_serializer=map_management_service.UpdateMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["update_map_config"] + + @property + def delete_map_config( + self, + ) -> Callable[[map_management_service.DeleteMapConfigRequest], empty_pb2.Empty]: + r"""Return a callable for the delete map config method over gRPC. + + Deletes a MapConfig. + + Returns: + Callable[[~.DeleteMapConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_map_config" not in self._stubs: + self._stubs["delete_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteMapConfig", + request_serializer=map_management_service.DeleteMapConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_map_config"] + + @property + def create_style_config( + self, + ) -> Callable[ + [map_management_service.CreateStyleConfigRequest], + map_management_service.StyleConfig, + ]: + r"""Return a callable for the create style config method over gRPC. + + Creates a StyleConfig. + + Returns: + Callable[[~.CreateStyleConfigRequest], + ~.StyleConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["create_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateStyleConfig", + request_serializer=map_management_service.CreateStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["create_style_config"] + + @property + def get_style_config( + self, + ) -> Callable[ + [map_management_service.GetStyleConfigRequest], + map_management_service.StyleConfig, + ]: + r"""Return a callable for the get style config method over gRPC. + + Gets a StyleConfig. + + Returns: + Callable[[~.GetStyleConfigRequest], + ~.StyleConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["get_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetStyleConfig", + request_serializer=map_management_service.GetStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["get_style_config"] + + @property + def list_style_configs( + self, + ) -> Callable[ + [map_management_service.ListStyleConfigsRequest], + map_management_service.ListStyleConfigsResponse, + ]: + r"""Return a callable for the list style configs method over gRPC. + + Lists StyleConfigs. + + Returns: + Callable[[~.ListStyleConfigsRequest], + ~.ListStyleConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_configs" not in self._stubs: + self._stubs["list_style_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListStyleConfigs", + request_serializer=map_management_service.ListStyleConfigsRequest.serialize, + response_deserializer=map_management_service.ListStyleConfigsResponse.deserialize, + ) + return self._stubs["list_style_configs"] + + @property + def update_style_config( + self, + ) -> Callable[ + [map_management_service.UpdateStyleConfigRequest], + map_management_service.StyleConfig, + ]: + r"""Return a callable for the update style config method over gRPC. + + Updates a StyleConfig. + + Returns: + Callable[[~.UpdateStyleConfigRequest], + ~.StyleConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["update_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateStyleConfig", + request_serializer=map_management_service.UpdateStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["update_style_config"] + + @property + def delete_style_config( + self, + ) -> Callable[[map_management_service.DeleteStyleConfigRequest], empty_pb2.Empty]: + r"""Return a callable for the delete style config method over gRPC. + + Deletes a StyleConfig. + + Returns: + Callable[[~.DeleteStyleConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_style_config" not in self._stubs: + self._stubs["delete_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteStyleConfig", + request_serializer=map_management_service.DeleteStyleConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_style_config"] + + @property + def create_map_context_config( + self, + ) -> Callable[ + [map_management_service.CreateMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + r"""Return a callable for the create map context config method over gRPC. + + Creates a MapContextConfig. + + Returns: + Callable[[~.CreateMapContextConfigRequest], + ~.MapContextConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["create_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateMapContextConfig", + request_serializer=map_management_service.CreateMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["create_map_context_config"] + + @property + def get_map_context_config( + self, + ) -> Callable[ + [map_management_service.GetMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + r"""Return a callable for the get map context config method over gRPC. + + Gets a MapContextConfig. + + Returns: + Callable[[~.GetMapContextConfigRequest], + ~.MapContextConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["get_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetMapContextConfig", + request_serializer=map_management_service.GetMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["get_map_context_config"] + + @property + def list_map_context_configs( + self, + ) -> Callable[ + [map_management_service.ListMapContextConfigsRequest], + map_management_service.ListMapContextConfigsResponse, + ]: + r"""Return a callable for the list map context configs method over gRPC. + + Lists MapContextConfigs. + + Returns: + Callable[[~.ListMapContextConfigsRequest], + ~.ListMapContextConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_configs" not in self._stubs: + self._stubs["list_map_context_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListMapContextConfigs", + request_serializer=map_management_service.ListMapContextConfigsRequest.serialize, + response_deserializer=map_management_service.ListMapContextConfigsResponse.deserialize, + ) + return self._stubs["list_map_context_configs"] + + @property + def update_map_context_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + r"""Return a callable for the update map context config method over gRPC. + + Updates a MapContextConfig. + + Returns: + Callable[[~.UpdateMapContextConfigRequest], + ~.MapContextConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["update_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateMapContextConfig", + request_serializer=map_management_service.UpdateMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["update_map_context_config"] + + @property + def delete_map_context_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapContextConfigRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete map context config method over gRPC. + + Deletes a MapContextConfig. + + Returns: + Callable[[~.DeleteMapContextConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_map_context_config" not in self._stubs: + self._stubs["delete_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteMapContextConfig", + request_serializer=map_management_service.DeleteMapContextConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_map_context_config"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("MapManagementGrpcTransport",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc_asyncio.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ecc3e5d6ae3c --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/grpc_asyncio.py @@ -0,0 +1,877 @@ +# -*- 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.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +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.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.maps.mapmanagement_v2.types import map_management_service + +from .base import DEFAULT_CLIENT_INFO, MapManagementTransport +from .grpc import MapManagementGrpcTransport + +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.maps.mapmanagement.v2.MapManagement", + "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.maps.mapmanagement.v2.MapManagement", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class MapManagementGrpcAsyncIOTransport(MapManagementTransport): + """gRPC AsyncIO backend transport for MapManagement. + + The Map Management API uses your inputs to create and manage Google + Cloud based styling resources for Google Maps. + + Using this API, you can can create and manage MapConfigs (Map IDs), + StyleConfigs (JSON-based styling), and MapContextConfigs + (associations between styles, datasets, and map variants). + + This API offers features through three channels: + + - ``v2alpha``: Experimental features. + - ``v2beta``: Preview features, recommended for early adoption. + - ``v2``: General Availability (GA) features. + + Capabilities described here are generally available across both the + v2alpha and v2beta endpoints. + + 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 = "mapmanagement.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 = "mapmanagement.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: 'mapmanagement.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] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_map_config( + self, + ) -> Callable[ + [map_management_service.CreateMapConfigRequest], + Awaitable[map_management_service.MapConfig], + ]: + r"""Return a callable for the create map config method over gRPC. + + Creates a MapConfig in a project. + + Returns: + Callable[[~.CreateMapConfigRequest], + Awaitable[~.MapConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["create_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateMapConfig", + request_serializer=map_management_service.CreateMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["create_map_config"] + + @property + def get_map_config( + self, + ) -> Callable[ + [map_management_service.GetMapConfigRequest], + Awaitable[map_management_service.MapConfig], + ]: + r"""Return a callable for the get map config method over gRPC. + + Gets a MapConfig. + + Returns: + Callable[[~.GetMapConfigRequest], + Awaitable[~.MapConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["get_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetMapConfig", + request_serializer=map_management_service.GetMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["get_map_config"] + + @property + def list_map_configs( + self, + ) -> Callable[ + [map_management_service.ListMapConfigsRequest], + Awaitable[map_management_service.ListMapConfigsResponse], + ]: + r"""Return a callable for the list map configs method over gRPC. + + Lists MapConfigs for a project. + + Returns: + Callable[[~.ListMapConfigsRequest], + Awaitable[~.ListMapConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_configs" not in self._stubs: + self._stubs["list_map_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListMapConfigs", + request_serializer=map_management_service.ListMapConfigsRequest.serialize, + response_deserializer=map_management_service.ListMapConfigsResponse.deserialize, + ) + return self._stubs["list_map_configs"] + + @property + def update_map_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapConfigRequest], + Awaitable[map_management_service.MapConfig], + ]: + r"""Return a callable for the update map config method over gRPC. + + Updates a MapConfig. + + Returns: + Callable[[~.UpdateMapConfigRequest], + Awaitable[~.MapConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_config" not in self._stubs: + self._stubs["update_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateMapConfig", + request_serializer=map_management_service.UpdateMapConfigRequest.serialize, + response_deserializer=map_management_service.MapConfig.deserialize, + ) + return self._stubs["update_map_config"] + + @property + def delete_map_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapConfigRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete map config method over gRPC. + + Deletes a MapConfig. + + Returns: + Callable[[~.DeleteMapConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_map_config" not in self._stubs: + self._stubs["delete_map_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteMapConfig", + request_serializer=map_management_service.DeleteMapConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_map_config"] + + @property + def create_style_config( + self, + ) -> Callable[ + [map_management_service.CreateStyleConfigRequest], + Awaitable[map_management_service.StyleConfig], + ]: + r"""Return a callable for the create style config method over gRPC. + + Creates a StyleConfig. + + Returns: + Callable[[~.CreateStyleConfigRequest], + Awaitable[~.StyleConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["create_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateStyleConfig", + request_serializer=map_management_service.CreateStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["create_style_config"] + + @property + def get_style_config( + self, + ) -> Callable[ + [map_management_service.GetStyleConfigRequest], + Awaitable[map_management_service.StyleConfig], + ]: + r"""Return a callable for the get style config method over gRPC. + + Gets a StyleConfig. + + Returns: + Callable[[~.GetStyleConfigRequest], + Awaitable[~.StyleConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["get_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetStyleConfig", + request_serializer=map_management_service.GetStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["get_style_config"] + + @property + def list_style_configs( + self, + ) -> Callable[ + [map_management_service.ListStyleConfigsRequest], + Awaitable[map_management_service.ListStyleConfigsResponse], + ]: + r"""Return a callable for the list style configs method over gRPC. + + Lists StyleConfigs. + + Returns: + Callable[[~.ListStyleConfigsRequest], + Awaitable[~.ListStyleConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_configs" not in self._stubs: + self._stubs["list_style_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListStyleConfigs", + request_serializer=map_management_service.ListStyleConfigsRequest.serialize, + response_deserializer=map_management_service.ListStyleConfigsResponse.deserialize, + ) + return self._stubs["list_style_configs"] + + @property + def update_style_config( + self, + ) -> Callable[ + [map_management_service.UpdateStyleConfigRequest], + Awaitable[map_management_service.StyleConfig], + ]: + r"""Return a callable for the update style config method over gRPC. + + Updates a StyleConfig. + + Returns: + Callable[[~.UpdateStyleConfigRequest], + Awaitable[~.StyleConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_style_config" not in self._stubs: + self._stubs["update_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateStyleConfig", + request_serializer=map_management_service.UpdateStyleConfigRequest.serialize, + response_deserializer=map_management_service.StyleConfig.deserialize, + ) + return self._stubs["update_style_config"] + + @property + def delete_style_config( + self, + ) -> Callable[ + [map_management_service.DeleteStyleConfigRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete style config method over gRPC. + + Deletes a StyleConfig. + + Returns: + Callable[[~.DeleteStyleConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_style_config" not in self._stubs: + self._stubs["delete_style_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteStyleConfig", + request_serializer=map_management_service.DeleteStyleConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_style_config"] + + @property + def create_map_context_config( + self, + ) -> Callable[ + [map_management_service.CreateMapContextConfigRequest], + Awaitable[map_management_service.MapContextConfig], + ]: + r"""Return a callable for the create map context config method over gRPC. + + Creates a MapContextConfig. + + Returns: + Callable[[~.CreateMapContextConfigRequest], + Awaitable[~.MapContextConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["create_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/CreateMapContextConfig", + request_serializer=map_management_service.CreateMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["create_map_context_config"] + + @property + def get_map_context_config( + self, + ) -> Callable[ + [map_management_service.GetMapContextConfigRequest], + Awaitable[map_management_service.MapContextConfig], + ]: + r"""Return a callable for the get map context config method over gRPC. + + Gets a MapContextConfig. + + Returns: + Callable[[~.GetMapContextConfigRequest], + Awaitable[~.MapContextConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["get_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/GetMapContextConfig", + request_serializer=map_management_service.GetMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["get_map_context_config"] + + @property + def list_map_context_configs( + self, + ) -> Callable[ + [map_management_service.ListMapContextConfigsRequest], + Awaitable[map_management_service.ListMapContextConfigsResponse], + ]: + r"""Return a callable for the list map context configs method over gRPC. + + Lists MapContextConfigs. + + Returns: + Callable[[~.ListMapContextConfigsRequest], + Awaitable[~.ListMapContextConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_configs" not in self._stubs: + self._stubs["list_map_context_configs"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/ListMapContextConfigs", + request_serializer=map_management_service.ListMapContextConfigsRequest.serialize, + response_deserializer=map_management_service.ListMapContextConfigsResponse.deserialize, + ) + return self._stubs["list_map_context_configs"] + + @property + def update_map_context_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapContextConfigRequest], + Awaitable[map_management_service.MapContextConfig], + ]: + r"""Return a callable for the update map context config method over gRPC. + + Updates a MapContextConfig. + + Returns: + Callable[[~.UpdateMapContextConfigRequest], + Awaitable[~.MapContextConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_map_context_config" not in self._stubs: + self._stubs["update_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/UpdateMapContextConfig", + request_serializer=map_management_service.UpdateMapContextConfigRequest.serialize, + response_deserializer=map_management_service.MapContextConfig.deserialize, + ) + return self._stubs["update_map_context_config"] + + @property + def delete_map_context_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapContextConfigRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete map context config method over gRPC. + + Deletes a MapContextConfig. + + Returns: + Callable[[~.DeleteMapContextConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_map_context_config" not in self._stubs: + self._stubs["delete_map_context_config"] = self._logged_channel.unary_unary( + "/google.maps.mapmanagement.v2.MapManagement/DeleteMapContextConfig", + request_serializer=map_management_service.DeleteMapContextConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_map_context_config"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_map_config: self._wrap_method( + self.create_map_config, + default_timeout=None, + client_info=client_info, + ), + self.get_map_config: self._wrap_method( + self.get_map_config, + default_timeout=None, + client_info=client_info, + ), + self.list_map_configs: self._wrap_method( + self.list_map_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_map_config: self._wrap_method( + self.update_map_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_map_config: self._wrap_method( + self.delete_map_config, + default_timeout=None, + client_info=client_info, + ), + self.create_style_config: self._wrap_method( + self.create_style_config, + default_timeout=None, + client_info=client_info, + ), + self.get_style_config: self._wrap_method( + self.get_style_config, + default_timeout=None, + client_info=client_info, + ), + self.list_style_configs: self._wrap_method( + self.list_style_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_style_config: self._wrap_method( + self.update_style_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_style_config: self._wrap_method( + self.delete_style_config, + default_timeout=None, + client_info=client_info, + ), + self.create_map_context_config: self._wrap_method( + self.create_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.get_map_context_config: self._wrap_method( + self.get_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.list_map_context_configs: self._wrap_method( + self.list_map_context_configs, + default_timeout=None, + client_info=client_info, + ), + self.update_map_context_config: self._wrap_method( + self.update_map_context_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_map_context_config: self._wrap_method( + self.delete_map_context_config, + 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" + + +__all__ = ("MapManagementGrpcAsyncIOTransport",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest.py new file mode 100644 index 000000000000..496f19cde0e0 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest.py @@ -0,0 +1,3321 @@ +# -*- 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 +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, 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.protobuf import json_format +from requests import __version__ as requests_version + +from google.maps.mapmanagement_v2.types import map_management_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseMapManagementRestTransport + +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}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class MapManagementRestInterceptor: + """Interceptor for MapManagement. + + 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 MapManagementRestTransport. + + .. code-block:: python + class MyCustomMapManagementInterceptor(MapManagementRestInterceptor): + def pre_create_map_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_map_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_map_context_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_map_context_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_style_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_style_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_map_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_map_context_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_style_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_map_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_map_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_map_context_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_map_context_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_style_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_style_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_map_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_map_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_map_context_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_map_context_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_style_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_style_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_map_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_map_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_map_context_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_map_context_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_style_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_style_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = MapManagementRestTransport(interceptor=MyCustomMapManagementInterceptor()) + client = MapManagementClient(transport=transport) + + + """ + + def pre_create_map_config( + self, + request: map_management_service.CreateMapConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.CreateMapConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_map_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_create_map_config( + self, response: map_management_service.MapConfig + ) -> map_management_service.MapConfig: + """Post-rpc interceptor for create_map_config + + DEPRECATED. Please use the `post_create_map_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_create_map_config` interceptor runs + before the `post_create_map_config_with_metadata` interceptor. + """ + return response + + def post_create_map_config_with_metadata( + self, + response: map_management_service.MapConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_map_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_create_map_config_with_metadata` + interceptor in new development instead of the `post_create_map_config` interceptor. + When both interceptors are used, this `post_create_map_config_with_metadata` interceptor runs after the + `post_create_map_config` interceptor. The (possibly modified) response returned by + `post_create_map_config` will be passed to + `post_create_map_config_with_metadata`. + """ + return response, metadata + + def pre_create_map_context_config( + self, + request: map_management_service.CreateMapContextConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.CreateMapContextConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_map_context_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_create_map_context_config( + self, response: map_management_service.MapContextConfig + ) -> map_management_service.MapContextConfig: + """Post-rpc interceptor for create_map_context_config + + DEPRECATED. Please use the `post_create_map_context_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_create_map_context_config` interceptor runs + before the `post_create_map_context_config_with_metadata` interceptor. + """ + return response + + def post_create_map_context_config_with_metadata( + self, + response: map_management_service.MapContextConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapContextConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_map_context_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_create_map_context_config_with_metadata` + interceptor in new development instead of the `post_create_map_context_config` interceptor. + When both interceptors are used, this `post_create_map_context_config_with_metadata` interceptor runs after the + `post_create_map_context_config` interceptor. The (possibly modified) response returned by + `post_create_map_context_config` will be passed to + `post_create_map_context_config_with_metadata`. + """ + return response, metadata + + def pre_create_style_config( + self, + request: map_management_service.CreateStyleConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.CreateStyleConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_style_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_create_style_config( + self, response: map_management_service.StyleConfig + ) -> map_management_service.StyleConfig: + """Post-rpc interceptor for create_style_config + + DEPRECATED. Please use the `post_create_style_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_create_style_config` interceptor runs + before the `post_create_style_config_with_metadata` interceptor. + """ + return response + + def post_create_style_config_with_metadata( + self, + response: map_management_service.StyleConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.StyleConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_style_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_create_style_config_with_metadata` + interceptor in new development instead of the `post_create_style_config` interceptor. + When both interceptors are used, this `post_create_style_config_with_metadata` interceptor runs after the + `post_create_style_config` interceptor. The (possibly modified) response returned by + `post_create_style_config` will be passed to + `post_create_style_config_with_metadata`. + """ + return response, metadata + + def pre_delete_map_config( + self, + request: map_management_service.DeleteMapConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.DeleteMapConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_map_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def pre_delete_map_context_config( + self, + request: map_management_service.DeleteMapContextConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.DeleteMapContextConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_map_context_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def pre_delete_style_config( + self, + request: map_management_service.DeleteStyleConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.DeleteStyleConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_style_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def pre_get_map_config( + self, + request: map_management_service.GetMapConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.GetMapConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_map_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_get_map_config( + self, response: map_management_service.MapConfig + ) -> map_management_service.MapConfig: + """Post-rpc interceptor for get_map_config + + DEPRECATED. Please use the `post_get_map_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_get_map_config` interceptor runs + before the `post_get_map_config_with_metadata` interceptor. + """ + return response + + def post_get_map_config_with_metadata( + self, + response: map_management_service.MapConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_map_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_get_map_config_with_metadata` + interceptor in new development instead of the `post_get_map_config` interceptor. + When both interceptors are used, this `post_get_map_config_with_metadata` interceptor runs after the + `post_get_map_config` interceptor. The (possibly modified) response returned by + `post_get_map_config` will be passed to + `post_get_map_config_with_metadata`. + """ + return response, metadata + + def pre_get_map_context_config( + self, + request: map_management_service.GetMapContextConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.GetMapContextConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_map_context_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_get_map_context_config( + self, response: map_management_service.MapContextConfig + ) -> map_management_service.MapContextConfig: + """Post-rpc interceptor for get_map_context_config + + DEPRECATED. Please use the `post_get_map_context_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_get_map_context_config` interceptor runs + before the `post_get_map_context_config_with_metadata` interceptor. + """ + return response + + def post_get_map_context_config_with_metadata( + self, + response: map_management_service.MapContextConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapContextConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_map_context_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_get_map_context_config_with_metadata` + interceptor in new development instead of the `post_get_map_context_config` interceptor. + When both interceptors are used, this `post_get_map_context_config_with_metadata` interceptor runs after the + `post_get_map_context_config` interceptor. The (possibly modified) response returned by + `post_get_map_context_config` will be passed to + `post_get_map_context_config_with_metadata`. + """ + return response, metadata + + def pre_get_style_config( + self, + request: map_management_service.GetStyleConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.GetStyleConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_style_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_get_style_config( + self, response: map_management_service.StyleConfig + ) -> map_management_service.StyleConfig: + """Post-rpc interceptor for get_style_config + + DEPRECATED. Please use the `post_get_style_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_get_style_config` interceptor runs + before the `post_get_style_config_with_metadata` interceptor. + """ + return response + + def post_get_style_config_with_metadata( + self, + response: map_management_service.StyleConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.StyleConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_style_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_get_style_config_with_metadata` + interceptor in new development instead of the `post_get_style_config` interceptor. + When both interceptors are used, this `post_get_style_config_with_metadata` interceptor runs after the + `post_get_style_config` interceptor. The (possibly modified) response returned by + `post_get_style_config` will be passed to + `post_get_style_config_with_metadata`. + """ + return response, metadata + + def pre_list_map_configs( + self, + request: map_management_service.ListMapConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListMapConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_map_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_list_map_configs( + self, response: map_management_service.ListMapConfigsResponse + ) -> map_management_service.ListMapConfigsResponse: + """Post-rpc interceptor for list_map_configs + + DEPRECATED. Please use the `post_list_map_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_list_map_configs` interceptor runs + before the `post_list_map_configs_with_metadata` interceptor. + """ + return response + + def post_list_map_configs_with_metadata( + self, + response: map_management_service.ListMapConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListMapConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_map_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_list_map_configs_with_metadata` + interceptor in new development instead of the `post_list_map_configs` interceptor. + When both interceptors are used, this `post_list_map_configs_with_metadata` interceptor runs after the + `post_list_map_configs` interceptor. The (possibly modified) response returned by + `post_list_map_configs` will be passed to + `post_list_map_configs_with_metadata`. + """ + return response, metadata + + def pre_list_map_context_configs( + self, + request: map_management_service.ListMapContextConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListMapContextConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_map_context_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_list_map_context_configs( + self, response: map_management_service.ListMapContextConfigsResponse + ) -> map_management_service.ListMapContextConfigsResponse: + """Post-rpc interceptor for list_map_context_configs + + DEPRECATED. Please use the `post_list_map_context_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_list_map_context_configs` interceptor runs + before the `post_list_map_context_configs_with_metadata` interceptor. + """ + return response + + def post_list_map_context_configs_with_metadata( + self, + response: map_management_service.ListMapContextConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListMapContextConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_map_context_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_list_map_context_configs_with_metadata` + interceptor in new development instead of the `post_list_map_context_configs` interceptor. + When both interceptors are used, this `post_list_map_context_configs_with_metadata` interceptor runs after the + `post_list_map_context_configs` interceptor. The (possibly modified) response returned by + `post_list_map_context_configs` will be passed to + `post_list_map_context_configs_with_metadata`. + """ + return response, metadata + + def pre_list_style_configs( + self, + request: map_management_service.ListStyleConfigsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListStyleConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_style_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_list_style_configs( + self, response: map_management_service.ListStyleConfigsResponse + ) -> map_management_service.ListStyleConfigsResponse: + """Post-rpc interceptor for list_style_configs + + DEPRECATED. Please use the `post_list_style_configs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_list_style_configs` interceptor runs + before the `post_list_style_configs_with_metadata` interceptor. + """ + return response + + def post_list_style_configs_with_metadata( + self, + response: map_management_service.ListStyleConfigsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.ListStyleConfigsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_style_configs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_list_style_configs_with_metadata` + interceptor in new development instead of the `post_list_style_configs` interceptor. + When both interceptors are used, this `post_list_style_configs_with_metadata` interceptor runs after the + `post_list_style_configs` interceptor. The (possibly modified) response returned by + `post_list_style_configs` will be passed to + `post_list_style_configs_with_metadata`. + """ + return response, metadata + + def pre_update_map_config( + self, + request: map_management_service.UpdateMapConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.UpdateMapConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_map_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_update_map_config( + self, response: map_management_service.MapConfig + ) -> map_management_service.MapConfig: + """Post-rpc interceptor for update_map_config + + DEPRECATED. Please use the `post_update_map_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_update_map_config` interceptor runs + before the `post_update_map_config_with_metadata` interceptor. + """ + return response + + def post_update_map_config_with_metadata( + self, + response: map_management_service.MapConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_map_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_update_map_config_with_metadata` + interceptor in new development instead of the `post_update_map_config` interceptor. + When both interceptors are used, this `post_update_map_config_with_metadata` interceptor runs after the + `post_update_map_config` interceptor. The (possibly modified) response returned by + `post_update_map_config` will be passed to + `post_update_map_config_with_metadata`. + """ + return response, metadata + + def pre_update_map_context_config( + self, + request: map_management_service.UpdateMapContextConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.UpdateMapContextConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_map_context_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_update_map_context_config( + self, response: map_management_service.MapContextConfig + ) -> map_management_service.MapContextConfig: + """Post-rpc interceptor for update_map_context_config + + DEPRECATED. Please use the `post_update_map_context_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_update_map_context_config` interceptor runs + before the `post_update_map_context_config_with_metadata` interceptor. + """ + return response + + def post_update_map_context_config_with_metadata( + self, + response: map_management_service.MapContextConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.MapContextConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_map_context_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_update_map_context_config_with_metadata` + interceptor in new development instead of the `post_update_map_context_config` interceptor. + When both interceptors are used, this `post_update_map_context_config_with_metadata` interceptor runs after the + `post_update_map_context_config` interceptor. The (possibly modified) response returned by + `post_update_map_context_config` will be passed to + `post_update_map_context_config_with_metadata`. + """ + return response, metadata + + def pre_update_style_config( + self, + request: map_management_service.UpdateStyleConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.UpdateStyleConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_style_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the MapManagement server. + """ + return request, metadata + + def post_update_style_config( + self, response: map_management_service.StyleConfig + ) -> map_management_service.StyleConfig: + """Post-rpc interceptor for update_style_config + + DEPRECATED. Please use the `post_update_style_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the MapManagement server but before + it is returned to user code. This `post_update_style_config` interceptor runs + before the `post_update_style_config_with_metadata` interceptor. + """ + return response + + def post_update_style_config_with_metadata( + self, + response: map_management_service.StyleConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + map_management_service.StyleConfig, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_style_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the MapManagement server but before it is returned to user code. + + We recommend only using this `post_update_style_config_with_metadata` + interceptor in new development instead of the `post_update_style_config` interceptor. + When both interceptors are used, this `post_update_style_config_with_metadata` interceptor runs after the + `post_update_style_config` interceptor. The (possibly modified) response returned by + `post_update_style_config` will be passed to + `post_update_style_config_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class MapManagementRestStub: + _session: AuthorizedSession + _host: str + _interceptor: MapManagementRestInterceptor + + +class MapManagementRestTransport(_BaseMapManagementRestTransport): + """REST backend synchronous transport for MapManagement. + + The Map Management API uses your inputs to create and manage Google + Cloud based styling resources for Google Maps. + + Using this API, you can can create and manage MapConfigs (Map IDs), + StyleConfigs (JSON-based styling), and MapContextConfigs + (associations between styles, datasets, and map variants). + + This API offers features through three channels: + + - ``v2alpha``: Experimental features. + - ``v2beta``: Preview features, recommended for early adoption. + - ``v2``: General Availability (GA) features. + + Capabilities described here are generally available across both the + v2alpha and v2beta endpoints. + + 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 = "mapmanagement.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[MapManagementRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'mapmanagement.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[MapManagementRestInterceptor]): 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 + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or MapManagementRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateMapConfig( + _BaseMapManagementRestTransport._BaseCreateMapConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.CreateMapConfig") + + @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: map_management_service.CreateMapConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapConfig: + r"""Call the create map config method over HTTP. + + Args: + request (~.map_management_service.CreateMapConfigRequest): + The request object. Request to create a MapConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + + http_options = ( + _BaseMapManagementRestTransport._BaseCreateMapConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_map_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseCreateMapConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseCreateMapConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseCreateMapConfig._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.maps.mapmanagement_v2.MapManagementClient.CreateMapConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateMapConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._CreateMapConfig._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 = map_management_service.MapConfig() + pb_resp = map_management_service.MapConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_map_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_map_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapConfig.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.maps.mapmanagement_v2.MapManagementClient.create_map_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateMapConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMapContextConfig( + _BaseMapManagementRestTransport._BaseCreateMapContextConfig, + MapManagementRestStub, + ): + def __hash__(self): + return hash("MapManagementRestTransport.CreateMapContextConfig") + + @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: map_management_service.CreateMapContextConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Call the create map context config method over HTTP. + + Args: + request (~.map_management_service.CreateMapContextConfigRequest): + The request object. Request to create a MapContextConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + + http_options = _BaseMapManagementRestTransport._BaseCreateMapContextConfig._get_http_options() + + request, metadata = self._interceptor.pre_create_map_context_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseCreateMapContextConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseCreateMapContextConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseCreateMapContextConfig._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.maps.mapmanagement_v2.MapManagementClient.CreateMapContextConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateMapContextConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._CreateMapContextConfig._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 = map_management_service.MapContextConfig() + pb_resp = map_management_service.MapContextConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_map_context_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_map_context_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapContextConfig.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.maps.mapmanagement_v2.MapManagementClient.create_map_context_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateMapContextConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateStyleConfig( + _BaseMapManagementRestTransport._BaseCreateStyleConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.CreateStyleConfig") + + @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: map_management_service.CreateStyleConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.StyleConfig: + r"""Call the create style config method over HTTP. + + Args: + request (~.map_management_service.CreateStyleConfigRequest): + The request object. Request to create a StyleConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + + http_options = _BaseMapManagementRestTransport._BaseCreateStyleConfig._get_http_options() + + request, metadata = self._interceptor.pre_create_style_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseCreateStyleConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseCreateStyleConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseCreateStyleConfig._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.maps.mapmanagement_v2.MapManagementClient.CreateStyleConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateStyleConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._CreateStyleConfig._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 = map_management_service.StyleConfig() + pb_resp = map_management_service.StyleConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_style_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_style_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.StyleConfig.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.maps.mapmanagement_v2.MapManagementClient.create_style_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "CreateStyleConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMapConfig( + _BaseMapManagementRestTransport._BaseDeleteMapConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.DeleteMapConfig") + + @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: map_management_service.DeleteMapConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete map config method over HTTP. + + Args: + request (~.map_management_service.DeleteMapConfigRequest): + The request object. Request to delete a MapConfig. If the + MapConfig has any child + MapContextConfigs, those will be deleted + as well. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = ( + _BaseMapManagementRestTransport._BaseDeleteMapConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_map_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseDeleteMapConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseDeleteMapConfig._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.maps.mapmanagement_v2.MapManagementClient.DeleteMapConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "DeleteMapConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._DeleteMapConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteMapContextConfig( + _BaseMapManagementRestTransport._BaseDeleteMapContextConfig, + MapManagementRestStub, + ): + def __hash__(self): + return hash("MapManagementRestTransport.DeleteMapContextConfig") + + @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: map_management_service.DeleteMapContextConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete map context config method over HTTP. + + Args: + request (~.map_management_service.DeleteMapContextConfigRequest): + The request object. Request to delete a MapContextConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseMapManagementRestTransport._BaseDeleteMapContextConfig._get_http_options() + + request, metadata = self._interceptor.pre_delete_map_context_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseDeleteMapContextConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseDeleteMapContextConfig._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.maps.mapmanagement_v2.MapManagementClient.DeleteMapContextConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "DeleteMapContextConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._DeleteMapContextConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteStyleConfig( + _BaseMapManagementRestTransport._BaseDeleteStyleConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.DeleteStyleConfig") + + @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: map_management_service.DeleteStyleConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete style config method over HTTP. + + Args: + request (~.map_management_service.DeleteStyleConfigRequest): + The request object. Request to delete a StyleConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseMapManagementRestTransport._BaseDeleteStyleConfig._get_http_options() + + request, metadata = self._interceptor.pre_delete_style_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseDeleteStyleConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseDeleteStyleConfig._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.maps.mapmanagement_v2.MapManagementClient.DeleteStyleConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "DeleteStyleConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._DeleteStyleConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetMapConfig( + _BaseMapManagementRestTransport._BaseGetMapConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.GetMapConfig") + + @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: map_management_service.GetMapConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapConfig: + r"""Call the get map config method over HTTP. + + Args: + request (~.map_management_service.GetMapConfigRequest): + The request object. Request to get a MapConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + + http_options = ( + _BaseMapManagementRestTransport._BaseGetMapConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_map_config(request, metadata) + transcoded_request = _BaseMapManagementRestTransport._BaseGetMapConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseGetMapConfig._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.maps.mapmanagement_v2.MapManagementClient.GetMapConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetMapConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._GetMapConfig._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 = map_management_service.MapConfig() + pb_resp = map_management_service.MapConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_map_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_map_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapConfig.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.maps.mapmanagement_v2.MapManagementClient.get_map_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetMapConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMapContextConfig( + _BaseMapManagementRestTransport._BaseGetMapContextConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.GetMapContextConfig") + + @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: map_management_service.GetMapContextConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Call the get map context config method over HTTP. + + Args: + request (~.map_management_service.GetMapContextConfigRequest): + The request object. Request to get a MapContextConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + + http_options = _BaseMapManagementRestTransport._BaseGetMapContextConfig._get_http_options() + + request, metadata = self._interceptor.pre_get_map_context_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseGetMapContextConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseGetMapContextConfig._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.maps.mapmanagement_v2.MapManagementClient.GetMapContextConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetMapContextConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._GetMapContextConfig._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 = map_management_service.MapContextConfig() + pb_resp = map_management_service.MapContextConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_map_context_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_map_context_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapContextConfig.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.maps.mapmanagement_v2.MapManagementClient.get_map_context_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetMapContextConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetStyleConfig( + _BaseMapManagementRestTransport._BaseGetStyleConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.GetStyleConfig") + + @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: map_management_service.GetStyleConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.StyleConfig: + r"""Call the get style config method over HTTP. + + Args: + request (~.map_management_service.GetStyleConfigRequest): + The request object. Request to get a StyleConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + + http_options = ( + _BaseMapManagementRestTransport._BaseGetStyleConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_style_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseGetStyleConfig._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseGetStyleConfig._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.maps.mapmanagement_v2.MapManagementClient.GetStyleConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetStyleConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._GetStyleConfig._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 = map_management_service.StyleConfig() + pb_resp = map_management_service.StyleConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_style_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_style_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.StyleConfig.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.maps.mapmanagement_v2.MapManagementClient.get_style_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "GetStyleConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMapConfigs( + _BaseMapManagementRestTransport._BaseListMapConfigs, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.ListMapConfigs") + + @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: map_management_service.ListMapConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.ListMapConfigsResponse: + r"""Call the list map configs method over HTTP. + + Args: + request (~.map_management_service.ListMapConfigsRequest): + The request object. Request to list MapConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.ListMapConfigsResponse: + Response to list MapConfigs. + """ + + http_options = ( + _BaseMapManagementRestTransport._BaseListMapConfigs._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_map_configs( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseListMapConfigs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseListMapConfigs._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.maps.mapmanagement_v2.MapManagementClient.ListMapConfigs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListMapConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._ListMapConfigs._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 = map_management_service.ListMapConfigsResponse() + pb_resp = map_management_service.ListMapConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_map_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_map_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + map_management_service.ListMapConfigsResponse.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.maps.mapmanagement_v2.MapManagementClient.list_map_configs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListMapConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMapContextConfigs( + _BaseMapManagementRestTransport._BaseListMapContextConfigs, + MapManagementRestStub, + ): + def __hash__(self): + return hash("MapManagementRestTransport.ListMapContextConfigs") + + @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: map_management_service.ListMapContextConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.ListMapContextConfigsResponse: + r"""Call the list map context configs method over HTTP. + + Args: + request (~.map_management_service.ListMapContextConfigsRequest): + The request object. Request to list MapContextConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.ListMapContextConfigsResponse: + Response to list MapContextConfigs. + """ + + http_options = _BaseMapManagementRestTransport._BaseListMapContextConfigs._get_http_options() + + request, metadata = self._interceptor.pre_list_map_context_configs( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseListMapContextConfigs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseListMapContextConfigs._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.maps.mapmanagement_v2.MapManagementClient.ListMapContextConfigs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListMapContextConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._ListMapContextConfigs._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 = map_management_service.ListMapContextConfigsResponse() + pb_resp = map_management_service.ListMapContextConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_map_context_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_map_context_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + map_management_service.ListMapContextConfigsResponse.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.maps.mapmanagement_v2.MapManagementClient.list_map_context_configs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListMapContextConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListStyleConfigs( + _BaseMapManagementRestTransport._BaseListStyleConfigs, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.ListStyleConfigs") + + @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: map_management_service.ListStyleConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.ListStyleConfigsResponse: + r"""Call the list style configs method over HTTP. + + Args: + request (~.map_management_service.ListStyleConfigsRequest): + The request object. Request to list StyleConfigs. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.ListStyleConfigsResponse: + Response to list StyleConfigs. + """ + + http_options = _BaseMapManagementRestTransport._BaseListStyleConfigs._get_http_options() + + request, metadata = self._interceptor.pre_list_style_configs( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseListStyleConfigs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseListStyleConfigs._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.maps.mapmanagement_v2.MapManagementClient.ListStyleConfigs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListStyleConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._ListStyleConfigs._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 = map_management_service.ListStyleConfigsResponse() + pb_resp = map_management_service.ListStyleConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_style_configs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_style_configs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + map_management_service.ListStyleConfigsResponse.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.maps.mapmanagement_v2.MapManagementClient.list_style_configs", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "ListStyleConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateMapConfig( + _BaseMapManagementRestTransport._BaseUpdateMapConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.UpdateMapConfig") + + @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: map_management_service.UpdateMapConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapConfig: + r"""Call the update map config method over HTTP. + + Args: + request (~.map_management_service.UpdateMapConfigRequest): + The request object. Request to update a MapConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapConfig: + Represents a single map in a Maps API + client application. The MapConfig is the + parent resource of MapContextConfigs and + enables custom styling in SDKs + (Mobile/Web). A MapConfig can have + multiple MapContextConfigs, each + applying styling to specific map + variants. + + """ + + http_options = ( + _BaseMapManagementRestTransport._BaseUpdateMapConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_map_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseUpdateMapConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseUpdateMapConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseUpdateMapConfig._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.maps.mapmanagement_v2.MapManagementClient.UpdateMapConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateMapConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._UpdateMapConfig._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 = map_management_service.MapConfig() + pb_resp = map_management_service.MapConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_map_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_map_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapConfig.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.maps.mapmanagement_v2.MapManagementClient.update_map_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateMapConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateMapContextConfig( + _BaseMapManagementRestTransport._BaseUpdateMapContextConfig, + MapManagementRestStub, + ): + def __hash__(self): + return hash("MapManagementRestTransport.UpdateMapContextConfig") + + @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: map_management_service.UpdateMapContextConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.MapContextConfig: + r"""Call the update map context config method over HTTP. + + Args: + request (~.map_management_service.UpdateMapContextConfigRequest): + The request object. Request to update a MapContextConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.MapContextConfig: + Encapsulates the styling + configuration for a map. The + MapContextConfig associates styling + components, such as a StyleConfig and + Datasets, with specific map variants of + a MapConfig. When the MapConfig is + loaded in an SDK, the styling and + dataset information from the + MapContextConfig are applied to the + specified map variants. + + """ + + http_options = _BaseMapManagementRestTransport._BaseUpdateMapContextConfig._get_http_options() + + request, metadata = self._interceptor.pre_update_map_context_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseUpdateMapContextConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseUpdateMapContextConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseUpdateMapContextConfig._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.maps.mapmanagement_v2.MapManagementClient.UpdateMapContextConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateMapContextConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._UpdateMapContextConfig._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 = map_management_service.MapContextConfig() + pb_resp = map_management_service.MapContextConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_map_context_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_map_context_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.MapContextConfig.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.maps.mapmanagement_v2.MapManagementClient.update_map_context_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateMapContextConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateStyleConfig( + _BaseMapManagementRestTransport._BaseUpdateStyleConfig, MapManagementRestStub + ): + def __hash__(self): + return hash("MapManagementRestTransport.UpdateStyleConfig") + + @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: map_management_service.UpdateStyleConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> map_management_service.StyleConfig: + r"""Call the update style config method over HTTP. + + Args: + request (~.map_management_service.UpdateStyleConfigRequest): + The request object. Request to update a StyleConfig. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.map_management_service.StyleConfig: + Represents a single style in a Maps + API client application. The StyleConfig + contains the style sheet that defines + the visual appearance of the map. + + """ + + http_options = _BaseMapManagementRestTransport._BaseUpdateStyleConfig._get_http_options() + + request, metadata = self._interceptor.pre_update_style_config( + request, metadata + ) + transcoded_request = _BaseMapManagementRestTransport._BaseUpdateStyleConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseMapManagementRestTransport._BaseUpdateStyleConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMapManagementRestTransport._BaseUpdateStyleConfig._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.maps.mapmanagement_v2.MapManagementClient.UpdateStyleConfig", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateStyleConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MapManagementRestTransport._UpdateStyleConfig._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 = map_management_service.StyleConfig() + pb_resp = map_management_service.StyleConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_style_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_style_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = map_management_service.StyleConfig.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.maps.mapmanagement_v2.MapManagementClient.update_style_config", + extra={ + "serviceName": "google.maps.mapmanagement.v2.MapManagement", + "rpcName": "UpdateStyleConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_map_config( + self, + ) -> Callable[ + [map_management_service.CreateMapConfigRequest], + map_management_service.MapConfig, + ]: + # 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._CreateMapConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_map_context_config( + self, + ) -> Callable[ + [map_management_service.CreateMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + # 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._CreateMapContextConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_style_config( + self, + ) -> Callable[ + [map_management_service.CreateStyleConfigRequest], + map_management_service.StyleConfig, + ]: + # 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._CreateStyleConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_map_config( + self, + ) -> Callable[[map_management_service.DeleteMapConfigRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMapConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_map_context_config( + self, + ) -> Callable[ + [map_management_service.DeleteMapContextConfigRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMapContextConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_style_config( + self, + ) -> Callable[[map_management_service.DeleteStyleConfigRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteStyleConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_map_config( + self, + ) -> Callable[ + [map_management_service.GetMapConfigRequest], map_management_service.MapConfig + ]: + # 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._GetMapConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_map_context_config( + self, + ) -> Callable[ + [map_management_service.GetMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + # 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._GetMapContextConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_style_config( + self, + ) -> Callable[ + [map_management_service.GetStyleConfigRequest], + map_management_service.StyleConfig, + ]: + # 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._GetStyleConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_map_configs( + self, + ) -> Callable[ + [map_management_service.ListMapConfigsRequest], + map_management_service.ListMapConfigsResponse, + ]: + # 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._ListMapConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_map_context_configs( + self, + ) -> Callable[ + [map_management_service.ListMapContextConfigsRequest], + map_management_service.ListMapContextConfigsResponse, + ]: + # 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._ListMapContextConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_style_configs( + self, + ) -> Callable[ + [map_management_service.ListStyleConfigsRequest], + map_management_service.ListStyleConfigsResponse, + ]: + # 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._ListStyleConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_map_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapConfigRequest], + map_management_service.MapConfig, + ]: + # 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._UpdateMapConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_map_context_config( + self, + ) -> Callable[ + [map_management_service.UpdateMapContextConfigRequest], + map_management_service.MapContextConfig, + ]: + # 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._UpdateMapContextConfig( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_style_config( + self, + ) -> Callable[ + [map_management_service.UpdateStyleConfigRequest], + map_management_service.StyleConfig, + ]: + # 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._UpdateStyleConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("MapManagementRestTransport",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest_base.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest_base.py new file mode 100644 index 000000000000..aa81cb171464 --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/services/map_management/transports/rest_base.py @@ -0,0 +1,863 @@ +# -*- 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 + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.maps.mapmanagement_v2.types import map_management_service + +from .base import DEFAULT_CLIENT_INFO, MapManagementTransport + + +class _BaseMapManagementRestTransport(MapManagementTransport): + """Base REST backend transport for MapManagement. + + 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 = "mapmanagement.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: 'mapmanagement.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 _BaseCreateMapConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/mapConfigs", + "body": "map_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.CreateMapConfigRequest.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( + _BaseMapManagementRestTransport._BaseCreateMapConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMapContextConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*/mapConfigs/*}/mapContextConfigs", + "body": "map_context_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.CreateMapContextConfigRequest.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( + _BaseMapManagementRestTransport._BaseCreateMapContextConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateStyleConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/styleConfigs", + "body": "style_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.CreateStyleConfigRequest.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( + _BaseMapManagementRestTransport._BaseCreateStyleConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMapConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/mapConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.DeleteMapConfigRequest.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( + _BaseMapManagementRestTransport._BaseDeleteMapConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMapContextConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/mapConfigs/*/mapContextConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.DeleteMapContextConfigRequest.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( + _BaseMapManagementRestTransport._BaseDeleteMapContextConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteStyleConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/styleConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.DeleteStyleConfigRequest.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( + _BaseMapManagementRestTransport._BaseDeleteStyleConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMapConfig: + 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/*/mapConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.GetMapConfigRequest.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( + _BaseMapManagementRestTransport._BaseGetMapConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMapContextConfig: + 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/*/mapConfigs/*/mapContextConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.GetMapContextConfigRequest.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( + _BaseMapManagementRestTransport._BaseGetMapContextConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetStyleConfig: + 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/*/styleConfigs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.GetStyleConfigRequest.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( + _BaseMapManagementRestTransport._BaseGetStyleConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMapConfigs: + 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/*}/mapConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.ListMapConfigsRequest.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( + _BaseMapManagementRestTransport._BaseListMapConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMapContextConfigs: + 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/*/mapConfigs/*}/mapContextConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.ListMapContextConfigsRequest.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( + _BaseMapManagementRestTransport._BaseListMapContextConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListStyleConfigs: + 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/*}/styleConfigs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.ListStyleConfigsRequest.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( + _BaseMapManagementRestTransport._BaseListStyleConfigs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateMapConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{map_config.name=projects/*/mapConfigs/*}", + "body": "map_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.UpdateMapConfigRequest.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( + _BaseMapManagementRestTransport._BaseUpdateMapConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateMapContextConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{map_context_config.name=projects/*/mapConfigs/*/mapContextConfigs/*}", + "body": "map_context_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.UpdateMapContextConfigRequest.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( + _BaseMapManagementRestTransport._BaseUpdateMapContextConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateStyleConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{style_config.name=projects/*/styleConfigs/*}", + "body": "style_config", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = map_management_service.UpdateStyleConfigRequest.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( + _BaseMapManagementRestTransport._BaseUpdateStyleConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseMapManagementRestTransport",) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/__init__.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/__init__.py new file mode 100644 index 000000000000..cf99dfcd9a8c --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/__init__.py @@ -0,0 +1,68 @@ +# -*- 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 .map_management_service import ( + CreateMapConfigRequest, + CreateMapContextConfigRequest, + CreateStyleConfigRequest, + DeleteMapConfigRequest, + DeleteMapContextConfigRequest, + DeleteStyleConfigRequest, + GetMapConfigRequest, + GetMapContextConfigRequest, + GetStyleConfigRequest, + ListMapConfigsRequest, + ListMapConfigsResponse, + ListMapContextConfigsRequest, + ListMapContextConfigsResponse, + ListStyleConfigsRequest, + ListStyleConfigsResponse, + MapConfig, + MapContextConfig, + MapFeatures, + MapRenderingType, + StyleConfig, + StyleConfigView, + UpdateMapConfigRequest, + UpdateMapContextConfigRequest, + UpdateStyleConfigRequest, +) + +__all__ = ( + "CreateMapConfigRequest", + "CreateMapContextConfigRequest", + "CreateStyleConfigRequest", + "DeleteMapConfigRequest", + "DeleteMapContextConfigRequest", + "DeleteStyleConfigRequest", + "GetMapConfigRequest", + "GetMapContextConfigRequest", + "GetStyleConfigRequest", + "ListMapConfigsRequest", + "ListMapConfigsResponse", + "ListMapContextConfigsRequest", + "ListMapContextConfigsResponse", + "ListStyleConfigsRequest", + "ListStyleConfigsResponse", + "MapConfig", + "MapContextConfig", + "MapFeatures", + "StyleConfig", + "UpdateMapConfigRequest", + "UpdateMapContextConfigRequest", + "UpdateStyleConfigRequest", + "MapRenderingType", + "StyleConfigView", +) diff --git a/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/map_management_service.py b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/map_management_service.py new file mode 100644 index 000000000000..fae33ad6342a --- /dev/null +++ b/packages/google-maps-mapmanagement/google/maps/mapmanagement_v2/types/map_management_service.py @@ -0,0 +1,940 @@ +# -*- 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.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.maps.mapmanagement.v2", + manifest={ + "MapRenderingType", + "StyleConfigView", + "CreateMapConfigRequest", + "GetMapConfigRequest", + "ListMapConfigsRequest", + "ListMapConfigsResponse", + "UpdateMapConfigRequest", + "DeleteMapConfigRequest", + "MapFeatures", + "MapConfig", + "StyleConfig", + "CreateStyleConfigRequest", + "GetStyleConfigRequest", + "ListStyleConfigsRequest", + "ListStyleConfigsResponse", + "UpdateStyleConfigRequest", + "DeleteStyleConfigRequest", + "MapContextConfig", + "CreateMapContextConfigRequest", + "GetMapContextConfigRequest", + "ListMapContextConfigsRequest", + "ListMapContextConfigsResponse", + "UpdateMapContextConfigRequest", + "DeleteMapContextConfigRequest", + }, +) + + +class MapRenderingType(proto.Enum): + r"""The type of map to be rendered. + + Values: + RASTER (0): + A map rendered using the raster based + implementation. This is the default rendering + type if not specified. + VECTOR (1): + A map rendered using webGL. + """ + + RASTER = 0 + VECTOR = 1 + + +class StyleConfigView(proto.Enum): + r"""What subset of the StyleConfig to return. + + Values: + STYLE_CONFIG_VIEW_UNSPECIFIED (0): + Unspecified view. + FULL (1): + Include the ``json_style_sheet`` and ``style_sheet`` in the + response. + METADATA_ONLY (2): + Exclude the ``json_style_sheet`` and ``style_sheet`` from + the response. + """ + + STYLE_CONFIG_VIEW_UNSPECIFIED = 0 + FULL = 1 + METADATA_ONLY = 2 + + +class CreateMapConfigRequest(proto.Message): + r"""Request to create a MapConfig. + + Attributes: + parent (str): + Required. Parent project that will own the MapConfig. + Format: ``projects/{$my-project-id}`` + map_config (google.maps.mapmanagement_v2.types.MapConfig): + Required. The MapConfig to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + map_config: "MapConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="MapConfig", + ) + + +class GetMapConfigRequest(proto.Message): + r"""Request to get a MapConfig. + + Attributes: + name (str): + Required. Resource name of the MapConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMapConfigsRequest(proto.Message): + r"""Request to list MapConfigs. + + Attributes: + parent (str): + Required. Parent project that owns the MapConfigs. Format: + ``projects/{project}`` + page_size (int): + Optional. The maximum number of MapConfigs to + return. The service may return fewer than this + value. If unspecified, at most 50 MapConfigs + will be returned. The maximum value is 1000; + values above 1000 will be coerced to + 1000. CURRENTLY UNSUPPORTED. + page_token (str): + Optional. A page token, received from a previous + ``ListMapConfigs`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListMapConfigs`` must match the call that provided the + page token. CURRENTLY UNSUPPORTED. + """ + + 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 ListMapConfigsResponse(proto.Message): + r"""Response to list MapConfigs. + + Attributes: + map_configs (MutableSequence[google.maps.mapmanagement_v2.types.MapConfig]): + The list of MapConfigs. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. CURRENTLY UNSUPPORTED. + """ + + @property + def raw_page(self): + return self + + map_configs: MutableSequence["MapConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="MapConfig", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateMapConfigRequest(proto.Message): + r"""Request to update a MapConfig. + + Attributes: + map_config (google.maps.mapmanagement_v2.types.MapConfig): + Required. The MapConfig to update. + + The MapConfig's ``name`` field is used to identify the + MapConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The specific field to update for the MapConfig. If + not specified, the MapConfig will be updated in its + entirety. Valid fields are: + + - ``display_name`` + - ``description`` + - ``map_features`` + """ + + map_config: "MapConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="MapConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteMapConfigRequest(proto.Message): + r"""Request to delete a MapConfig. If the MapConfig has any child + MapContextConfigs, those will be deleted as well. + + Attributes: + name (str): + Required. Resource name of the MapConfig to delete. Format: + ``projects/{project}/mapConfigs/{map_config}`` + force (bool): + Optional. If set to true, any + MapContextConfigs from this MapConfig will also + be deleted. (Otherwise, the request will only + work if the MapConfig has no MapContextConfigs.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class MapFeatures(proto.Message): + r"""Represents a collection of map features that apply to a + MapConfig. Features set on a MapConfig are inherited by all of + its child MapContextConfigs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + simple_features (MutableSequence[google.maps.mapmanagement_v2.types.MapFeatures.SimpleFeature]): + Optional. The visual feature to use for this + map. + poi_boost_level (int): + Optional. POI Boost level, where 0 denotes no boostings and + negative values denotes de-boosting. Boosted POIs are shown + at lower zoom than default and vice versa de-boosted. + Currently supports 2 levels of boosting, so the level is + clamped to [-2, 2]. If not specified, the POI density + defined in the style sheet will be used if it exists. + Otherwise, no POI density will be applied. + + This field is a member of `oneof`_ ``_poi_boost_level``. + """ + + class SimpleFeature(proto.Enum): + r"""This represents the set of map features that affect the + intrinsic structure of the map. + + Values: + SIMPLE_FEATURE_UNSPECIFIED (0): + Unspecified visual feature. + FLATTEN_BUILDINGS (1): + Flattens all buildings in the map. + ICONIC_ICONS (2): + Influences how icons are rendered. + """ + + SIMPLE_FEATURE_UNSPECIFIED = 0 + FLATTEN_BUILDINGS = 1 + ICONIC_ICONS = 2 + + simple_features: MutableSequence[SimpleFeature] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=SimpleFeature, + ) + poi_boost_level: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class MapConfig(proto.Message): + r"""Represents a single map in a Maps API client application. The + MapConfig is the parent resource of MapContextConfigs and + enables custom styling in SDKs (Mobile/Web). A MapConfig can + have multiple MapContextConfigs, each applying styling to + specific map variants. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. Resource name of + this MapConfig. For example: + "projects/my-project-123/mapConfigs/234". Output + only. + display_name (str): + Optional. The display name of this MapConfig, + as specified by the user. + description (str): + Optional. The description of this MapConfig, + as specified by the user. + map_id (str): + Output only. The Map ID of this MapConfig, + used to identify the map in client applications. + This read-only field is generated when the + MapConfig is created. Output only. + map_features (google.maps.mapmanagement_v2.types.MapFeatures): + Optional. The Map Features that apply to this + Map Config. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the creation time of the + Map Config. Output only. + + This field is a member of `oneof`_ ``_create_time``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the last update time of + the Map Config. Output only. + + This field is a member of `oneof`_ ``_update_time``. + map_type (google.maps.mapmanagement_v2.types.MapRenderingType): + Optional. Represents the Map Type of the + MapConfig. If this is unset, the default + behavior is to use the raster map type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + map_id: str = proto.Field( + proto.STRING, + number=4, + ) + map_features: "MapFeatures" = proto.Field( + proto.MESSAGE, + number=5, + message="MapFeatures", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message=timestamp_pb2.Timestamp, + ) + map_type: "MapRenderingType" = proto.Field( + proto.ENUM, + number=8, + enum="MapRenderingType", + ) + + +class StyleConfig(proto.Message): + r"""Represents a single style in a Maps API client application. + The StyleConfig contains the style sheet that defines the visual + appearance of the map. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. Resource name of + this StyleConfig. For example: + "projects/my-project-123/styleConfigs/234". + display_name (str): + Optional. The display name of this + StyleConfig, as specified by the user. + description (str): + Optional. The description of this + StyleConfig, as specified by the user. + style_id (str): + Output only. The unique identifier of this + style. This is a read-only field that is + generated when the StyleConfig is created. + Output only. + json_style_sheet (str): + Optional. JSON representation of the style sheet for this + StyleConfig. If not specified or if provided as an empty + string, the base unstyled Google map style will be used. See + https://developers.google.com/maps/documentation/javascript/cloud-customization/json-reference + for more details on the acceptable JSON format. If both + ``style_sheet`` and ``json_style_sheet`` are filled out, + ``style_sheet`` takes precedence. + style_sheet (google.protobuf.struct_pb2.Struct): + Optional. The style sheet for this StyleConfig, represented + as a raw JSON object. If both ``style_sheet`` and + ``json_style_sheet`` are filled out, ``style_sheet`` takes + precedence. See + https://developers.google.com/maps/documentation/javascript/cloud-customization/json-reference + for more details on the acceptable JSON format. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the creation time of the + StyleConfig. + + This field is a member of `oneof`_ ``_create_time``. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the last update time of + the StyleConfig. + + This field is a member of `oneof`_ ``_update_time``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + style_id: str = proto.Field( + proto.STRING, + number=4, + ) + json_style_sheet: str = proto.Field( + proto.STRING, + number=6, + ) + style_sheet: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=timestamp_pb2.Timestamp, + ) + + +class CreateStyleConfigRequest(proto.Message): + r"""Request to create a StyleConfig. + + Attributes: + parent (str): + Required. Parent project that will own the StyleConfig. + Format: ``projects/{project}`` + style_config (google.maps.mapmanagement_v2.types.StyleConfig): + Required. The StyleConfig to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + style_config: "StyleConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="StyleConfig", + ) + + +class GetStyleConfigRequest(proto.Message): + r"""Request to get a StyleConfig. + + Attributes: + name (str): + Required. Resource name of the StyleConfig. Format: + ``projects/{project}/styleConfigs/{style_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListStyleConfigsRequest(proto.Message): + r"""Request to list StyleConfigs. + + Attributes: + parent (str): + Required. Parent project that owns the StyleConfigs. Format: + ``projects/{project}`` + page_size (int): + Optional. The maximum number of StyleConfigs + to return. The service may return fewer than + this value. If unspecified, at most 50 + StyleConfigs will be returned. The maximum value + is 1000; values above 1000 will be coerced to + 1000. CURRENTLY UNSUPPORTED. + page_token (str): + Optional. A page token, received from a previous + ``ListStyleConfigs`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListStyleConfigs`` must match the call that provided the + page token. CURRENTLY UNSUPPORTED. + filter (str): + Optional. Filter expression for the ListStyleConfigs call. + Currently only supports filtering by display_name. For + example: ``display_name="My StyleConfig"`` will return all + StyleConfigs with the display name "My StyleConfig". + view (google.maps.mapmanagement_v2.types.StyleConfigView): + Optional. The subset of the StyleConfig to + return. If this is unset, the default behavior + is to return the FULL view. + """ + + 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, + ) + view: "StyleConfigView" = proto.Field( + proto.ENUM, + number=5, + enum="StyleConfigView", + ) + + +class ListStyleConfigsResponse(proto.Message): + r"""Response to list StyleConfigs. + + Attributes: + style_configs (MutableSequence[google.maps.mapmanagement_v2.types.StyleConfig]): + The StyleConfigs. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. CURRENTLY UNSUPPORTED. + """ + + @property + def raw_page(self): + return self + + style_configs: MutableSequence["StyleConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="StyleConfig", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateStyleConfigRequest(proto.Message): + r"""Request to update a StyleConfig. + + Attributes: + style_config (google.maps.mapmanagement_v2.types.StyleConfig): + Required. The StyleConfig to update. + + The StyleConfig's ``name`` field is used to identify the + StyleConfig to update. Format: + ``projects/{project}/styleConfigs/{style_config}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If not specified, + the StyleConfig will be updated in its entirety. Valid + fields are: + + - ``display_name`` + - ``description`` + - ``json_style_sheet`` + """ + + style_config: "StyleConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="StyleConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteStyleConfigRequest(proto.Message): + r"""Request to delete a StyleConfig. + + Attributes: + name (str): + Required. Resource name of the StyleConfig to delete. + Format: ``projects/{project}/styleConfigs/{style_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MapContextConfig(proto.Message): + r"""Encapsulates the styling configuration for a map. The + MapContextConfig associates styling components, such as a + StyleConfig and Datasets, with specific map variants of a + MapConfig. When the MapConfig is loaded in an SDK, the styling + and dataset information from the MapContextConfig are applied to + the specified map variants. + + Attributes: + name (str): + Output only. Identifier. Resource name of this + MapContextConfig. For example: + projects/{project_id}/mapConfigs/{map_id}/mapContextConfigs/{map_context_config_id} + map_config (str): + Required. The MapConfig resource name that this + MapContextConfig is associated with. Format: + projects/{project}/mapConfigs/{map_config}. This field is + required and cannot be omitted. + style_config (str): + Required. The StyleConfig resource name that is styling this + MapContextConfig. This field is required and cannot be + omitted. Format: + projects/{project}/styleConfigs/{style_config} + dataset (MutableSequence[str]): + Optional. The Dataset resource name that is + associated with this MapContextConfig. This + field is optional and can be omitted. If + omitted, no datasets will be associated with the + MapContextConfig. If a dataset is specified, it + will be applied to the MapContextConfig. Format: + + projects/{project}/datasets/{dataset} + alias (str): + Optional. The user defined human readable + name for this MapContextConfig. + map_variants (MutableSequence[google.maps.mapmanagement_v2.types.MapContextConfig.MapVariant]): + Required. The map variants that this + MapContextConfig can be applied to. If empty, + the MapContextConfig will be default applied to + only the ROADMAP map variant. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the creation time of the + MapContextConfig. Output only. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Denotes the last update time of + the MapContextConfig. Output only. + """ + + class MapVariant(proto.Enum): + r"""Possible Map Variants that the MapContextConfig can be applied to. + Map Variants are grouped into Light and Dark variants. A Light + variant cannot be paired with a Dark variant for the same + MapContextConfig. The Light Variants are: ROADMAP, SATELLITE, + TERRAIN, NAVIGATION, TRANSIT, ABSTRACT3D, PHOTOREALISTIC3D. The Dark + Variants are: ROADMAP_DARK, NAVIGATION_LOW_LIGHT, TERRAIN_DARK, + TRANSIT_DARK. + + For example, the following is a valid pairing: {MapContextConfig 1: + [ROADMAP, NAVIGATION]} {MapContextConfig 2: [ROADMAP_DARK, + NAVIGATION_LOW_LIGHT]} + + The following is an invalid pairing: {MapContextConfig 1: [ROADMAP, + ROADMAP_DARK]} + + Values: + ROADMAP (0): + The default roadmap map type. If no map + variants are specified in a MapContextConfig, + this variant is used by default. + ROADMAP_DARK (1): + A dark version of the roadmap map type. + SATELLITE (2): + Satellite imagery. + TERRAIN (3): + Terrain map type. + TERRAIN_DARK (4): + A dark version of the terrain map type. + NAVIGATION (5): + Navigation map type. + NAVIGATION_LOW_LIGHT (6): + A low light version of the navigation map + type. + TRANSIT (7): + Transit map type. + TRANSIT_DARK (8): + A dark version of the transit map type. + ABSTRACT3D (9): + Abstract 3D map type. + PHOTOREALISTIC3D (10): + Photorealistic 3D map type. + """ + + ROADMAP = 0 + ROADMAP_DARK = 1 + SATELLITE = 2 + TERRAIN = 3 + TERRAIN_DARK = 4 + NAVIGATION = 5 + NAVIGATION_LOW_LIGHT = 6 + TRANSIT = 7 + TRANSIT_DARK = 8 + ABSTRACT3D = 9 + PHOTOREALISTIC3D = 10 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + map_config: str = proto.Field( + proto.STRING, + number=2, + ) + style_config: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + alias: str = proto.Field( + proto.STRING, + number=5, + ) + map_variants: MutableSequence[MapVariant] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=MapVariant, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class CreateMapContextConfigRequest(proto.Message): + r"""Request to create a MapContextConfig. + + Attributes: + parent (str): + Required. Parent MapConfig that will own the + MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}`` + map_context_config (google.maps.mapmanagement_v2.types.MapContextConfig): + Required. The MapContextConfig to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + map_context_config: "MapContextConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="MapContextConfig", + ) + + +class GetMapContextConfigRequest(proto.Message): + r"""Request to get a MapContextConfig. + + Attributes: + name (str): + Required. Resource name of the MapContextConfig. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMapContextConfigsRequest(proto.Message): + r"""Request to list MapContextConfigs. + + Attributes: + parent (str): + Required. Parent MapConfig that owns the MapContextConfigs. + Format: ``projects/{project}/mapConfigs/{map_config}`` + page_size (int): + Optional. The maximum number of + MapContextConfigs to return. The service may + return fewer than this value. If unspecified, at + most 50 MapContextConfigs will be returned. The + maximum value is 1000; values above 1000 will be + coerced to 1000. CURRENTLY UNSUPPORTED. + page_token (str): + Optional. A page token, received from a previous + ``ListMapContextConfigs`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListMapContextConfigs`` must match the call that provided + the page token. CURRENTLY UNSUPPORTED. + """ + + 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 ListMapContextConfigsResponse(proto.Message): + r"""Response to list MapContextConfigs. + + Attributes: + map_context_configs (MutableSequence[google.maps.mapmanagement_v2.types.MapContextConfig]): + The MapContextConfigs. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. CURRENTLY UNSUPPORTED. + """ + + @property + def raw_page(self): + return self + + map_context_configs: MutableSequence["MapContextConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="MapContextConfig", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateMapContextConfigRequest(proto.Message): + r"""Request to update a MapContextConfig. + + Attributes: + map_context_config (google.maps.mapmanagement_v2.types.MapContextConfig): + Required. The MapContextConfig to update. + + The MapContextConfig's ``name`` field is used to identify + the MapContextConfig to update. Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If not specified, + the MapContextConfig will be updated in its entirety. Valid + fields are: + + - ``display_name`` + - ``alias`` + - ``map_variants`` + - ``style_config`` + - ``dataset`` + """ + + map_context_config: "MapContextConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="MapContextConfig", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteMapContextConfigRequest(proto.Message): + r"""Request to delete a MapContextConfig. + + Attributes: + name (str): + Required. Resource name of the MapContextConfig to delete. + Format: + ``projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_async.py new file mode 100644 index 000000000000..b601d9bcbe3b --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_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 CreateMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateMapConfig_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.maps import mapmanagement_v2 + + +async def sample_create_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateMapConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateMapConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_sync.py new file mode 100644 index 000000000000..72735a450fff --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_config_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 CreateMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateMapConfig_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.maps import mapmanagement_v2 + + +def sample_create_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateMapConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateMapConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_async.py new file mode 100644 index 000000000000..bc00ff5220b1 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_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 CreateMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_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.maps import mapmanagement_v2 + + +async def sample_create_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ["PHOTOREALISTIC3D"] + + request = mapmanagement_v2.CreateMapContextConfigRequest( + parent="parent_value", + map_context_config=map_context_config, + ) + + # Make the request + response = await client.create_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_sync.py new file mode 100644 index 000000000000..0ba2bb862ab4 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_map_context_config_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 CreateMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_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.maps import mapmanagement_v2 + + +def sample_create_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ["PHOTOREALISTIC3D"] + + request = mapmanagement_v2.CreateMapContextConfigRequest( + parent="parent_value", + map_context_config=map_context_config, + ) + + # Make the request + response = client.create_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_async.py new file mode 100644 index 000000000000..b4beb02b5034 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_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 CreateStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateStyleConfig_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.maps import mapmanagement_v2 + + +async def sample_create_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateStyleConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateStyleConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_sync.py new file mode 100644 index 000000000000..aaef594e4c09 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_create_style_config_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 CreateStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_CreateStyleConfig_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.maps import mapmanagement_v2 + + +def sample_create_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.CreateStyleConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_CreateStyleConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_async.py new file mode 100644 index 000000000000..25615c265da4 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteMapConfig_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.maps import mapmanagement_v2 + + +async def sample_delete_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_map_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteMapConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_sync.py new file mode 100644 index 000000000000..96cae692b35f --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_config_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteMapConfig_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.maps import mapmanagement_v2 + + +def sample_delete_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_map_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteMapConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_async.py new file mode 100644 index 000000000000..d842bdee525a --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_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.maps import mapmanagement_v2 + + +async def sample_delete_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapContextConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_map_context_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_sync.py new file mode 100644 index 000000000000..a8823840644c --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_map_context_config_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_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.maps import mapmanagement_v2 + + +def sample_delete_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteMapContextConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_map_context_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_async.py new file mode 100644 index 000000000000..799adb6ceba3 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_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.maps import mapmanagement_v2 + + +async def sample_delete_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteStyleConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_style_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_sync.py new file mode 100644 index 000000000000..3030704f3ff7 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_delete_style_config_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_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.maps import mapmanagement_v2 + + +def sample_delete_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.DeleteStyleConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_style_config(request=request) + + +# [END mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_async.py new file mode 100644 index 000000000000..6878e205635f --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_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 GetMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetMapConfig_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.maps import mapmanagement_v2 + + +async def sample_get_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetMapConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_sync.py new file mode 100644 index 000000000000..46abf32d532e --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_config_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 GetMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetMapConfig_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.maps import mapmanagement_v2 + + +def sample_get_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetMapConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_async.py new file mode 100644 index 000000000000..f3a8c375cd74 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_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 GetMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetMapContextConfig_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.maps import mapmanagement_v2 + + +async def sample_get_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapContextConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetMapContextConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_sync.py new file mode 100644 index 000000000000..1a227ad48009 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_map_context_config_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 GetMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetMapContextConfig_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.maps import mapmanagement_v2 + + +def sample_get_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetMapContextConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetMapContextConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_async.py new file mode 100644 index 000000000000..4ab92c0e65a8 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_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 GetStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetStyleConfig_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.maps import mapmanagement_v2 + + +async def sample_get_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetStyleConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetStyleConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_sync.py new file mode 100644 index 000000000000..086b4b52f3b0 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_get_style_config_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 GetStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_GetStyleConfig_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.maps import mapmanagement_v2 + + +def sample_get_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.GetStyleConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_GetStyleConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_async.py new file mode 100644 index 000000000000..8f7dce74ab38 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_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 ListMapConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListMapConfigs_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.maps import mapmanagement_v2 + + +async def sample_list_map_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListMapConfigs_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_sync.py new file mode 100644 index 000000000000..68316f8e3d33 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_configs_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 ListMapConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListMapConfigs_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.maps import mapmanagement_v2 + + +def sample_list_map_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListMapConfigs_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_async.py new file mode 100644 index 000000000000..a2f436fb7ba1 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_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 ListMapContextConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_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.maps import mapmanagement_v2 + + +async def sample_list_map_context_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapContextConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_context_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_sync.py new file mode 100644 index 000000000000..4538f6023f36 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_map_context_configs_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 ListMapContextConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_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.maps import mapmanagement_v2 + + +def sample_list_map_context_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListMapContextConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_map_context_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_async.py new file mode 100644 index 000000000000..4077e280a6b4 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_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 ListStyleConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListStyleConfigs_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.maps import mapmanagement_v2 + + +async def sample_list_style_configs(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListStyleConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_style_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListStyleConfigs_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_sync.py new file mode 100644 index 000000000000..f8ced721ee25 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_list_style_configs_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 ListStyleConfigs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_ListStyleConfigs_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.maps import mapmanagement_v2 + + +def sample_list_style_configs(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.ListStyleConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_style_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_ListStyleConfigs_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_async.py new file mode 100644 index 000000000000..e6b620ecaf84 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateMapConfig_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.maps import mapmanagement_v2 + + +async def sample_update_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateMapConfigRequest() + + # Make the request + response = await client.update_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateMapConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_sync.py new file mode 100644 index 000000000000..77917c4bceef --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_config_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateMapConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateMapConfig_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.maps import mapmanagement_v2 + + +def sample_update_map_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateMapConfigRequest() + + # Make the request + response = client.update_map_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateMapConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_async.py new file mode 100644 index 000000000000..d9d299324f13 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_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 UpdateMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_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.maps import mapmanagement_v2 + + +async def sample_update_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ["PHOTOREALISTIC3D"] + + request = mapmanagement_v2.UpdateMapContextConfigRequest( + map_context_config=map_context_config, + ) + + # Make the request + response = await client.update_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_sync.py new file mode 100644 index 000000000000..d1e177592831 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_map_context_config_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 UpdateMapContextConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_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.maps import mapmanagement_v2 + + +def sample_update_map_context_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + map_context_config = mapmanagement_v2.MapContextConfig() + map_context_config.map_config = "map_config_value" + map_context_config.style_config = "style_config_value" + map_context_config.map_variants = ["PHOTOREALISTIC3D"] + + request = mapmanagement_v2.UpdateMapContextConfigRequest( + map_context_config=map_context_config, + ) + + # Make the request + response = client.update_map_context_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_async.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_async.py new file mode 100644 index 000000000000..4d51c99eabdc --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_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.maps import mapmanagement_v2 + + +async def sample_update_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementAsyncClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateStyleConfigRequest() + + # Make the request + response = await client.update_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_async] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_sync.py b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_sync.py new file mode 100644 index 000000000000..7e55d89eb7fa --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/mapmanagement_v2_generated_map_management_update_style_config_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateStyleConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-mapmanagement + + +# [START mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_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.maps import mapmanagement_v2 + + +def sample_update_style_config(): + # Create a client + client = mapmanagement_v2.MapManagementClient() + + # Initialize request argument(s) + request = mapmanagement_v2.UpdateStyleConfigRequest() + + # Make the request + response = client.update_style_config(request=request) + + # Handle the response + print(response) + + +# [END mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_sync] diff --git a/packages/google-maps-mapmanagement/samples/generated_samples/snippet_metadata_google.maps.mapmanagement.v2.json b/packages/google-maps-mapmanagement/samples/generated_samples/snippet_metadata_google.maps.mapmanagement.v2.json new file mode 100644 index 000000000000..2cb628e791c8 --- /dev/null +++ b/packages/google-maps-mapmanagement/samples/generated_samples/snippet_metadata_google.maps.mapmanagement.v2.json @@ -0,0 +1,2468 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.mapmanagement.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-mapmanagement", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.create_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateMapConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "map_config", + "type": "google.maps.mapmanagement_v2.types.MapConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.MapConfig", + "shortName": "create_map_config" + }, + "description": "Sample for CreateMapConfig", + "file": "mapmanagement_v2_generated_map_management_create_map_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateMapConfig_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": "mapmanagement_v2_generated_map_management_create_map_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.create_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateMapConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "map_config", + "type": "google.maps.mapmanagement_v2.types.MapConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.MapConfig", + "shortName": "create_map_config" + }, + "description": "Sample for CreateMapConfig", + "file": "mapmanagement_v2_generated_map_management_create_map_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateMapConfig_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": "mapmanagement_v2_generated_map_management_create_map_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.create_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateMapContextConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "map_context_config", + "type": "google.maps.mapmanagement_v2.types.MapContextConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "create_map_context_config" + }, + "description": "Sample for CreateMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_create_map_context_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_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": "mapmanagement_v2_generated_map_management_create_map_context_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.create_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateMapContextConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "map_context_config", + "type": "google.maps.mapmanagement_v2.types.MapContextConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "create_map_context_config" + }, + "description": "Sample for CreateMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_create_map_context_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateMapContextConfig_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": "mapmanagement_v2_generated_map_management_create_map_context_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.create_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateStyleConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "style_config", + "type": "google.maps.mapmanagement_v2.types.StyleConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "create_style_config" + }, + "description": "Sample for CreateStyleConfig", + "file": "mapmanagement_v2_generated_map_management_create_style_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateStyleConfig_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": "mapmanagement_v2_generated_map_management_create_style_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.create_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.CreateStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "CreateStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.CreateStyleConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "style_config", + "type": "google.maps.mapmanagement_v2.types.StyleConfig" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "create_style_config" + }, + "description": "Sample for CreateStyleConfig", + "file": "mapmanagement_v2_generated_map_management_create_style_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_CreateStyleConfig_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": "mapmanagement_v2_generated_map_management_create_style_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.delete_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteMapConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_map_config" + }, + "description": "Sample for DeleteMapConfig", + "file": "mapmanagement_v2_generated_map_management_delete_map_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteMapConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_map_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.delete_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteMapConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_map_config" + }, + "description": "Sample for DeleteMapConfig", + "file": "mapmanagement_v2_generated_map_management_delete_map_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteMapConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_map_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.delete_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteMapContextConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_map_context_config" + }, + "description": "Sample for DeleteMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_delete_map_context_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_map_context_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.delete_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteMapContextConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_map_context_config" + }, + "description": "Sample for DeleteMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_delete_map_context_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteMapContextConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_map_context_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.delete_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteStyleConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_style_config" + }, + "description": "Sample for DeleteStyleConfig", + "file": "mapmanagement_v2_generated_map_management_delete_style_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_style_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.delete_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.DeleteStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "DeleteStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.DeleteStyleConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_style_config" + }, + "description": "Sample for DeleteStyleConfig", + "file": "mapmanagement_v2_generated_map_management_delete_style_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_DeleteStyleConfig_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_delete_style_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.get_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetMapConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.MapConfig", + "shortName": "get_map_config" + }, + "description": "Sample for GetMapConfig", + "file": "mapmanagement_v2_generated_map_management_get_map_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetMapConfig_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": "mapmanagement_v2_generated_map_management_get_map_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.get_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetMapConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.MapConfig", + "shortName": "get_map_config" + }, + "description": "Sample for GetMapConfig", + "file": "mapmanagement_v2_generated_map_management_get_map_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetMapConfig_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": "mapmanagement_v2_generated_map_management_get_map_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.get_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetMapContextConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "get_map_context_config" + }, + "description": "Sample for GetMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_get_map_context_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetMapContextConfig_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": "mapmanagement_v2_generated_map_management_get_map_context_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.get_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetMapContextConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "get_map_context_config" + }, + "description": "Sample for GetMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_get_map_context_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetMapContextConfig_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": "mapmanagement_v2_generated_map_management_get_map_context_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.get_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetStyleConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "get_style_config" + }, + "description": "Sample for GetStyleConfig", + "file": "mapmanagement_v2_generated_map_management_get_style_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetStyleConfig_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": "mapmanagement_v2_generated_map_management_get_style_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.get_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.GetStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "GetStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.GetStyleConfigRequest" + }, + { + "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.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "get_style_config" + }, + "description": "Sample for GetStyleConfig", + "file": "mapmanagement_v2_generated_map_management_get_style_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_GetStyleConfig_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": "mapmanagement_v2_generated_map_management_get_style_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.list_map_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListMapConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListMapConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListMapConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListMapConfigsAsyncPager", + "shortName": "list_map_configs" + }, + "description": "Sample for ListMapConfigs", + "file": "mapmanagement_v2_generated_map_management_list_map_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListMapConfigs_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": "mapmanagement_v2_generated_map_management_list_map_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.list_map_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListMapConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListMapConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListMapConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListMapConfigsPager", + "shortName": "list_map_configs" + }, + "description": "Sample for ListMapConfigs", + "file": "mapmanagement_v2_generated_map_management_list_map_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListMapConfigs_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": "mapmanagement_v2_generated_map_management_list_map_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.list_map_context_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListMapContextConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListMapContextConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListMapContextConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListMapContextConfigsAsyncPager", + "shortName": "list_map_context_configs" + }, + "description": "Sample for ListMapContextConfigs", + "file": "mapmanagement_v2_generated_map_management_list_map_context_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_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": "mapmanagement_v2_generated_map_management_list_map_context_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.list_map_context_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListMapContextConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListMapContextConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListMapContextConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListMapContextConfigsPager", + "shortName": "list_map_context_configs" + }, + "description": "Sample for ListMapContextConfigs", + "file": "mapmanagement_v2_generated_map_management_list_map_context_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListMapContextConfigs_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": "mapmanagement_v2_generated_map_management_list_map_context_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.list_style_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListStyleConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListStyleConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListStyleConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListStyleConfigsAsyncPager", + "shortName": "list_style_configs" + }, + "description": "Sample for ListStyleConfigs", + "file": "mapmanagement_v2_generated_map_management_list_style_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListStyleConfigs_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": "mapmanagement_v2_generated_map_management_list_style_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.list_style_configs", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.ListStyleConfigs", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "ListStyleConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.ListStyleConfigsRequest" + }, + { + "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.maps.mapmanagement_v2.services.map_management.pagers.ListStyleConfigsPager", + "shortName": "list_style_configs" + }, + "description": "Sample for ListStyleConfigs", + "file": "mapmanagement_v2_generated_map_management_list_style_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_ListStyleConfigs_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": "mapmanagement_v2_generated_map_management_list_style_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.update_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateMapConfigRequest" + }, + { + "name": "map_config", + "type": "google.maps.mapmanagement_v2.types.MapConfig" + }, + { + "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.maps.mapmanagement_v2.types.MapConfig", + "shortName": "update_map_config" + }, + "description": "Sample for UpdateMapConfig", + "file": "mapmanagement_v2_generated_map_management_update_map_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateMapConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_map_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.update_map_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateMapConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateMapConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateMapConfigRequest" + }, + { + "name": "map_config", + "type": "google.maps.mapmanagement_v2.types.MapConfig" + }, + { + "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.maps.mapmanagement_v2.types.MapConfig", + "shortName": "update_map_config" + }, + "description": "Sample for UpdateMapConfig", + "file": "mapmanagement_v2_generated_map_management_update_map_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateMapConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_map_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.update_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateMapContextConfigRequest" + }, + { + "name": "map_context_config", + "type": "google.maps.mapmanagement_v2.types.MapContextConfig" + }, + { + "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.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "update_map_context_config" + }, + "description": "Sample for UpdateMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_update_map_context_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_map_context_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.update_map_context_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateMapContextConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateMapContextConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateMapContextConfigRequest" + }, + { + "name": "map_context_config", + "type": "google.maps.mapmanagement_v2.types.MapContextConfig" + }, + { + "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.maps.mapmanagement_v2.types.MapContextConfig", + "shortName": "update_map_context_config" + }, + "description": "Sample for UpdateMapContextConfig", + "file": "mapmanagement_v2_generated_map_management_update_map_context_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateMapContextConfig_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_map_context_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient", + "shortName": "MapManagementAsyncClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementAsyncClient.update_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateStyleConfigRequest" + }, + { + "name": "style_config", + "type": "google.maps.mapmanagement_v2.types.StyleConfig" + }, + { + "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.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "update_style_config" + }, + "description": "Sample for UpdateStyleConfig", + "file": "mapmanagement_v2_generated_map_management_update_style_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_style_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.mapmanagement_v2.MapManagementClient", + "shortName": "MapManagementClient" + }, + "fullName": "google.maps.mapmanagement_v2.MapManagementClient.update_style_config", + "method": { + "fullName": "google.maps.mapmanagement.v2.MapManagement.UpdateStyleConfig", + "service": { + "fullName": "google.maps.mapmanagement.v2.MapManagement", + "shortName": "MapManagement" + }, + "shortName": "UpdateStyleConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.mapmanagement_v2.types.UpdateStyleConfigRequest" + }, + { + "name": "style_config", + "type": "google.maps.mapmanagement_v2.types.StyleConfig" + }, + { + "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.maps.mapmanagement_v2.types.StyleConfig", + "shortName": "update_style_config" + }, + "description": "Sample for UpdateStyleConfig", + "file": "mapmanagement_v2_generated_map_management_update_style_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "mapmanagement_v2_generated_MapManagement_UpdateStyleConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "mapmanagement_v2_generated_map_management_update_style_config_sync.py" + } + ] +} diff --git a/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/__init__.py b/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/test_map_management.py b/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/test_map_management.py new file mode 100644 index 000000000000..3a58ef5f1670 --- /dev/null +++ b/packages/google-maps-mapmanagement/tests/unit/gapic/mapmanagement_v2/test_map_management.py @@ -0,0 +1,14790 @@ +# -*- 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.auth +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, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.maps.mapmanagement_v2.services.map_management import ( + MapManagementAsyncClient, + MapManagementClient, + pagers, + transports, +) +from google.maps.mapmanagement_v2.types import map_management_service + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@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 MapManagementClient._get_default_mtls_endpoint(None) is None + assert ( + MapManagementClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + MapManagementClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + MapManagementClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + MapManagementClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + MapManagementClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + assert ( + MapManagementClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert MapManagementClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert MapManagementClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert MapManagementClient._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: + MapManagementClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert MapManagementClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert MapManagementClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert MapManagementClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert MapManagementClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._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): + MapManagementClient._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 MapManagementClient._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 MapManagementClient._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 MapManagementClient._get_client_cert_source(None, False) is None + assert ( + MapManagementClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + MapManagementClient._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 ( + MapManagementClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + MapManagementClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + MapManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementClient), +) +@mock.patch.object( + MapManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = MapManagementClient._DEFAULT_UNIVERSE + default_endpoint = MapManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = MapManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + MapManagementClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + MapManagementClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == MapManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + MapManagementClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + MapManagementClient._get_api_endpoint(None, None, default_universe, "always") + == MapManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + MapManagementClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == MapManagementClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + MapManagementClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + MapManagementClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + MapManagementClient._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 ( + MapManagementClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + MapManagementClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + MapManagementClient._get_universe_domain(None, None) + == MapManagementClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + MapManagementClient._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 = MapManagementClient(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 = MapManagementClient(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", + [ + (MapManagementClient, "grpc"), + (MapManagementAsyncClient, "grpc_asyncio"), + (MapManagementClient, "rest"), + ], +) +def test_map_management_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 == ( + "mapmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://mapmanagement.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.MapManagementGrpcTransport, "grpc"), + (transports.MapManagementGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.MapManagementRestTransport, "rest"), + ], +) +def test_map_management_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", + [ + (MapManagementClient, "grpc"), + (MapManagementAsyncClient, "grpc_asyncio"), + (MapManagementClient, "rest"), + ], +) +def test_map_management_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 == ( + "mapmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://mapmanagement.googleapis.com" + ) + + +def test_map_management_client_get_transport_class(): + transport = MapManagementClient.get_transport_class() + available_transports = [ + transports.MapManagementGrpcTransport, + transports.MapManagementRestTransport, + ] + assert transport in available_transports + + transport = MapManagementClient.get_transport_class("grpc") + assert transport == transports.MapManagementGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (MapManagementClient, transports.MapManagementGrpcTransport, "grpc"), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (MapManagementClient, transports.MapManagementRestTransport, "rest"), + ], +) +@mock.patch.object( + MapManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementClient), +) +@mock.patch.object( + MapManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementAsyncClient), +) +def test_map_management_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(MapManagementClient, "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(MapManagementClient, "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", + [ + (MapManagementClient, transports.MapManagementGrpcTransport, "grpc", "true"), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (MapManagementClient, transports.MapManagementGrpcTransport, "grpc", "false"), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (MapManagementClient, transports.MapManagementRestTransport, "rest", "true"), + (MapManagementClient, transports.MapManagementRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + MapManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementClient), +) +@mock.patch.object( + MapManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_map_management_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", [MapManagementClient, MapManagementAsyncClient] +) +@mock.patch.object( + MapManagementClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(MapManagementClient), +) +@mock.patch.object( + MapManagementAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(MapManagementAsyncClient), +) +def test_map_management_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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + 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", [MapManagementClient, MapManagementAsyncClient] +) +@mock.patch.object( + MapManagementClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementClient), +) +@mock.patch.object( + MapManagementAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(MapManagementAsyncClient), +) +def test_map_management_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = MapManagementClient._DEFAULT_UNIVERSE + default_endpoint = MapManagementClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = MapManagementClient._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", + [ + (MapManagementClient, transports.MapManagementGrpcTransport, "grpc"), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (MapManagementClient, transports.MapManagementRestTransport, "rest"), + ], +) +def test_map_management_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", + [ + ( + MapManagementClient, + transports.MapManagementGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (MapManagementClient, transports.MapManagementRestTransport, "rest", None), + ], +) +def test_map_management_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_map_management_client_client_options_from_dict(): + with mock.patch( + "google.maps.mapmanagement_v2.services.map_management.transports.MapManagementGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = MapManagementClient( + 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", + [ + ( + MapManagementClient, + transports.MapManagementGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + MapManagementAsyncClient, + transports.MapManagementGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_map_management_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( + "mapmanagement.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="mapmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapConfigRequest(), + {}, + ], +) +def test_create_map_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + response = client.create_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_create_map_config_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 = MapManagementClient( + 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 = map_management_service.CreateMapConfigRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_map_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapConfigRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_map_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_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.create_map_config] = ( + mock_rpc + ) + request = {} + client.create_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_map_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_create_map_config_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 = MapManagementAsyncClient( + 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_map_config + 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_map_config + ] = mock_rpc + + request = {} + await client.create_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_map_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapConfigRequest(), + {}, + ], +) +async def test_create_map_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + response = await client.create_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_create_map_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.CreateMapConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + call.return_value = map_management_service.MapConfig() + client.create_map_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 + + # 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_map_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.CreateMapConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + await client.create_map_config(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_map_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_map_config( + parent="parent_value", + map_config=map_management_service.MapConfig(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].map_config + mock_val = map_management_service.MapConfig(name="name_value") + assert arg == mock_val + + +def test_create_map_config_flattened_error(): + client = MapManagementClient( + 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_map_config( + map_management_service.CreateMapConfigRequest(), + parent="parent_value", + map_config=map_management_service.MapConfig(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_map_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_map_config( + parent="parent_value", + map_config=map_management_service.MapConfig(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].map_config + mock_val = map_management_service.MapConfig(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_map_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_config( + map_management_service.CreateMapConfigRequest(), + parent="parent_value", + map_config=map_management_service.MapConfig(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapConfigRequest(), + {}, + ], +) +def test_get_map_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + response = client.get_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.GetMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_get_map_config_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 = MapManagementClient( + 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 = map_management_service.GetMapConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_map_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_map_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_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_map_config] = mock_rpc + request = {} + client.get_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_map_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_map_config_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 = MapManagementAsyncClient( + 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_map_config + 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_map_config + ] = mock_rpc + + request = {} + await client.get_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_map_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapConfigRequest(), + {}, + ], +) +async def test_get_map_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_map_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + response = await client.get_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.GetMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_get_map_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.GetMapConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + call.return_value = map_management_service.MapConfig() + client.get_map_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 + + # 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_map_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.GetMapConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + await client.get_map_config(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_map_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_map_config( + 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_map_config_flattened_error(): + client = MapManagementClient( + 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_map_config( + map_management_service.GetMapConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_map_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_map_config( + 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_map_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_config( + map_management_service.GetMapConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListMapConfigsRequest(), + {}, + ], +) +def test_list_map_configs(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_configs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_map_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.ListMapConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_map_configs_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 = MapManagementClient( + 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 = map_management_service.ListMapConfigsRequest( + 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_map_configs), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_map_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapConfigsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_map_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_map_configs] = ( + mock_rpc + ) + request = {} + client.list_map_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_map_configs(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_map_configs_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 = MapManagementAsyncClient( + 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_map_configs + 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_map_configs + ] = mock_rpc + + request = {} + await client.list_map_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_map_configs(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", + [ + map_management_service.ListMapConfigsRequest(), + {}, + ], +) +async def test_list_map_configs_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_map_configs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_map_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.ListMapConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_map_configs_field_headers(): + client = MapManagementClient( + 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 = map_management_service.ListMapConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + call.return_value = map_management_service.ListMapConfigsResponse() + client.list_map_configs(request) + + # Establish that the 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_map_configs_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.ListMapConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapConfigsResponse() + ) + await client.list_map_configs(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_map_configs_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_map_configs( + 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_map_configs_flattened_error(): + client = MapManagementClient( + 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_map_configs( + map_management_service.ListMapConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_map_configs_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_map_configs( + 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_map_configs_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_configs( + map_management_service.ListMapConfigsRequest(), + parent="parent_value", + ) + + +def test_list_map_configs_pager(transport_name: str = "grpc"): + client = MapManagementClient( + 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_map_configs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[], + next_page_token="def", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_map_configs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, map_management_service.MapConfig) for i in results) + + +def test_list_map_configs_pages(transport_name: str = "grpc"): + client = MapManagementClient( + 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_map_configs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[], + next_page_token="def", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_map_configs(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_map_configs_async_pager(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_configs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[], + next_page_token="def", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_map_configs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, map_management_service.MapConfig) for i in responses) + + +@pytest.mark.asyncio +async def test_list_map_configs_async_pages(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_configs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[], + next_page_token="def", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_map_configs(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", + [ + map_management_service.UpdateMapConfigRequest(), + {}, + ], +) +def test_update_map_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + response = client.update_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_update_map_config_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 = MapManagementClient( + 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 = map_management_service.UpdateMapConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_map_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapConfigRequest() + assert args[0] == request_msg + + +def test_update_map_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_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_map_config] = ( + mock_rpc + ) + request = {} + client.update_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_map_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_update_map_config_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 = MapManagementAsyncClient( + 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_map_config + 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_map_config + ] = mock_rpc + + request = {} + await client.update_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_map_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateMapConfigRequest(), + {}, + ], +) +async def test_update_map_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + response = await client.update_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +def test_update_map_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.UpdateMapConfigRequest() + + request.map_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + call.return_value = map_management_service.MapConfig() + client.update_map_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "map_config.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_map_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.UpdateMapConfigRequest() + + request.map_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + await client.update_map_config(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", + "map_config.name=name_value", + ) in kw["metadata"] + + +def test_update_map_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_map_config( + map_config=map_management_service.MapConfig(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].map_config + mock_val = map_management_service.MapConfig(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_map_config_flattened_error(): + client = MapManagementClient( + 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_map_config( + map_management_service.UpdateMapConfigRequest(), + map_config=map_management_service.MapConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_map_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_map_config( + map_config=map_management_service.MapConfig(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].map_config + mock_val = map_management_service.MapConfig(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_map_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_config( + map_management_service.UpdateMapConfigRequest(), + map_config=map_management_service.MapConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapConfigRequest(), + {}, + ], +) +def test_delete_map_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_map_config_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 = MapManagementClient( + 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 = map_management_service.DeleteMapConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_map_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_map_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_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.delete_map_config] = ( + mock_rpc + ) + request = {} + client.delete_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_map_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_delete_map_config_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 = MapManagementAsyncClient( + 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_map_config + 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_map_config + ] = mock_rpc + + request = {} + await client.delete_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_map_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapConfigRequest(), + {}, + ], +) +async def test_delete_map_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteMapConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_map_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.DeleteMapConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + call.return_value = None + client.delete_map_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 + + # 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_map_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.DeleteMapConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_map_config(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_map_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_map_config( + name="name_value", + force=True, + ) + + # 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 + arg = args[0].force + mock_val = True + assert arg == mock_val + + +def test_delete_map_config_flattened_error(): + client = MapManagementClient( + 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_map_config( + map_management_service.DeleteMapConfigRequest(), + name="name_value", + force=True, + ) + + +@pytest.mark.asyncio +async def test_delete_map_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_map_config( + name="name_value", + force=True, + ) + + # 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 + arg = args[0].force + mock_val = True + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_map_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_config( + map_management_service.DeleteMapConfigRequest(), + name="name_value", + force=True, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateStyleConfigRequest(), + {}, + ], +) +def test_create_style_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + response = client.create_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_create_style_config_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 = MapManagementClient( + 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 = map_management_service.CreateStyleConfigRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_style_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateStyleConfigRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_style_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_style_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.create_style_config] = ( + mock_rpc + ) + request = {} + client.create_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_style_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_create_style_config_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 = MapManagementAsyncClient( + 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_style_config + 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_style_config + ] = mock_rpc + + request = {} + await client.create_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_style_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateStyleConfigRequest(), + {}, + ], +) +async def test_create_style_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + response = await client.create_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_create_style_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.CreateStyleConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + call.return_value = map_management_service.StyleConfig() + client.create_style_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 + + # 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_style_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.CreateStyleConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + await client.create_style_config(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_style_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_style_config( + parent="parent_value", + style_config=map_management_service.StyleConfig(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].style_config + mock_val = map_management_service.StyleConfig(name="name_value") + assert arg == mock_val + + +def test_create_style_config_flattened_error(): + client = MapManagementClient( + 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_style_config( + map_management_service.CreateStyleConfigRequest(), + parent="parent_value", + style_config=map_management_service.StyleConfig(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_style_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_style_config( + parent="parent_value", + style_config=map_management_service.StyleConfig(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].style_config + mock_val = map_management_service.StyleConfig(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_style_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_style_config( + map_management_service.CreateStyleConfigRequest(), + parent="parent_value", + style_config=map_management_service.StyleConfig(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetStyleConfigRequest(), + {}, + ], +) +def test_get_style_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_style_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + response = client.get_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.GetStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_get_style_config_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 = MapManagementClient( + 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 = map_management_service.GetStyleConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_style_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetStyleConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_style_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_style_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_style_config] = ( + mock_rpc + ) + request = {} + client.get_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_style_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_style_config_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 = MapManagementAsyncClient( + 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_style_config + 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_style_config + ] = mock_rpc + + request = {} + await client.get_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_style_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetStyleConfigRequest(), + {}, + ], +) +async def test_get_style_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_style_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + response = await client.get_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.GetStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_get_style_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.GetStyleConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + call.return_value = map_management_service.StyleConfig() + client.get_style_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 + + # 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_style_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.GetStyleConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + await client.get_style_config(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_style_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_style_config( + 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_style_config_flattened_error(): + client = MapManagementClient( + 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_style_config( + map_management_service.GetStyleConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_style_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_style_config( + 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_style_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_style_config( + map_management_service.GetStyleConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListStyleConfigsRequest(), + {}, + ], +) +def test_list_style_configs(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_style_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListStyleConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_style_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.ListStyleConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStyleConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_style_configs_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 = MapManagementClient( + 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 = map_management_service.ListStyleConfigsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_style_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListStyleConfigsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +def test_list_style_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_style_configs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_style_configs] = ( + mock_rpc + ) + request = {} + client.list_style_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_style_configs(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_style_configs_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 = MapManagementAsyncClient( + 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_style_configs + 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_style_configs + ] = mock_rpc + + request = {} + await client.list_style_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_style_configs(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", + [ + map_management_service.ListStyleConfigsRequest(), + {}, + ], +) +async def test_list_style_configs_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_style_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListStyleConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_style_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.ListStyleConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStyleConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_style_configs_field_headers(): + client = MapManagementClient( + 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 = map_management_service.ListStyleConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + call.return_value = map_management_service.ListStyleConfigsResponse() + client.list_style_configs(request) + + # Establish that the 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_style_configs_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.ListStyleConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListStyleConfigsResponse() + ) + await client.list_style_configs(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_style_configs_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListStyleConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_style_configs( + 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_style_configs_flattened_error(): + client = MapManagementClient( + 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_style_configs( + map_management_service.ListStyleConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_style_configs_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListStyleConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListStyleConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_style_configs( + 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_style_configs_flattened_error_async(): + client = MapManagementAsyncClient( + 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_style_configs( + map_management_service.ListStyleConfigsRequest(), + parent="parent_value", + ) + + +def test_list_style_configs_pager(transport_name: str = "grpc"): + client = MapManagementClient( + 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_style_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[], + next_page_token="def", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_style_configs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, map_management_service.StyleConfig) for i in results) + + +def test_list_style_configs_pages(transport_name: str = "grpc"): + client = MapManagementClient( + 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_style_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[], + next_page_token="def", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_style_configs(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_style_configs_async_pager(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[], + next_page_token="def", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_style_configs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, map_management_service.StyleConfig) for i in responses) + + +@pytest.mark.asyncio +async def test_list_style_configs_async_pages(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[], + next_page_token="def", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_style_configs(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", + [ + map_management_service.UpdateStyleConfigRequest(), + {}, + ], +) +def test_update_style_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + response = client.update_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_update_style_config_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 = MapManagementClient( + 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 = map_management_service.UpdateStyleConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_style_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request_msg + + +def test_update_style_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_style_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_style_config] = ( + mock_rpc + ) + request = {} + client.update_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_style_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_update_style_config_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 = MapManagementAsyncClient( + 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_style_config + 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_style_config + ] = mock_rpc + + request = {} + await client.update_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_style_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateStyleConfigRequest(), + {}, + ], +) +async def test_update_style_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + response = await client.update_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +def test_update_style_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.UpdateStyleConfigRequest() + + request.style_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + call.return_value = map_management_service.StyleConfig() + client.update_style_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "style_config.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_style_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.UpdateStyleConfigRequest() + + request.style_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + await client.update_style_config(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", + "style_config.name=name_value", + ) in kw["metadata"] + + +def test_update_style_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_style_config( + style_config=map_management_service.StyleConfig(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].style_config + mock_val = map_management_service.StyleConfig(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_style_config_flattened_error(): + client = MapManagementClient( + 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_style_config( + map_management_service.UpdateStyleConfigRequest(), + style_config=map_management_service.StyleConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_style_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.StyleConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_style_config( + style_config=map_management_service.StyleConfig(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].style_config + mock_val = map_management_service.StyleConfig(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_style_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_style_config( + map_management_service.UpdateStyleConfigRequest(), + style_config=map_management_service.StyleConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteStyleConfigRequest(), + {}, + ], +) +def test_delete_style_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_style_config_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 = MapManagementClient( + 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 = map_management_service.DeleteStyleConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_style_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteStyleConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_style_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_style_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.delete_style_config] = ( + mock_rpc + ) + request = {} + client.delete_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_style_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_delete_style_config_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 = MapManagementAsyncClient( + 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_style_config + 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_style_config + ] = mock_rpc + + request = {} + await client.delete_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_style_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteStyleConfigRequest(), + {}, + ], +) +async def test_delete_style_config_async(request_type, transport: str = "grpc_asyncio"): + client = MapManagementAsyncClient( + 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_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteStyleConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_style_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.DeleteStyleConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + call.return_value = None + client.delete_style_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 + + # 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_style_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.DeleteStyleConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_style_config(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_style_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_style_config( + 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_style_config_flattened_error(): + client = MapManagementClient( + 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_style_config( + map_management_service.DeleteStyleConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_style_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_style_config( + 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_style_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_style_config( + map_management_service.DeleteStyleConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapContextConfigRequest(), + {}, + ], +) +def test_create_map_context_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + response = client.create_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_create_map_context_config_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 = MapManagementClient( + 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 = map_management_service.CreateMapContextConfigRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_map_context_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapContextConfigRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_map_context_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_context_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.create_map_context_config + ] = mock_rpc + request = {} + client.create_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_map_context_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_create_map_context_config_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 = MapManagementAsyncClient( + 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_map_context_config + 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_map_context_config + ] = mock_rpc + + request = {} + await client.create_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_map_context_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapContextConfigRequest(), + {}, + ], +) +async def test_create_map_context_config_async( + request_type, transport: str = "grpc_asyncio" +): + client = MapManagementAsyncClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + response = await client.create_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.CreateMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_create_map_context_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.CreateMapContextConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.create_map_context_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 + + # 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_map_context_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.CreateMapContextConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + await client.create_map_context_config(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_map_context_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_map_context_config( + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + 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].map_context_config + mock_val = map_management_service.MapContextConfig(name="name_value") + assert arg == mock_val + + +def test_create_map_context_config_flattened_error(): + client = MapManagementClient( + 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_map_context_config( + map_management_service.CreateMapContextConfigRequest(), + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_map_context_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_map_context_config( + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + 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].map_context_config + mock_val = map_management_service.MapContextConfig(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_map_context_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_context_config( + map_management_service.CreateMapContextConfigRequest(), + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapContextConfigRequest(), + {}, + ], +) +def test_get_map_context_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + response = client.get_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.GetMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_get_map_context_config_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 = MapManagementClient( + 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 = map_management_service.GetMapContextConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_map_context_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapContextConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_map_context_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_context_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_map_context_config] = ( + mock_rpc + ) + request = {} + client.get_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_map_context_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_map_context_config_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 = MapManagementAsyncClient( + 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_map_context_config + 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_map_context_config + ] = mock_rpc + + request = {} + await client.get_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_map_context_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapContextConfigRequest(), + {}, + ], +) +async def test_get_map_context_config_async( + request_type, transport: str = "grpc_asyncio" +): + client = MapManagementAsyncClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + response = await client.get_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.GetMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_get_map_context_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.GetMapContextConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.get_map_context_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 + + # 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_map_context_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.GetMapContextConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + await client.get_map_context_config(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_map_context_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_map_context_config( + 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_map_context_config_flattened_error(): + client = MapManagementClient( + 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_map_context_config( + map_management_service.GetMapContextConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_map_context_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_map_context_config( + 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_map_context_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_context_config( + map_management_service.GetMapContextConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListMapContextConfigsRequest(), + {}, + ], +) +def test_list_map_context_configs(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_context_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapContextConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_map_context_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.ListMapContextConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapContextConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_map_context_configs_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 = MapManagementClient( + 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 = map_management_service.ListMapContextConfigsRequest( + 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_map_context_configs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_map_context_configs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapContextConfigsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_map_context_configs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_context_configs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_map_context_configs + ] = mock_rpc + request = {} + client.list_map_context_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_map_context_configs(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_map_context_configs_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 = MapManagementAsyncClient( + 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_map_context_configs + 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_map_context_configs + ] = mock_rpc + + request = {} + await client.list_map_context_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_map_context_configs(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", + [ + map_management_service.ListMapContextConfigsRequest(), + {}, + ], +) +async def test_list_map_context_configs_async( + request_type, transport: str = "grpc_asyncio" +): + client = MapManagementAsyncClient( + 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_map_context_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapContextConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_map_context_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.ListMapContextConfigsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapContextConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_map_context_configs_field_headers(): + client = MapManagementClient( + 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 = map_management_service.ListMapContextConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + call.return_value = map_management_service.ListMapContextConfigsResponse() + client.list_map_context_configs(request) + + # Establish that the 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_map_context_configs_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.ListMapContextConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapContextConfigsResponse() + ) + await client.list_map_context_configs(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_map_context_configs_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapContextConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_map_context_configs( + 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_map_context_configs_flattened_error(): + client = MapManagementClient( + 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_map_context_configs( + map_management_service.ListMapContextConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_map_context_configs_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.ListMapContextConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapContextConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_map_context_configs( + 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_map_context_configs_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_context_configs( + map_management_service.ListMapContextConfigsRequest(), + parent="parent_value", + ) + + +def test_list_map_context_configs_pager(transport_name: str = "grpc"): + client = MapManagementClient( + 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_map_context_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[], + next_page_token="def", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_map_context_configs( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, map_management_service.MapContextConfig) for i in results + ) + + +def test_list_map_context_configs_pages(transport_name: str = "grpc"): + client = MapManagementClient( + 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_map_context_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[], + next_page_token="def", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_map_context_configs(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_map_context_configs_async_pager(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[], + next_page_token="def", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_map_context_configs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, map_management_service.MapContextConfig) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_map_context_configs_async_pages(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[], + next_page_token="def", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_map_context_configs(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", + [ + map_management_service.UpdateMapContextConfigRequest(), + {}, + ], +) +def test_update_map_context_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + response = client.update_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_update_map_context_config_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 = MapManagementClient( + 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 = map_management_service.UpdateMapContextConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_map_context_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request_msg + + +def test_update_map_context_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_context_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_map_context_config + ] = mock_rpc + request = {} + client.update_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_map_context_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_update_map_context_config_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 = MapManagementAsyncClient( + 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_map_context_config + 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_map_context_config + ] = mock_rpc + + request = {} + await client.update_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_map_context_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateMapContextConfigRequest(), + {}, + ], +) +async def test_update_map_context_config_async( + request_type, transport: str = "grpc_asyncio" +): + client = MapManagementAsyncClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + response = await client.update_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +def test_update_map_context_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.UpdateMapContextConfigRequest() + + request.map_context_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.update_map_context_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "map_context_config.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_map_context_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.UpdateMapContextConfigRequest() + + request.map_context_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + await client.update_map_context_config(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", + "map_context_config.name=name_value", + ) in kw["metadata"] + + +def test_update_map_context_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_map_context_config( + map_context_config=map_management_service.MapContextConfig( + 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].map_context_config + mock_val = map_management_service.MapContextConfig(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_map_context_config_flattened_error(): + client = MapManagementClient( + 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_map_context_config( + map_management_service.UpdateMapContextConfigRequest(), + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_map_context_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = map_management_service.MapContextConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_map_context_config( + map_context_config=map_management_service.MapContextConfig( + 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].map_context_config + mock_val = map_management_service.MapContextConfig(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_map_context_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_context_config( + map_management_service.UpdateMapContextConfigRequest(), + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapContextConfigRequest(), + {}, + ], +) +def test_delete_map_context_config(request_type, transport: str = "grpc"): + client = MapManagementClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_map_context_config_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 = MapManagementClient( + 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 = map_management_service.DeleteMapContextConfigRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_map_context_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapContextConfigRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_map_context_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = MapManagementClient( + 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_map_context_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.delete_map_context_config + ] = mock_rpc + request = {} + client.delete_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_map_context_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_delete_map_context_config_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 = MapManagementAsyncClient( + 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_map_context_config + 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_map_context_config + ] = mock_rpc + + request = {} + await client.delete_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_map_context_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 +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapContextConfigRequest(), + {}, + ], +) +async def test_delete_map_context_config_async( + request_type, transport: str = "grpc_asyncio" +): + client = MapManagementAsyncClient( + 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_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = map_management_service.DeleteMapContextConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_map_context_config_field_headers(): + client = MapManagementClient( + 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 = map_management_service.DeleteMapContextConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + call.return_value = None + client.delete_map_context_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 + + # 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_map_context_config_field_headers_async(): + client = MapManagementAsyncClient( + 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 = map_management_service.DeleteMapContextConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_map_context_config(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_map_context_config_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_map_context_config( + 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_map_context_config_flattened_error(): + client = MapManagementClient( + 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_map_context_config( + map_management_service.DeleteMapContextConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_map_context_config_flattened_async(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_map_context_config( + 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_map_context_config_flattened_error_async(): + client = MapManagementAsyncClient( + 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_map_context_config( + map_management_service.DeleteMapContextConfigRequest(), + name="name_value", + ) + + +def test_create_map_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 = MapManagementClient( + 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_map_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.create_map_config] = ( + mock_rpc + ) + + request = {} + client.create_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_map_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 + + +def test_create_map_config_rest_required_fields( + request_type=map_management_service.CreateMapConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_config._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_map_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapConfig() + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_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_create_map_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_map_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "mapConfig", + ) + ) + ) + + +def test_create_map_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + map_config=map_management_service.MapConfig(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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_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/{parent=projects/*}/mapConfigs" % client.transport._host, args[1] + ) + + +def test_create_map_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_config( + map_management_service.CreateMapConfigRequest(), + parent="parent_value", + map_config=map_management_service.MapConfig(name="name_value"), + ) + + +def test_get_map_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 = MapManagementClient( + 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_map_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_map_config] = mock_rpc + + request = {} + client.get_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_map_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 + + +def test_get_map_config_rest_required_fields( + request_type=map_management_service.GetMapConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_config._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_map_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" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapConfig() + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_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_get_map_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_map_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_map_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/mapConfigs/sample2"} + + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_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/*/mapConfigs/*}" % client.transport._host, args[1] + ) + + +def test_get_map_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_config( + map_management_service.GetMapConfigRequest(), + name="name_value", + ) + + +def test_list_map_configs_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 = MapManagementClient( + 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_map_configs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_map_configs] = ( + mock_rpc + ) + + request = {} + client.list_map_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_map_configs(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_map_configs_rest_required_fields( + request_type=map_management_service.ListMapConfigsRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_configs._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_map_configs._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.ListMapConfigsResponse() + # 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 = map_management_service.ListMapConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_configs(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_map_configs_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_map_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_map_configs_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.ListMapConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # 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 = map_management_service.ListMapConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_configs(**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/*}/mapConfigs" % client.transport._host, args[1] + ) + + +def test_list_map_configs_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_configs( + map_management_service.ListMapConfigsRequest(), + parent="parent_value", + ) + + +def test_list_map_configs_rest_pager(transport: str = "rest"): + client = MapManagementClient( + 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 = ( + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[], + next_page_token="def", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapConfigsResponse( + map_configs=[ + map_management_service.MapConfig(), + map_management_service.MapConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + map_management_service.ListMapConfigsResponse.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"} + + pager = client.list_map_configs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, map_management_service.MapConfig) for i in results) + + pages = list(client.list_map_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_map_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 = MapManagementClient( + 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_map_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_map_config] = ( + mock_rpc + ) + + request = {} + client.update_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_map_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 + + +def test_update_map_config_rest_required_fields( + request_type=map_management_service.UpdateMapConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_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_map_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapConfig() + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_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_map_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_map_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("mapConfig",))) + + +def test_update_map_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"map_config": {"name": "projects/sample1/mapConfigs/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + map_config=map_management_service.MapConfig(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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_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/{map_config.name=projects/*/mapConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_update_map_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_config( + map_management_service.UpdateMapConfigRequest(), + map_config=map_management_service.MapConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_map_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 = MapManagementClient( + 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_map_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.delete_map_config] = ( + mock_rpc + ) + + request = {} + client.delete_map_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_map_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 + + +def test_delete_map_config_rest_required_fields( + request_type=map_management_service.DeleteMapConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_config._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_map_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_map_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_delete_map_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_map_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +def test_delete_map_config_rest_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/mapConfigs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + force=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_map_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/*/mapConfigs/*}" % client.transport._host, args[1] + ) + + +def test_delete_map_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_config( + map_management_service.DeleteMapConfigRequest(), + name="name_value", + force=True, + ) + + +def test_create_style_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 = MapManagementClient( + 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_style_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.create_style_config] = ( + mock_rpc + ) + + request = {} + client.create_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_style_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 + + +def test_create_style_config_rest_required_fields( + request_type=map_management_service.CreateStyleConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_style_config._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_style_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.StyleConfig() + # 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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_style_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_create_style_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_style_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "styleConfig", + ) + ) + ) + + +def test_create_style_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.StyleConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + style_config=map_management_service.StyleConfig(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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_style_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/{parent=projects/*}/styleConfigs" % client.transport._host, args[1] + ) + + +def test_create_style_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_style_config( + map_management_service.CreateStyleConfigRequest(), + parent="parent_value", + style_config=map_management_service.StyleConfig(name="name_value"), + ) + + +def test_get_style_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 = MapManagementClient( + 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_style_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_style_config] = ( + mock_rpc + ) + + request = {} + client.get_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_style_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 + + +def test_get_style_config_rest_required_fields( + request_type=map_management_service.GetStyleConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_style_config._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_style_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" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.StyleConfig() + # 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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_style_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_get_style_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_style_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_style_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.StyleConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/styleConfigs/sample2"} + + # 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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_style_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/*/styleConfigs/*}" % client.transport._host, args[1] + ) + + +def test_get_style_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_style_config( + map_management_service.GetStyleConfigRequest(), + name="name_value", + ) + + +def test_list_style_configs_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 = MapManagementClient( + 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_style_configs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_style_configs] = ( + mock_rpc + ) + + request = {} + client.list_style_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_style_configs(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_style_configs_rest_required_fields( + request_type=map_management_service.ListStyleConfigsRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_style_configs._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_style_configs._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", + "view", + ) + ) + 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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.ListStyleConfigsResponse() + # 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 = map_management_service.ListStyleConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_style_configs(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_style_configs_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_style_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "view", + ) + ) + & set(("parent",)) + ) + + +def test_list_style_configs_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.ListStyleConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # 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 = map_management_service.ListStyleConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_style_configs(**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/*}/styleConfigs" % client.transport._host, args[1] + ) + + +def test_list_style_configs_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_style_configs( + map_management_service.ListStyleConfigsRequest(), + parent="parent_value", + ) + + +def test_list_style_configs_rest_pager(transport: str = "rest"): + client = MapManagementClient( + 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 = ( + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[], + next_page_token="def", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListStyleConfigsResponse( + style_configs=[ + map_management_service.StyleConfig(), + map_management_service.StyleConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + map_management_service.ListStyleConfigsResponse.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"} + + pager = client.list_style_configs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, map_management_service.StyleConfig) for i in results) + + pages = list(client.list_style_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_style_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 = MapManagementClient( + 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_style_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_style_config] = ( + mock_rpc + ) + + request = {} + client.update_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_style_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 + + +def test_update_style_config_rest_required_fields( + request_type=map_management_service.UpdateStyleConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_style_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_style_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.StyleConfig() + # 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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_style_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_style_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_style_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("styleConfig",))) + + +def test_update_style_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.StyleConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "style_config": {"name": "projects/sample1/styleConfigs/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + style_config=map_management_service.StyleConfig(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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_style_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/{style_config.name=projects/*/styleConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_style_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_style_config( + map_management_service.UpdateStyleConfigRequest(), + style_config=map_management_service.StyleConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_style_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 = MapManagementClient( + 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_style_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.delete_style_config] = ( + mock_rpc + ) + + request = {} + client.delete_style_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_style_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 + + +def test_delete_style_config_rest_required_fields( + request_type=map_management_service.DeleteStyleConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_style_config._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_style_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" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_style_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_delete_style_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_style_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_style_config_rest_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/styleConfigs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_style_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/*/styleConfigs/*}" % client.transport._host, args[1] + ) + + +def test_delete_style_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_style_config( + map_management_service.DeleteStyleConfigRequest(), + name="name_value", + ) + + +def test_create_map_context_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 = MapManagementClient( + 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_map_context_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.create_map_context_config + ] = mock_rpc + + request = {} + client.create_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_map_context_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 + + +def test_create_map_context_config_rest_required_fields( + request_type=map_management_service.CreateMapContextConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_context_config._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_map_context_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapContextConfig() + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_context_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_create_map_context_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_map_context_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "mapContextConfig", + ) + ) + ) + + +def test_create_map_context_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapContextConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/mapConfigs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_context_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/{parent=projects/*/mapConfigs/*}/mapContextConfigs" + % client.transport._host, + args[1], + ) + + +def test_create_map_context_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_context_config( + map_management_service.CreateMapContextConfigRequest(), + parent="parent_value", + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + ) + + +def test_get_map_context_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 = MapManagementClient( + 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_map_context_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_map_context_config] = ( + mock_rpc + ) + + request = {} + client.get_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_map_context_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 + + +def test_get_map_context_config_rest_required_fields( + request_type=map_management_service.GetMapContextConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_context_config._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_map_context_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" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapContextConfig() + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_context_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_get_map_context_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_map_context_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_map_context_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapContextConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_context_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/*/mapConfigs/*/mapContextConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_map_context_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_context_config( + map_management_service.GetMapContextConfigRequest(), + name="name_value", + ) + + +def test_list_map_context_configs_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 = MapManagementClient( + 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_map_context_configs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = 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_map_context_configs + ] = mock_rpc + + request = {} + client.list_map_context_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_map_context_configs(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_map_context_configs_rest_required_fields( + request_type=map_management_service.ListMapContextConfigsRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_context_configs._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_map_context_configs._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.ListMapContextConfigsResponse() + # 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 = map_management_service.ListMapContextConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_context_configs(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_map_context_configs_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_map_context_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_map_context_configs_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.ListMapContextConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/mapConfigs/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 = map_management_service.ListMapContextConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_context_configs(**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/*/mapConfigs/*}/mapContextConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_map_context_configs_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_context_configs( + map_management_service.ListMapContextConfigsRequest(), + parent="parent_value", + ) + + +def test_list_map_context_configs_rest_pager(transport: str = "rest"): + client = MapManagementClient( + 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 = ( + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + next_page_token="abc", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[], + next_page_token="def", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + ], + next_page_token="ghi", + ), + map_management_service.ListMapContextConfigsResponse( + map_context_configs=[ + map_management_service.MapContextConfig(), + map_management_service.MapContextConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + map_management_service.ListMapContextConfigsResponse.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/mapConfigs/sample2"} + + pager = client.list_map_context_configs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, map_management_service.MapContextConfig) for i in results + ) + + pages = list(client.list_map_context_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_map_context_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 = MapManagementClient( + 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_map_context_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_map_context_config + ] = mock_rpc + + request = {} + client.update_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_map_context_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 + + +def test_update_map_context_config_rest_required_fields( + request_type=map_management_service.UpdateMapContextConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_context_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_map_context_config._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 = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = map_management_service.MapContextConfig() + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_map_context_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_map_context_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_map_context_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("mapContextConfig",))) + + +def test_update_map_context_config_rest_flattened(): + client = MapManagementClient( + 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 = map_management_service.MapContextConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "map_context_config": { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + map_context_config=map_management_service.MapContextConfig( + 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_map_context_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/{map_context_config.name=projects/*/mapConfigs/*/mapContextConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_map_context_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_context_config( + map_management_service.UpdateMapContextConfigRequest(), + map_context_config=map_management_service.MapContextConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_map_context_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 = MapManagementClient( + 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_map_context_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.delete_map_context_config + ] = mock_rpc + + request = {} + client.delete_map_context_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_map_context_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 + + +def test_delete_map_context_config_rest_required_fields( + request_type=map_management_service.DeleteMapContextConfigRequest, +): + transport_class = transports.MapManagementRestTransport + + 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_map_context_config._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_map_context_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" + + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_map_context_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_delete_map_context_config_rest_unset_required_fields(): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_map_context_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_map_context_config_rest_flattened(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_map_context_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/*/mapConfigs/*/mapContextConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_map_context_config_rest_flattened_error(transport: str = "rest"): + client = MapManagementClient( + 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_map_context_config( + map_management_service.DeleteMapContextConfigRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapManagementClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MapManagementClient( + 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 = MapManagementClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MapManagementClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MapManagementClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MapManagementGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MapManagementGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + transports.MapManagementRestTransport, + ], +) +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 = MapManagementClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MapManagementClient( + 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_map_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + call.return_value = map_management_service.MapConfig() + client.create_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + call.return_value = map_management_service.MapConfig() + client.get_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_configs_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + call.return_value = map_management_service.ListMapConfigsResponse() + client.list_map_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapConfigsRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + call.return_value = map_management_service.MapConfig() + client.update_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + call.return_value = None + client.delete_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + call.return_value = map_management_service.StyleConfig() + client.create_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + call.return_value = map_management_service.StyleConfig() + client.get_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_configs_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + call.return_value = map_management_service.ListStyleConfigsResponse() + client.list_style_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListStyleConfigsRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + call.return_value = map_management_service.StyleConfig() + client.update_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + call.return_value = None + client.delete_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.create_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.get_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_configs_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + call.return_value = map_management_service.ListMapContextConfigsResponse() + client.list_map_context_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapContextConfigsRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + call.return_value = map_management_service.MapContextConfig() + client.update_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_grpc(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + call.return_value = None + client.delete_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapContextConfigRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MapManagementAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MapManagementAsyncClient( + 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_map_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + await client.create_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapConfigRequest() + assert args[0] == request_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_map_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + await client.get_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapConfigRequest() + assert args[0] == request_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_map_configs_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_map_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapConfigsRequest() + assert args[0] == request_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_map_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + ) + await client.update_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapConfigRequest() + assert args[0] == request_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_map_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapConfigRequest() + assert args[0] == request_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_style_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + await client.create_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateStyleConfigRequest() + assert args[0] == request_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_style_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + await client.get_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetStyleConfigRequest() + assert args[0] == request_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_style_configs_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListStyleConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_style_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListStyleConfigsRequest() + assert args[0] == request_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_style_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_value", + ) + ) + await client.update_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request_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_style_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteStyleConfigRequest() + assert args[0] == request_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_map_context_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + await client.create_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapContextConfigRequest() + assert args[0] == request_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_map_context_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + await client.get_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapContextConfigRequest() + assert args[0] == request_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_map_context_configs_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.ListMapContextConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_map_context_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapContextConfigsRequest() + assert args[0] == request_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_map_context_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + ) + await client.update_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request_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_map_context_config_empty_call_grpc_asyncio(): + client = MapManagementAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapContextConfigRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MapManagementClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_map_config_rest_bad_request( + request_type=map_management_service.CreateMapConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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_map_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapConfigRequest, + dict, + ], +) +def test_create_map_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["map_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "map_id": "map_id_value", + "map_features": {"simple_features": [1], "poi_boost_level": 1605}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "map_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 = map_management_service.CreateMapConfigRequest.meta.fields["map_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["map_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["map_config"][field])): + del request_init["map_config"][field][i][subfield] + else: + del request_init["map_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 = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_map_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_create_map_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_create_map_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_create_map_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.CreateMapConfigRequest.pb( + map_management_service.CreateMapConfigRequest() + ) + 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 = map_management_service.MapConfig.to_json( + map_management_service.MapConfig() + ) + req.return_value.content = return_value + + request = map_management_service.CreateMapConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapConfig() + post_with_metadata.return_value = map_management_service.MapConfig(), metadata + + client.create_map_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_map_config_rest_bad_request( + request_type=map_management_service.GetMapConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/mapConfigs/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.get_map_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapConfigRequest, + dict, + ], +) +def test_get_map_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/mapConfigs/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 = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_map_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_get_map_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, "post_get_map_config_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_get_map_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.GetMapConfigRequest.pb( + map_management_service.GetMapConfigRequest() + ) + 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 = map_management_service.MapConfig.to_json( + map_management_service.MapConfig() + ) + req.return_value.content = return_value + + request = map_management_service.GetMapConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapConfig() + post_with_metadata.return_value = map_management_service.MapConfig(), metadata + + client.get_map_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_map_configs_rest_bad_request( + request_type=map_management_service.ListMapConfigsRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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_map_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListMapConfigsRequest, + dict, + ], +) +def test_list_map_configs_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = map_management_service.ListMapConfigsResponse( + 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 = map_management_service.ListMapConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_map_configs_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_list_map_configs" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_list_map_configs_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_list_map_configs" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.ListMapConfigsRequest.pb( + map_management_service.ListMapConfigsRequest() + ) + 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 = map_management_service.ListMapConfigsResponse.to_json( + map_management_service.ListMapConfigsResponse() + ) + req.return_value.content = return_value + + request = map_management_service.ListMapConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.ListMapConfigsResponse() + post_with_metadata.return_value = ( + map_management_service.ListMapConfigsResponse(), + metadata, + ) + + client.list_map_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_map_config_rest_bad_request( + request_type=map_management_service.UpdateMapConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"map_config": {"name": "projects/sample1/mapConfigs/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.update_map_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateMapConfigRequest, + dict, + ], +) +def test_update_map_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"map_config": {"name": "projects/sample1/mapConfigs/sample2"}} + request_init["map_config"] = { + "name": "projects/sample1/mapConfigs/sample2", + "display_name": "display_name_value", + "description": "description_value", + "map_id": "map_id_value", + "map_features": {"simple_features": [1], "poi_boost_level": 1605}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "map_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 = map_management_service.UpdateMapConfigRequest.meta.fields["map_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["map_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["map_config"][field])): + del request_init["map_config"][field][i][subfield] + else: + del request_init["map_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 = map_management_service.MapConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + map_id="map_id_value", + map_type=map_management_service.MapRenderingType.VECTOR, + ) + + # 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 = map_management_service.MapConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.map_id == "map_id_value" + assert response.map_type == map_management_service.MapRenderingType.VECTOR + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_map_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_update_map_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_update_map_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_update_map_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.UpdateMapConfigRequest.pb( + map_management_service.UpdateMapConfigRequest() + ) + 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 = map_management_service.MapConfig.to_json( + map_management_service.MapConfig() + ) + req.return_value.content = return_value + + request = map_management_service.UpdateMapConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapConfig() + post_with_metadata.return_value = map_management_service.MapConfig(), metadata + + client.update_map_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_map_config_rest_bad_request( + request_type=map_management_service.DeleteMapConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/mapConfigs/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.delete_map_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapConfigRequest, + dict, + ], +) +def test_delete_map_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/mapConfigs/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 = 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_map_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_map_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "pre_delete_map_config" + ) as pre, + ): + pre.assert_not_called() + pb_message = map_management_service.DeleteMapConfigRequest.pb( + map_management_service.DeleteMapConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = map_management_service.DeleteMapConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_map_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_style_config_rest_bad_request( + request_type=map_management_service.CreateStyleConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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_style_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateStyleConfigRequest, + dict, + ], +) +def test_create_style_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["style_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "style_id": "style_id_value", + "json_style_sheet": "json_style_sheet_value", + "style_sheet": {"fields": {}}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_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 = map_management_service.CreateStyleConfigRequest.meta.fields[ + "style_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["style_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["style_config"][field])): + del request_init["style_config"][field][i][subfield] + else: + del request_init["style_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 = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_style_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_style_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_create_style_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_create_style_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_create_style_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.CreateStyleConfigRequest.pb( + map_management_service.CreateStyleConfigRequest() + ) + 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 = map_management_service.StyleConfig.to_json( + map_management_service.StyleConfig() + ) + req.return_value.content = return_value + + request = map_management_service.CreateStyleConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.StyleConfig() + post_with_metadata.return_value = map_management_service.StyleConfig(), metadata + + client.create_style_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_style_config_rest_bad_request( + request_type=map_management_service.GetStyleConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/styleConfigs/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.get_style_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetStyleConfigRequest, + dict, + ], +) +def test_get_style_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/styleConfigs/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 = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_style_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_style_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_get_style_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_get_style_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_get_style_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.GetStyleConfigRequest.pb( + map_management_service.GetStyleConfigRequest() + ) + 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 = map_management_service.StyleConfig.to_json( + map_management_service.StyleConfig() + ) + req.return_value.content = return_value + + request = map_management_service.GetStyleConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.StyleConfig() + post_with_metadata.return_value = map_management_service.StyleConfig(), metadata + + client.get_style_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_style_configs_rest_bad_request( + request_type=map_management_service.ListStyleConfigsRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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_style_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListStyleConfigsRequest, + dict, + ], +) +def test_list_style_configs_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = map_management_service.ListStyleConfigsResponse( + 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 = map_management_service.ListStyleConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_style_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStyleConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_style_configs_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_list_style_configs" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_list_style_configs_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_list_style_configs" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.ListStyleConfigsRequest.pb( + map_management_service.ListStyleConfigsRequest() + ) + 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 = map_management_service.ListStyleConfigsResponse.to_json( + map_management_service.ListStyleConfigsResponse() + ) + req.return_value.content = return_value + + request = map_management_service.ListStyleConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.ListStyleConfigsResponse() + post_with_metadata.return_value = ( + map_management_service.ListStyleConfigsResponse(), + metadata, + ) + + client.list_style_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_style_config_rest_bad_request( + request_type=map_management_service.UpdateStyleConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"style_config": {"name": "projects/sample1/styleConfigs/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.update_style_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateStyleConfigRequest, + dict, + ], +) +def test_update_style_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"style_config": {"name": "projects/sample1/styleConfigs/sample2"}} + request_init["style_config"] = { + "name": "projects/sample1/styleConfigs/sample2", + "display_name": "display_name_value", + "description": "description_value", + "style_id": "style_id_value", + "json_style_sheet": "json_style_sheet_value", + "style_sheet": {"fields": {}}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_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 = map_management_service.UpdateStyleConfigRequest.meta.fields[ + "style_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["style_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["style_config"][field])): + del request_init["style_config"][field][i][subfield] + else: + del request_init["style_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 = map_management_service.StyleConfig( + name="name_value", + display_name="display_name_value", + description="description_value", + style_id="style_id_value", + json_style_sheet="json_style_sheet_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 = map_management_service.StyleConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_style_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.StyleConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.style_id == "style_id_value" + assert response.json_style_sheet == "json_style_sheet_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_style_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_update_style_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_update_style_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_update_style_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.UpdateStyleConfigRequest.pb( + map_management_service.UpdateStyleConfigRequest() + ) + 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 = map_management_service.StyleConfig.to_json( + map_management_service.StyleConfig() + ) + req.return_value.content = return_value + + request = map_management_service.UpdateStyleConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.StyleConfig() + post_with_metadata.return_value = map_management_service.StyleConfig(), metadata + + client.update_style_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_style_config_rest_bad_request( + request_type=map_management_service.DeleteStyleConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/styleConfigs/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.delete_style_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteStyleConfigRequest, + dict, + ], +) +def test_delete_style_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/styleConfigs/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 = 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_style_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_style_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "pre_delete_style_config" + ) as pre, + ): + pre.assert_not_called() + pb_message = map_management_service.DeleteStyleConfigRequest.pb( + map_management_service.DeleteStyleConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = map_management_service.DeleteStyleConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_style_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_map_context_config_rest_bad_request( + request_type=map_management_service.CreateMapContextConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/mapConfigs/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_map_context_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.CreateMapContextConfigRequest, + dict, + ], +) +def test_create_map_context_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/mapConfigs/sample2"} + request_init["map_context_config"] = { + "name": "name_value", + "map_config": "map_config_value", + "style_config": "style_config_value", + "dataset": ["dataset_value1", "dataset_value2"], + "alias": "alias_value", + "map_variants": [1], + "create_time": {"seconds": 751, "nanos": 543}, + "update_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 = map_management_service.CreateMapContextConfigRequest.meta.fields[ + "map_context_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["map_context_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["map_context_config"][field])): + del request_init["map_context_config"][field][i][subfield] + else: + del request_init["map_context_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 = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_context_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_map_context_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_create_map_context_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_create_map_context_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_create_map_context_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.CreateMapContextConfigRequest.pb( + map_management_service.CreateMapContextConfigRequest() + ) + 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 = map_management_service.MapContextConfig.to_json( + map_management_service.MapContextConfig() + ) + req.return_value.content = return_value + + request = map_management_service.CreateMapContextConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapContextConfig() + post_with_metadata.return_value = ( + map_management_service.MapContextConfig(), + metadata, + ) + + client.create_map_context_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_map_context_config_rest_bad_request( + request_type=map_management_service.GetMapContextConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/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_map_context_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.GetMapContextConfigRequest, + dict, + ], +) +def test_get_map_context_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/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 = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_context_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_map_context_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_get_map_context_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_get_map_context_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_get_map_context_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.GetMapContextConfigRequest.pb( + map_management_service.GetMapContextConfigRequest() + ) + 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 = map_management_service.MapContextConfig.to_json( + map_management_service.MapContextConfig() + ) + req.return_value.content = return_value + + request = map_management_service.GetMapContextConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapContextConfig() + post_with_metadata.return_value = ( + map_management_service.MapContextConfig(), + metadata, + ) + + client.get_map_context_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_map_context_configs_rest_bad_request( + request_type=map_management_service.ListMapContextConfigsRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/mapConfigs/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_map_context_configs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.ListMapContextConfigsRequest, + dict, + ], +) +def test_list_map_context_configs_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/mapConfigs/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 = map_management_service.ListMapContextConfigsResponse( + 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 = map_management_service.ListMapContextConfigsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_context_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMapContextConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_map_context_configs_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_list_map_context_configs" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_list_map_context_configs_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_list_map_context_configs" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.ListMapContextConfigsRequest.pb( + map_management_service.ListMapContextConfigsRequest() + ) + 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 = map_management_service.ListMapContextConfigsResponse.to_json( + map_management_service.ListMapContextConfigsResponse() + ) + req.return_value.content = return_value + + request = map_management_service.ListMapContextConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.ListMapContextConfigsResponse() + post_with_metadata.return_value = ( + map_management_service.ListMapContextConfigsResponse(), + metadata, + ) + + client.list_map_context_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_map_context_config_rest_bad_request( + request_type=map_management_service.UpdateMapContextConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "map_context_config": { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/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_map_context_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.UpdateMapContextConfigRequest, + dict, + ], +) +def test_update_map_context_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "map_context_config": { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/sample3" + } + } + request_init["map_context_config"] = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/sample3", + "map_config": "map_config_value", + "style_config": "style_config_value", + "dataset": ["dataset_value1", "dataset_value2"], + "alias": "alias_value", + "map_variants": [1], + "create_time": {"seconds": 751, "nanos": 543}, + "update_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 = map_management_service.UpdateMapContextConfigRequest.meta.fields[ + "map_context_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["map_context_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["map_context_config"][field])): + del request_init["map_context_config"][field][i][subfield] + else: + del request_init["map_context_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 = map_management_service.MapContextConfig( + name="name_value", + map_config="map_config_value", + style_config="style_config_value", + dataset=["dataset_value"], + alias="alias_value", + map_variants=[ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ], + ) + + # 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 = map_management_service.MapContextConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_map_context_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, map_management_service.MapContextConfig) + assert response.name == "name_value" + assert response.map_config == "map_config_value" + assert response.style_config == "style_config_value" + assert response.dataset == ["dataset_value"] + assert response.alias == "alias_value" + assert response.map_variants == [ + map_management_service.MapContextConfig.MapVariant.ROADMAP_DARK + ] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_map_context_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "post_update_map_context_config" + ) as post, + mock.patch.object( + transports.MapManagementRestInterceptor, + "post_update_map_context_config_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MapManagementRestInterceptor, "pre_update_map_context_config" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = map_management_service.UpdateMapContextConfigRequest.pb( + map_management_service.UpdateMapContextConfigRequest() + ) + 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 = map_management_service.MapContextConfig.to_json( + map_management_service.MapContextConfig() + ) + req.return_value.content = return_value + + request = map_management_service.UpdateMapContextConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = map_management_service.MapContextConfig() + post_with_metadata.return_value = ( + map_management_service.MapContextConfig(), + metadata, + ) + + client.update_map_context_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_map_context_config_rest_bad_request( + request_type=map_management_service.DeleteMapContextConfigRequest, +): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/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_map_context_config(request) + + +@pytest.mark.parametrize( + "request_type", + [ + map_management_service.DeleteMapContextConfigRequest, + dict, + ], +) +def test_delete_map_context_config_rest_call_success(request_type): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/mapConfigs/sample2/mapContextConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_map_context_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_map_context_config_rest_interceptors(null_interceptor): + transport = transports.MapManagementRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MapManagementRestInterceptor(), + ) + client = MapManagementClient(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.MapManagementRestInterceptor, "pre_delete_map_context_config" + ) as pre, + ): + pre.assert_not_called() + pb_message = map_management_service.DeleteMapContextConfigRequest.pb( + map_management_service.DeleteMapContextConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = map_management_service.DeleteMapContextConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_map_context_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_initialize_client_w_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_map_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_config), "__call__" + ) as call: + client.create_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_map_config), "__call__") as call: + client.get_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_configs_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_map_configs), "__call__") as call: + client.list_map_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapConfigsRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_config), "__call__" + ) as call: + client.update_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapConfigRequest() + assert args[0] == request_msg + + +# This 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_map_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_config), "__call__" + ) as call: + client.delete_map_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_style_config), "__call__" + ) as call: + client.create_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_style_config), "__call__") as call: + client.get_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_configs_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_style_configs), "__call__" + ) as call: + client.list_style_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListStyleConfigsRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_style_config), "__call__" + ) as call: + client.update_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_style_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_style_config), "__call__" + ) as call: + client.delete_style_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteStyleConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_map_context_config), "__call__" + ) as call: + client.create_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.CreateMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_map_context_config), "__call__" + ) as call: + client.get_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.GetMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_configs_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_map_context_configs), "__call__" + ) as call: + client.list_map_context_configs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.ListMapContextConfigsRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_map_context_config), "__call__" + ) as call: + client.update_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.UpdateMapContextConfigRequest() + assert args[0] == request_msg + + +# This 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_map_context_config_empty_call_rest(): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_map_context_config), "__call__" + ) as call: + client.delete_map_context_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = map_management_service.DeleteMapContextConfigRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.MapManagementGrpcTransport, + ) + + +def test_map_management_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.MapManagementTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_map_management_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.maps.mapmanagement_v2.services.map_management.transports.MapManagementTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.MapManagementTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_map_config", + "get_map_config", + "list_map_configs", + "update_map_config", + "delete_map_config", + "create_style_config", + "get_style_config", + "list_style_configs", + "update_style_config", + "delete_style_config", + "create_map_context_config", + "get_map_context_config", + "list_map_context_configs", + "update_map_context_config", + "delete_map_context_config", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_map_management_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.maps.mapmanagement_v2.services.map_management.transports.MapManagementTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MapManagementTransport( + 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_map_management_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.maps.mapmanagement_v2.services.map_management.transports.MapManagementTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.MapManagementTransport() + adc.assert_called_once() + + +def test_map_management_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) + MapManagementClient() + 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.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + ], +) +def test_map_management_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.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + transports.MapManagementRestTransport, + ], +) +def test_map_management_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.MapManagementGrpcTransport, grpc_helpers), + (transports.MapManagementGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_map_management_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( + "mapmanagement.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="mapmanagement.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + ], +) +def test_map_management_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_map_management_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.MapManagementRestTransport( + 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_map_management_host_no_port(transport_name): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="mapmanagement.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "mapmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://mapmanagement.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_map_management_host_with_port(transport_name): + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="mapmanagement.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "mapmanagement.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://mapmanagement.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_map_management_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = MapManagementClient( + credentials=creds1, + transport=transport_name, + ) + client2 = MapManagementClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_map_config._session + session2 = client2.transport.create_map_config._session + assert session1 != session2 + session1 = client1.transport.get_map_config._session + session2 = client2.transport.get_map_config._session + assert session1 != session2 + session1 = client1.transport.list_map_configs._session + session2 = client2.transport.list_map_configs._session + assert session1 != session2 + session1 = client1.transport.update_map_config._session + session2 = client2.transport.update_map_config._session + assert session1 != session2 + session1 = client1.transport.delete_map_config._session + session2 = client2.transport.delete_map_config._session + assert session1 != session2 + session1 = client1.transport.create_style_config._session + session2 = client2.transport.create_style_config._session + assert session1 != session2 + session1 = client1.transport.get_style_config._session + session2 = client2.transport.get_style_config._session + assert session1 != session2 + session1 = client1.transport.list_style_configs._session + session2 = client2.transport.list_style_configs._session + assert session1 != session2 + session1 = client1.transport.update_style_config._session + session2 = client2.transport.update_style_config._session + assert session1 != session2 + session1 = client1.transport.delete_style_config._session + session2 = client2.transport.delete_style_config._session + assert session1 != session2 + session1 = client1.transport.create_map_context_config._session + session2 = client2.transport.create_map_context_config._session + assert session1 != session2 + session1 = client1.transport.get_map_context_config._session + session2 = client2.transport.get_map_context_config._session + assert session1 != session2 + session1 = client1.transport.list_map_context_configs._session + session2 = client2.transport.list_map_context_configs._session + assert session1 != session2 + session1 = client1.transport.update_map_context_config._session + session2 = client2.transport.update_map_context_config._session + assert session1 != session2 + session1 = client1.transport.delete_map_context_config._session + session2 = client2.transport.delete_map_context_config._session + assert session1 != session2 + + +def test_map_management_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MapManagementGrpcTransport( + 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_map_management_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.MapManagementGrpcAsyncIOTransport( + 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.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + ], +) +def test_map_management_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.MapManagementGrpcTransport, + transports.MapManagementGrpcAsyncIOTransport, + ], +) +def test_map_management_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_dataset_path(): + project = "squid" + dataset = "clam" + expected = "projects/{project}/datasets/{dataset}".format( + project=project, + dataset=dataset, + ) + actual = MapManagementClient.dataset_path(project, dataset) + assert expected == actual + + +def test_parse_dataset_path(): + expected = { + "project": "whelk", + "dataset": "octopus", + } + path = MapManagementClient.dataset_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_dataset_path(path) + assert expected == actual + + +def test_map_config_path(): + project = "oyster" + map_config = "nudibranch" + expected = "projects/{project}/mapConfigs/{map_config}".format( + project=project, + map_config=map_config, + ) + actual = MapManagementClient.map_config_path(project, map_config) + assert expected == actual + + +def test_parse_map_config_path(): + expected = { + "project": "cuttlefish", + "map_config": "mussel", + } + path = MapManagementClient.map_config_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_map_config_path(path) + assert expected == actual + + +def test_map_context_config_path(): + project = "winkle" + map_config = "nautilus" + map_context_config = "scallop" + expected = "projects/{project}/mapConfigs/{map_config}/mapContextConfigs/{map_context_config}".format( + project=project, + map_config=map_config, + map_context_config=map_context_config, + ) + actual = MapManagementClient.map_context_config_path( + project, map_config, map_context_config + ) + assert expected == actual + + +def test_parse_map_context_config_path(): + expected = { + "project": "abalone", + "map_config": "squid", + "map_context_config": "clam", + } + path = MapManagementClient.map_context_config_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_map_context_config_path(path) + assert expected == actual + + +def test_style_config_path(): + project = "whelk" + style_config = "octopus" + expected = "projects/{project}/styleConfigs/{style_config}".format( + project=project, + style_config=style_config, + ) + actual = MapManagementClient.style_config_path(project, style_config) + assert expected == actual + + +def test_parse_style_config_path(): + expected = { + "project": "oyster", + "style_config": "nudibranch", + } + path = MapManagementClient.style_config_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_style_config_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = MapManagementClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = MapManagementClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = MapManagementClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = MapManagementClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = MapManagementClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = MapManagementClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = MapManagementClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = MapManagementClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = MapManagementClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = MapManagementClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = MapManagementClient.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.MapManagementTransport, "_prep_wrapped_messages" + ) as prep: + client = MapManagementClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.MapManagementTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = MapManagementClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = MapManagementClient( + 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 = MapManagementAsyncClient( + 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 = MapManagementClient( + 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 = MapManagementClient( + 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", + [ + (MapManagementClient, transports.MapManagementGrpcTransport), + (MapManagementAsyncClient, transports.MapManagementGrpcAsyncIOTransport), + ], +) +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-maps-routing/google/maps/routing_v2/types/polyline_details.py b/packages/google-maps-routing/google/maps/routing_v2/types/polyline_details.py index 6322daa0fae9..cb8bc2068f42 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/polyline_details.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/polyline_details.py @@ -34,10 +34,20 @@ class PolylineDetails(proto.Message): associated metadata. Attributes: + tunnel_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.TunnelInfo]): + Tunnel details along the polyline. This field is populated + if the request specifies the ``avoid_tunnels`` route + modifier and the resultant route fails to avoid them, OR if + ``TUNNEL_INFO_ON_POLYLINE`` is specified in + ``extra_computations`` and the route contains tunnels. flyover_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.FlyoverInfo]): Flyover details along the polyline. narrow_road_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.NarrowRoadInfo]): Narrow road details along the polyline. + bridge_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.BridgeInfo]): + Bridge details along the polyline. + skyway_info (MutableSequence[google.maps.routing_v2.types.PolylineDetails.SkywayInfo]): + Skyway details along the polyline. """ class RoadFeatureState(proto.Enum): @@ -89,6 +99,75 @@ class PolylinePointIndex(proto.Message): optional=True, ) + class TunnelInfo(proto.Message): + r"""Encapsulates information about tunnels along the polyline. + + Attributes: + tunnel_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): + Denotes whether a tunnel exists for a given + stretch of the polyline. + polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): + The location of tunnel related information + along the polyline. + """ + + tunnel_presence: "PolylineDetails.RoadFeatureState" = proto.Field( + proto.ENUM, + number=1, + enum="PolylineDetails.RoadFeatureState", + ) + polyline_point_index: "PolylineDetails.PolylinePointIndex" = proto.Field( + proto.MESSAGE, + number=2, + message="PolylineDetails.PolylinePointIndex", + ) + + class BridgeInfo(proto.Message): + r"""Encapsulates information about bridges along the polyline. + + Attributes: + bridge_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): + Denotes whether a bridge exists for a given + stretch of the polyline. + polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): + The location of bridge related information + along the polyline. + """ + + bridge_presence: "PolylineDetails.RoadFeatureState" = proto.Field( + proto.ENUM, + number=1, + enum="PolylineDetails.RoadFeatureState", + ) + polyline_point_index: "PolylineDetails.PolylinePointIndex" = proto.Field( + proto.MESSAGE, + number=2, + message="PolylineDetails.PolylinePointIndex", + ) + + class SkywayInfo(proto.Message): + r"""Encapsulates information about skyways along the polyline. + + Attributes: + skyway_presence (google.maps.routing_v2.types.PolylineDetails.RoadFeatureState): + Denotes whether a skyway exists for a given + stretch of the polyline. + polyline_point_index (google.maps.routing_v2.types.PolylineDetails.PolylinePointIndex): + The location of skyway related information + along the polyline. + """ + + skyway_presence: "PolylineDetails.RoadFeatureState" = proto.Field( + proto.ENUM, + number=1, + enum="PolylineDetails.RoadFeatureState", + ) + polyline_point_index: "PolylineDetails.PolylinePointIndex" = proto.Field( + proto.MESSAGE, + number=2, + message="PolylineDetails.PolylinePointIndex", + ) + class FlyoverInfo(proto.Message): r"""Encapsulates information about flyovers along the polyline. @@ -136,6 +215,11 @@ class NarrowRoadInfo(proto.Message): message="PolylineDetails.PolylinePointIndex", ) + tunnel_info: MutableSequence[TunnelInfo] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=TunnelInfo, + ) flyover_info: MutableSequence[FlyoverInfo] = proto.RepeatedField( proto.MESSAGE, number=12, @@ -146,6 +230,16 @@ class NarrowRoadInfo(proto.Message): number=13, message=NarrowRoadInfo, ) + bridge_info: MutableSequence[BridgeInfo] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=BridgeInfo, + ) + skyway_info: MutableSequence[SkywayInfo] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message=SkywayInfo, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py index 2203cd2759c6..5baf6eea1e23 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py @@ -64,6 +64,14 @@ class RouteModifiers(proto.Message): as unknown and tries to return the cash price. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_tunnels (bool): + Optional. When set to true, avoids tunnels where reasonable, + giving preference to routes not containing tunnels. Applies + only to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] + must be set to ``TRAFFIC_AWARE_OPTIMAL``. This field is not + supported in ComputeRouteMatrix. """ avoid_tolls: bool = proto.Field( @@ -92,6 +100,10 @@ class RouteModifiers(proto.Message): number=6, enum=gmr_toll_passes.TollPass, ) + avoid_tunnels: bool = proto.Field( + proto.BOOL, + number=7, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index 9b62bcf9a0ae..7d4634437ab6 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -147,9 +147,9 @@ class ComputeRoutesRequest(proto.Message): the overall cost of the route by re-ordering the specified intermediate waypoints. The request fails if any of the intermediate waypoints is a ``via`` waypoint. Use - ``ComputeRoutesResponse.Routes.optimized_intermediate_waypoint_index`` + ``ComputeRoutesResponse.routes.optimized_intermediate_waypoint_index`` to find the new ordering. If - ``ComputeRoutesResponseroutes.optimized_intermediate_waypoint_index`` + ``ComputeRoutesResponse.routes.optimized_intermediate_waypoint_index`` is not requested in the ``X-Goog-FieldMask`` header, the request fails. If ``optimize_waypoint_order`` is set to false, @@ -229,6 +229,7 @@ class ReferenceRoute(proto.Enum): class ExtraComputation(proto.Enum): r"""Extra computations to perform while completing the request. + Additional values may be added in the future. Values: EXTRA_COMPUTATION_UNSPECIFIED (0): @@ -241,24 +242,36 @@ class ExtraComputation(proto.Enum): TRAFFIC_ON_POLYLINE (3): Traffic aware polylines for the route(s). HTML_FORMATTED_NAVIGATION_INSTRUCTIONS (4): - ```NavigationInstructions`` `__ + [``NavigationInstruction``][google.maps.routing.v2.NavigationInstruction] presented as a formatted HTML text string. This content is meant to be read as-is. This content is for display only. Do not programmatically parse it. FLYOVER_INFO_ON_POLYLINE (7): Flyover information for the route(s). The ``routes.polyline_details.flyover_info`` fieldmask must be - specified to return this information. This data will only - currently be populated for certain metros in India. This - feature is experimental, and the SKU/charge is subject to - change. + specified to return this information. This data will + currently only be populated for certain metros in India. + This feature is experimental, and the SKU/charge is subject + to change. NARROW_ROAD_INFO_ON_POLYLINE (8): Narrow road information for the route(s). The ``routes.polyline_details.narrow_road_info`` fieldmask must - be specified to return this information. This data will only - currently be populated for certain metros in India. This - feature is experimental, and the SKU/charge is subject to - change. + be specified to return this information. This data will + currently only be populated for certain metros in India. + This feature is experimental, and the SKU/charge is subject + to change. + TUNNEL_INFO_ON_POLYLINE (9): + Tunnel information for the route(s). The + ``routes.polyline_details.tunnel_info`` fieldmask must be + specified to return this information. + BRIDGE_INFO_ON_POLYLINE (10): + Bridge information for the route(s). The + ``routes.polyline_details.bridge_info`` fieldmask must be + specified to return this information. + SKYWAY_INFO_ON_POLYLINE (11): + Skyway information for the route(s). The + ``routes.polyline_details.skyway_info`` fieldmask must be + specified to return this information. """ EXTRA_COMPUTATION_UNSPECIFIED = 0 @@ -268,6 +281,9 @@ class ExtraComputation(proto.Enum): HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 FLYOVER_INFO_ON_POLYLINE = 7 NARROW_ROAD_INFO_ON_POLYLINE = 8 + TUNNEL_INFO_ON_POLYLINE = 9 + BRIDGE_INFO_ON_POLYLINE = 10 + SKYWAY_INFO_ON_POLYLINE = 11 origin: gmr_waypoint.Waypoint = proto.Field( proto.MESSAGE, diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py index c0bb0f647c9c..9804f0870c1e 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py @@ -189,6 +189,8 @@ class TollPass(proto.Enum): MI, USA. US_MI_BCPASS (94): MI, USA. + US_MI_BREAKAWAY (101): + MI, USA. US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): MI, USA. US_MI_IQ_PROX_CARD (38): @@ -331,6 +333,7 @@ class TollPass(proto.Enum): US_ME_EZPASSME = 35 US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 US_MI_BCPASS = 94 + US_MI_BREAKAWAY = 101 US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 US_MI_IQ_PROX_CARD = 38 US_MI_IQ_TAG = 95 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py index fe6b6a19c022..c23284d7a656 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py @@ -59,7 +59,7 @@ class Waypoint(proto.Message): This field is a member of `oneof`_ ``location_type``. navigation_point_token (str): A token that identifies a - ```NavigationPoint`` `__, + ```NavigationPoint`` `__, obtained from the ``SearchDestinations`` method of the Geocoding API. diff --git a/release-please-individual-config.json b/release-please-individual-config.json index d218ce1f5f3b..51ac86e28b02 100644 --- a/release-please-individual-config.json +++ b/release-please-individual-config.json @@ -2,6 +2,18 @@ "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, "packages": { + "packages/google-cloud-ftp": { + "component": "google-cloud-ftp", + "extra-files": [ + "google/cloud/ftp/gapic_version.py", + "google/cloud/ftp_v1/gapic_version.py", + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.ftp.v1.json", + "type": "json" + } + ] + }, "packages/google-cloud-workloadidentity": { "component": "google-cloud-workloadidentity", "extra-files": [ @@ -14,21 +26,27 @@ } ] }, - "packages/google-cloud-ftp": { - "component": "google-cloud-ftp", + "packages/google-crc32c": { + "component": "google-crc32c" + }, + "packages/google-maps-mapmanagement": { + "component": "google-maps-mapmanagement", "extra-files": [ - "google/cloud/ftp/gapic_version.py", - "google/cloud/ftp_v1/gapic_version.py", + "google/maps/mapmanagement/gapic_version.py", + "google/maps/mapmanagement_v2/gapic_version.py", + "google/maps/mapmanagement_v2beta/gapic_version.py", { "jsonpath": "$.clientLibrary.version", - "path": "samples/generated_samples/snippet_metadata_google.cloud.ftp.v1.json", + "path": "samples/generated_samples/snippet_metadata_google.maps.mapmanagement.v2.json", + "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.maps.mapmanagement.v2beta.json", "type": "json" } ] }, - "packages/google-crc32c": { - "component": "google-crc32c" - }, "preview-packages/google-cloud-compute": { "draft-pull-request": true, "extra-files": [ @@ -43,4 +61,4 @@ }, "release-type": "python-librarian", "separate-pull-requests": true -} +} \ No newline at end of file