diff --git a/packages/google-cloud-compute/docs/compute_v1/region_instance_templates.rst b/packages/google-cloud-compute/docs/compute_v1/region_instance_templates.rst new file mode 100644 index 000000000000..bbeffb6e22cc --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/region_instance_templates.rst @@ -0,0 +1,10 @@ +RegionInstanceTemplates +----------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.region_instance_templates + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.region_instance_templates.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/services.rst b/packages/google-cloud-compute/docs/compute_v1/services.rst index aad91eef76b8..362c98cffae9 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services.rst @@ -56,6 +56,7 @@ Services for Google Cloud Compute v1 API region_instance_group_managers region_instance_groups region_instances + region_instance_templates region_network_endpoint_groups region_network_firewall_policies region_notification_endpoints diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 11772f30c5ce..853aec1a773f 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -132,6 +132,9 @@ from google.cloud.compute_v1.services.region_instance_groups.client import ( RegionInstanceGroupsClient, ) +from google.cloud.compute_v1.services.region_instance_templates.client import ( + RegionInstanceTemplatesClient, +) from google.cloud.compute_v1.services.region_instances.client import ( RegionInstancesClient, ) @@ -257,6 +260,7 @@ AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, + AggregatedListInstanceTemplatesRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -416,6 +420,7 @@ DeleteRegionHealthCheckRequest, DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, + DeleteRegionInstanceTemplateRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -596,6 +601,7 @@ GetRegionHealthCheckServiceRequest, GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, + GetRegionInstanceTemplateRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -725,6 +731,7 @@ InsertRegionHealthCheckRequest, InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, + InsertRegionInstanceTemplateRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -812,10 +819,13 @@ InstancesSetMachineResourcesRequest, InstancesSetMachineTypeRequest, InstancesSetMinCpuPlatformRequest, + InstancesSetNameRequest, InstancesSetServiceAccountRequest, InstancesStartWithEncryptionKeyRequest, InstanceTemplate, + InstanceTemplateAggregatedList, InstanceTemplateList, + InstanceTemplatesScopedList, InstanceWithNamedPorts, Int64RangeMatch, Interconnect, @@ -910,6 +920,7 @@ ListRegionHealthChecksRequest, ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, + ListRegionInstanceTemplatesRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -1248,6 +1259,9 @@ SecurityPolicyRuleHttpHeaderActionHttpHeaderOption, SecurityPolicyRuleMatcher, SecurityPolicyRuleMatcherConfig, + SecurityPolicyRulePreconfiguredWafConfig, + SecurityPolicyRulePreconfiguredWafConfigExclusion, + SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams, SecurityPolicyRuleRateLimitOptions, SecurityPolicyRuleRateLimitOptionsThreshold, SecurityPolicyRuleRedirectOptions, @@ -1318,6 +1332,7 @@ SetMinCpuPlatformInstanceRequest, SetNamedPortsInstanceGroupRequest, SetNamedPortsRegionInstanceGroupRequest, + SetNameInstanceRequest, SetNodeTemplateNodeGroupRequest, SetPrivateIpGoogleAccessSubnetworkRequest, SetProxyHeaderTargetSslProxyRequest, @@ -1461,6 +1476,7 @@ UpdateAutoscalerRequest, UpdateBackendBucketRequest, UpdateBackendServiceRequest, + UpdateDiskRequest, UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateHealthCheckRequest, @@ -1472,6 +1488,7 @@ UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, + UpdateRegionDiskRequest, UpdateRegionHealthCheckRequest, UpdateRegionUrlMapRequest, UpdateReservationRequest, @@ -1583,6 +1600,7 @@ "RegionInstanceGroupManagersClient", "RegionInstanceGroupsClient", "RegionInstancesClient", + "RegionInstanceTemplatesClient", "RegionNetworkEndpointGroupsClient", "RegionNetworkFirewallPoliciesClient", "RegionNotificationEndpointsClient", @@ -1662,6 +1680,7 @@ "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", "AggregatedListInstancesRequest", + "AggregatedListInstanceTemplatesRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -1821,6 +1840,7 @@ "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", + "DeleteRegionInstanceTemplateRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -2001,6 +2021,7 @@ "GetRegionHealthCheckServiceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", + "GetRegionInstanceTemplateRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -2130,6 +2151,7 @@ "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", + "InsertRegionInstanceTemplateRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -2217,10 +2239,13 @@ "InstancesSetMachineResourcesRequest", "InstancesSetMachineTypeRequest", "InstancesSetMinCpuPlatformRequest", + "InstancesSetNameRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", "InstanceTemplate", + "InstanceTemplateAggregatedList", "InstanceTemplateList", + "InstanceTemplatesScopedList", "InstanceWithNamedPorts", "Int64RangeMatch", "Interconnect", @@ -2315,6 +2340,7 @@ "ListRegionHealthChecksRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", + "ListRegionInstanceTemplatesRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2653,6 +2679,9 @@ "SecurityPolicyRuleHttpHeaderActionHttpHeaderOption", "SecurityPolicyRuleMatcher", "SecurityPolicyRuleMatcherConfig", + "SecurityPolicyRulePreconfiguredWafConfig", + "SecurityPolicyRulePreconfiguredWafConfigExclusion", + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", "SecurityPolicyRuleRateLimitOptions", "SecurityPolicyRuleRateLimitOptionsThreshold", "SecurityPolicyRuleRedirectOptions", @@ -2723,6 +2752,7 @@ "SetMinCpuPlatformInstanceRequest", "SetNamedPortsInstanceGroupRequest", "SetNamedPortsRegionInstanceGroupRequest", + "SetNameInstanceRequest", "SetNodeTemplateNodeGroupRequest", "SetPrivateIpGoogleAccessSubnetworkRequest", "SetProxyHeaderTargetSslProxyRequest", @@ -2866,6 +2896,7 @@ "UpdateAutoscalerRequest", "UpdateBackendBucketRequest", "UpdateBackendServiceRequest", + "UpdateDiskRequest", "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateHealthCheckRequest", @@ -2877,6 +2908,7 @@ "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", + "UpdateRegionDiskRequest", "UpdateRegionHealthCheckRequest", "UpdateRegionUrlMapRequest", "UpdateReservationRequest", 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 85a514d98ce0..5aa96998f8a4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -72,6 +72,7 @@ from .services.region_health_checks import RegionHealthChecksClient from .services.region_instance_group_managers import RegionInstanceGroupManagersClient from .services.region_instance_groups import RegionInstanceGroupsClient +from .services.region_instance_templates import RegionInstanceTemplatesClient from .services.region_instances import RegionInstancesClient from .services.region_network_endpoint_groups import RegionNetworkEndpointGroupsClient from .services.region_network_firewall_policies import ( @@ -155,6 +156,7 @@ AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, + AggregatedListInstanceTemplatesRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -314,6 +316,7 @@ DeleteRegionHealthCheckRequest, DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, + DeleteRegionInstanceTemplateRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -494,6 +497,7 @@ GetRegionHealthCheckServiceRequest, GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, + GetRegionInstanceTemplateRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -623,6 +627,7 @@ InsertRegionHealthCheckRequest, InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, + InsertRegionInstanceTemplateRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -710,10 +715,13 @@ InstancesSetMachineResourcesRequest, InstancesSetMachineTypeRequest, InstancesSetMinCpuPlatformRequest, + InstancesSetNameRequest, InstancesSetServiceAccountRequest, InstancesStartWithEncryptionKeyRequest, InstanceTemplate, + InstanceTemplateAggregatedList, InstanceTemplateList, + InstanceTemplatesScopedList, InstanceWithNamedPorts, Int64RangeMatch, Interconnect, @@ -808,6 +816,7 @@ ListRegionHealthChecksRequest, ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, + ListRegionInstanceTemplatesRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -1146,6 +1155,9 @@ SecurityPolicyRuleHttpHeaderActionHttpHeaderOption, SecurityPolicyRuleMatcher, SecurityPolicyRuleMatcherConfig, + SecurityPolicyRulePreconfiguredWafConfig, + SecurityPolicyRulePreconfiguredWafConfigExclusion, + SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams, SecurityPolicyRuleRateLimitOptions, SecurityPolicyRuleRateLimitOptionsThreshold, SecurityPolicyRuleRedirectOptions, @@ -1216,6 +1228,7 @@ SetMinCpuPlatformInstanceRequest, SetNamedPortsInstanceGroupRequest, SetNamedPortsRegionInstanceGroupRequest, + SetNameInstanceRequest, SetNodeTemplateNodeGroupRequest, SetPrivateIpGoogleAccessSubnetworkRequest, SetProxyHeaderTargetSslProxyRequest, @@ -1359,6 +1372,7 @@ UpdateAutoscalerRequest, UpdateBackendBucketRequest, UpdateBackendServiceRequest, + UpdateDiskRequest, UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateHealthCheckRequest, @@ -1370,6 +1384,7 @@ UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, + UpdateRegionDiskRequest, UpdateRegionHealthCheckRequest, UpdateRegionUrlMapRequest, UpdateReservationRequest, @@ -1473,6 +1488,7 @@ "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", + "AggregatedListInstanceTemplatesRequest", "AggregatedListInstancesRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", @@ -1636,6 +1652,7 @@ "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", + "DeleteRegionInstanceTemplateRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -1823,6 +1840,7 @@ "GetRegionHealthCheckServiceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", + "GetRegionInstanceTemplateRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -1960,6 +1978,7 @@ "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", + "InsertRegionInstanceTemplateRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -2041,8 +2060,10 @@ "InstanceProperties", "InstanceReference", "InstanceTemplate", + "InstanceTemplateAggregatedList", "InstanceTemplateList", "InstanceTemplatesClient", + "InstanceTemplatesScopedList", "InstanceWithNamedPorts", "InstancesAddResourcePoliciesRequest", "InstancesClient", @@ -2054,6 +2075,7 @@ "InstancesSetMachineResourcesRequest", "InstancesSetMachineTypeRequest", "InstancesSetMinCpuPlatformRequest", + "InstancesSetNameRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", "Int64RangeMatch", @@ -2154,6 +2176,7 @@ "ListRegionHealthChecksRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", + "ListRegionInstanceTemplatesRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2410,6 +2433,7 @@ "RegionInstanceGroupsListInstances", "RegionInstanceGroupsListInstancesRequest", "RegionInstanceGroupsSetNamedPortsRequest", + "RegionInstanceTemplatesClient", "RegionInstancesClient", "RegionList", "RegionNetworkEndpointGroupsClient", @@ -2534,6 +2558,9 @@ "SecurityPolicyRuleHttpHeaderActionHttpHeaderOption", "SecurityPolicyRuleMatcher", "SecurityPolicyRuleMatcherConfig", + "SecurityPolicyRulePreconfiguredWafConfig", + "SecurityPolicyRulePreconfiguredWafConfigExclusion", + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", "SecurityPolicyRuleRateLimitOptions", "SecurityPolicyRuleRateLimitOptionsThreshold", "SecurityPolicyRuleRedirectOptions", @@ -2603,6 +2630,7 @@ "SetMachineTypeInstanceRequest", "SetMetadataInstanceRequest", "SetMinCpuPlatformInstanceRequest", + "SetNameInstanceRequest", "SetNamedPortsInstanceGroupRequest", "SetNamedPortsRegionInstanceGroupRequest", "SetNodeTemplateNodeGroupRequest", @@ -2759,6 +2787,7 @@ "UpdateAutoscalerRequest", "UpdateBackendBucketRequest", "UpdateBackendServiceRequest", + "UpdateDiskRequest", "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateHealthCheckRequest", @@ -2770,6 +2799,7 @@ "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", + "UpdateRegionDiskRequest", "UpdateRegionHealthCheckRequest", "UpdateRegionUrlMapRequest", "UpdateReservationRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 87c73893dac2..b64a921f2859 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -338,6 +338,11 @@ "methods": [ "test_iam_permissions" ] + }, + "Update": { + "methods": [ + "update" + ] } } } @@ -1073,6 +1078,11 @@ "rest": { "libraryClient": "InstanceTemplatesClient", "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, "Delete": { "methods": [ "delete" @@ -1267,6 +1277,11 @@ "set_min_cpu_platform" ] }, + "SetName": { + "methods": [ + "set_name" + ] + }, "SetScheduling": { "methods": [ "set_scheduling" @@ -2422,6 +2437,11 @@ "methods": [ "test_iam_permissions" ] + }, + "Update": { + "methods": [ + "update" + ] } } } @@ -2633,6 +2653,35 @@ } } }, + "RegionInstanceTemplates": { + "clients": { + "rest": { + "libraryClient": "RegionInstanceTemplatesClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "RegionInstances": { "clients": { "rest": { diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py index a6b56a0e174d..d08973b62c95 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/autoscalers/client.py @@ -736,9 +736,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Autoscaler: - r"""Returns the specified autoscaler resource. Gets a - list of available autoscalers by making a list() - request. + r"""Returns the specified autoscaler resource. Args: request (Union[google.cloud.compute_v1.types.GetAutoscalerRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py index 97b23dbaf06b..3073cf8aeea3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_buckets/client.py @@ -1101,9 +1101,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendBucket: - r"""Returns the specified BackendBucket resource. Gets a - list of available backend buckets by making a list() - request. + r"""Returns the specified BackendBucket resource. Args: request (Union[google.cloud.compute_v1.types.GetBackendBucketRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py index 291efe8be9bd..7ef35b7b758c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py @@ -1193,8 +1193,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.BackendService: - r"""Returns the specified BackendService resource. Gets a - list of available backend services. + r"""Returns the specified BackendService resource. Args: request (Union[google.cloud.compute_v1.types.GetBackendServiceRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py index a3932837113c..215fd8b37cd5 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disk_types/client.py @@ -514,8 +514,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.DiskType: - r"""Returns the specified disk type. Gets a list of - available disk types by making a list() request. + r"""Returns the specified disk type. Args: request (Union[google.cloud.compute_v1.types.GetDiskTypeRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py index d9cc21cb2ada..ca99aff41be3 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/client.py @@ -1256,8 +1256,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Disk: - r"""Returns a specified persistent disk. Gets a list of - available persistent disks by making a list() request. + r"""Returns the specified persistent disk. Args: request (Union[google.cloud.compute_v1.types.GetDiskRequest, dict]): @@ -2839,6 +2838,249 @@ def test_iam_permissions( # Done; return the response. return response + def update_unary( + self, + request: Optional[Union[compute.UpdateDiskRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + disk: Optional[str] = None, + disk_resource: Optional[compute.Disk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Updates the specified disk with the data included in the + request. The update is performed only on selected fields + included as part of update-mask. Only the following fields can + be modified: user_license. + + Args: + request (Union[google.cloud.compute_v1.types.UpdateDiskRequest, dict]): + The request object. A request message for Disks.Update. + 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. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk (str): + The disk name for this request. + This corresponds to the ``disk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + This corresponds to the ``disk_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, disk, disk_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.UpdateDiskRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.UpdateDiskRequest): + request = compute.UpdateDiskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if disk is not None: + request.disk = disk + if disk_resource is not None: + request.disk_resource = disk_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # 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), + ("zone", request.zone), + ("disk", request.disk), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update( + self, + request: Optional[Union[compute.UpdateDiskRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + disk: Optional[str] = None, + disk_resource: Optional[compute.Disk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Updates the specified disk with the data included in the + request. The update is performed only on selected fields + included as part of update-mask. Only the following fields can + be modified: user_license. + + Args: + request (Union[google.cloud.compute_v1.types.UpdateDiskRequest, dict]): + The request object. A request message for Disks.Update. + 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. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk (str): + The disk name for this request. + This corresponds to the ``disk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + This corresponds to the ``disk_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, disk, disk_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.UpdateDiskRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.UpdateDiskRequest): + request = compute.UpdateDiskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if disk is not None: + request.disk = disk + if disk_resource is not None: + request.disk_resource = disk_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # 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), + ("zone", request.zone), + ("disk", request.disk), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def __enter__(self) -> "DisksClient": return self diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py index 00be0507c06d..e26c3ee734d6 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/base.py @@ -192,6 +192,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update: gapic_v1.method.wrap_method( + self.update, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -320,6 +325,15 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def update( + self, + ) -> Callable[ + [compute.UpdateDiskRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py index ddd1154ee97d..5def36397b9e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/disks/transports/rest.py @@ -167,6 +167,14 @@ def post_test_iam_permissions(self, response): logging.log(f"Received response: {response}") return response + def pre_update(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update(self, response): + logging.log(f"Received response: {response}") + return response + transport = DisksRestTransport(interceptor=MyCustomDisksInterceptor()) client = DisksClient(transport=transport) @@ -442,6 +450,25 @@ def post_test_iam_permissions( """ return response + def pre_update( + self, request: compute.UpdateDiskRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[compute.UpdateDiskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update + + Override in a subclass to manipulate the request or metadata + before they are sent to the Disks server. + """ + return request, metadata + + def post_update(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for update + + Override in a subclass to manipulate the response + after it is returned by the Disks server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class DisksRestStub: @@ -1949,6 +1976,116 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp + class _Update(DisksRestStub): + def __hash__(self): + return hash("Update") + + __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 + } + + def __call__( + self, + request: compute.UpdateDiskRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the update method over HTTP. + + Args: + request (~.compute.UpdateDiskRequest): + The request object. A request message for Disks.Update. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zonalOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/compute/v1/projects/{project}/zones/{zone}/disks/{disk}", + "body": "disk_resource", + }, + ] + request, metadata = self._interceptor.pre_update(request, metadata) + pb_request = compute.UpdateDiskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update(resp) + return resp + @property def add_resource_policies( self, @@ -2043,6 +2180,12 @@ def test_iam_permissions( # In C++ this would require a dynamic_cast return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + @property + def update(self) -> Callable[[compute.UpdateDiskRequest], compute.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._Update(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py index a7ff07505f41..9d7a278cc2b1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/firewall_policies/client.py @@ -1877,8 +1877,10 @@ def move_unary( on the ``request`` instance; if ``request`` is provided, this should not be set. parent_id (str): - The new parent of the firewall - policy. + The new parent of the firewall policy. The ID can be + either be "folders/[FOLDER_ID]" if the parent is a + folder or "organizations/[ORGANIZATION_ID]" if the + parent is an organization. This corresponds to the ``parent_id`` field on the ``request`` instance; if ``request`` is provided, this @@ -1966,8 +1968,10 @@ def move( on the ``request`` instance; if ``request`` is provided, this should not be set. parent_id (str): - The new parent of the firewall - policy. + The new parent of the firewall policy. The ID can be + either be "folders/[FOLDER_ID]" if the parent is a + folder or "organizations/[ORGANIZATION_ID]" if the + parent is an organization. This corresponds to the ``parent_id`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py index b46193df9f95..84d5715ae7b4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_addresses/client.py @@ -637,8 +637,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Address: - r"""Returns the specified address resource. Gets a list - of available addresses by making a list() request. + r"""Returns the specified address resource. Args: request (Union[google.cloud.compute_v1.types.GetGlobalAddressRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py index a30e43a52a0e..2a39593d164b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/global_network_endpoint_groups/client.py @@ -1179,9 +1179,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.NetworkEndpointGroup: - r"""Returns the specified network endpoint group. Gets a - list of available network endpoint groups by making a - list() request. + r"""Returns the specified network endpoint group. Args: request (Union[google.cloud.compute_v1.types.GetGlobalNetworkEndpointGroupRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py index 7b8e817c05b2..2212e69d6066 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/health_checks/client.py @@ -725,9 +725,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.HealthCheck: - r"""Returns the specified HealthCheck resource. Gets a - list of available health checks by making a list() - request. + r"""Returns the specified HealthCheck resource. Args: request (Union[google.cloud.compute_v1.types.GetHealthCheckRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py index 162a16ca9a1f..0765ec04a65c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/images/client.py @@ -849,8 +849,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Image: - r"""Returns the specified image. Gets a list of available - images by making a list() request. + r"""Returns the specified image. Args: request (Union[google.cloud.compute_v1.types.GetImageRequest, dict]): @@ -940,7 +939,8 @@ def get_from_family( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Image: r"""Returns the latest image that is part of an image - family and is not deprecated. + family and is not deprecated. For more information on + image families, see Public image families documentation. Args: request (Union[google.cloud.compute_v1.types.GetFromFamilyImageRequest, dict]): @@ -948,7 +948,11 @@ def get_from_family( Images.GetFromFamily. See the method description for details. project (str): - Project ID for this request. + The image project that the image + belongs to. For example, to get a CentOS + image, specify centos-cloud as the image + project. + This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py index d2cb307df1c1..b4e8da98f85a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_group_managers/client.py @@ -2221,8 +2221,7 @@ def get( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.InstanceGroupManager: r"""Returns all of the details about the specified - managed instance group. Gets a list of available managed - instance groups by making a list() request. + managed instance group. Args: request (Union[google.cloud.compute_v1.types.GetInstanceGroupManagerRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py index 107d4e280e31..d1292111e004 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/client.py @@ -423,6 +423,99 @@ def __init__( api_audience=client_options.api_audience, ) + def aggregated_list( + self, + request: Optional[ + Union[compute.AggregatedListInstanceTemplatesRequest, dict] + ] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AggregatedListPager: + r"""Retrieves the list of all InstanceTemplates + resources, regional and global, available to the + specified project. + + Args: + request (Union[google.cloud.compute_v1.types.AggregatedListInstanceTemplatesRequest, dict]): + The request object. A request message for + InstanceTemplates.AggregatedList. See the method + description for details. + project (str): + Name of the project scoping 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.instance_templates.pagers.AggregatedListPager: + Contains a list of + InstanceTemplatesScopedList. + 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. + has_flattened_params = any([project]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.AggregatedListInstanceTemplatesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.AggregatedListInstanceTemplatesRequest): + request = compute.AggregatedListInstanceTemplatesRequest(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.aggregated_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),)), + ) + + # 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.AggregatedListPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + def delete_unary( self, request: Optional[Union[compute.DeleteInstanceTemplateRequest, dict]] = None, @@ -643,9 +736,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.InstanceTemplate: - r"""Returns the specified instance template. Gets a list - of available instance templates by making a list() - request. + r"""Returns the specified instance template. Args: request (Union[google.cloud.compute_v1.types.GetInstanceTemplateRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/pagers.py index 45418f480dd4..10107b3ab51a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/pagers.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/pagers.py @@ -27,6 +27,71 @@ from google.cloud.compute_v1.types import compute +class AggregatedListPager: + """A pager for iterating through ``aggregated_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.InstanceTemplateAggregatedList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AggregatedList`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.InstanceTemplateAggregatedList` + 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.InstanceTemplateAggregatedList], + request: compute.AggregatedListInstanceTemplatesRequest, + response: compute.InstanceTemplateAggregatedList, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.AggregatedListInstanceTemplatesRequest): + The initial request object. + response (google.cloud.compute_v1.types.InstanceTemplateAggregatedList): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = compute.AggregatedListInstanceTemplatesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.InstanceTemplateAggregatedList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[Tuple[str, compute.InstanceTemplatesScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.InstanceTemplatesScopedList]: + return self._response.items.get(key) + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListPager: """A pager for iterating through ``list`` requests. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py index 58654a5f83ad..af5723970123 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/base.py @@ -127,6 +127,11 @@ def __init__( def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.aggregated_list: gapic_v1.method.wrap_method( + self.aggregated_list, + default_timeout=None, + client_info=client_info, + ), self.delete: gapic_v1.method.wrap_method( self.delete, default_timeout=None, @@ -173,6 +178,18 @@ def close(self): """ raise NotImplementedError() + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListInstanceTemplatesRequest], + Union[ + compute.InstanceTemplateAggregatedList, + Awaitable[compute.InstanceTemplateAggregatedList], + ], + ]: + raise NotImplementedError() + @property def delete( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py index 6f10d0846c4b..58fde9c2ece1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instance_templates/transports/rest.py @@ -63,6 +63,14 @@ class InstanceTemplatesRestInterceptor: .. code-block:: python class MyCustomInstanceTemplatesInterceptor(InstanceTemplatesRestInterceptor): + def pre_aggregated_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_aggregated_list(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -125,6 +133,31 @@ def post_test_iam_permissions(self, response): """ + def pre_aggregated_list( + self, + request: compute.AggregatedListInstanceTemplatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.AggregatedListInstanceTemplatesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for aggregated_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstanceTemplates server. + """ + return request, metadata + + def post_aggregated_list( + self, response: compute.InstanceTemplateAggregatedList + ) -> compute.InstanceTemplateAggregatedList: + """Post-rpc interceptor for aggregated_list + + Override in a subclass to manipulate the response + after it is returned by the InstanceTemplates server but before + it is returned to user code. + """ + return response + def pre_delete( self, request: compute.DeleteInstanceTemplateRequest, @@ -382,6 +415,95 @@ def __init__( self._interceptor = interceptor or InstanceTemplatesRestInterceptor() self._prep_wrapped_messages(client_info) + class _AggregatedList(InstanceTemplatesRestStub): + def __hash__(self): + return hash("AggregatedList") + + __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 + } + + def __call__( + self, + request: compute.AggregatedListInstanceTemplatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstanceTemplateAggregatedList: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListInstanceTemplatesRequest): + The request object. A request message for + InstanceTemplates.AggregatedList. 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstanceTemplateAggregatedList: + Contains a list of + InstanceTemplatesScopedList. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/aggregated/instanceTemplates", + }, + ] + request, metadata = self._interceptor.pre_aggregated_list(request, metadata) + pb_request = compute.AggregatedListInstanceTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.InstanceTemplateAggregatedList() + pb_resp = compute.InstanceTemplateAggregatedList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_aggregated_list(resp) + return resp + class _Delete(InstanceTemplatesRestStub): def __hash__(self): return hash("Delete") @@ -1137,6 +1259,17 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListInstanceTemplatesRequest], + compute.InstanceTemplateAggregatedList, + ]: + # 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._AggregatedList(self._session, self._host, self._interceptor) # type: ignore + @property def delete( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py index a6cfa7a09c28..80f7222d2dee 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py @@ -2274,8 +2274,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Instance: - r"""Returns the specified Instance resource. Gets a list - of available instances by making a list() request. + r"""Returns the specified Instance resource. Args: request (Union[google.cloud.compute_v1.types.GetInstanceRequest, dict]): @@ -6230,6 +6229,257 @@ def error_code(self): # Done; return the response. return response + def set_name_unary( + self, + request: Optional[Union[compute.SetNameInstanceRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instance: Optional[str] = None, + instances_set_name_request_resource: Optional[ + compute.InstancesSetNameRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets name of an instance. + + Args: + request (Union[google.cloud.compute_v1.types.SetNameInstanceRequest, dict]): + The request object. A request message for + Instances.SetName. 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. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (str): + The instance name for this request. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instances_set_name_request_resource (google.cloud.compute_v1.types.InstancesSetNameRequest): + The body resource for this request + This corresponds to the ``instances_set_name_request_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, instance, instances_set_name_request_resource] + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetNameInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetNameInstanceRequest): + request = compute.SetNameInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instance is not None: + request.instance = instance + if instances_set_name_request_resource is not None: + request.instances_set_name_request_resource = ( + instances_set_name_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_name] + + # 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), + ("zone", request.zone), + ("instance", request.instance), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_name( + self, + request: Optional[Union[compute.SetNameInstanceRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instance: Optional[str] = None, + instances_set_name_request_resource: Optional[ + compute.InstancesSetNameRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Sets name of an instance. + + Args: + request (Union[google.cloud.compute_v1.types.SetNameInstanceRequest, dict]): + The request object. A request message for + Instances.SetName. 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. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (str): + The instance name for this request. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instances_set_name_request_resource (google.cloud.compute_v1.types.InstancesSetNameRequest): + The body resource for this request + This corresponds to the ``instances_set_name_request_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, instance, instances_set_name_request_resource] + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetNameInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetNameInstanceRequest): + request = compute.SetNameInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instance is not None: + request.instance = instance + if instances_set_name_request_resource is not None: + request.instances_set_name_request_resource = ( + instances_set_name_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_name] + + # 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), + ("zone", request.zone), + ("instance", request.instance), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def set_scheduling_unary( self, request: Optional[Union[compute.SetSchedulingInstanceRequest, dict]] = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py index e8ef8e39d76f..6ef3034c706c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py @@ -277,6 +277,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_name: gapic_v1.method.wrap_method( + self.set_name, + default_timeout=None, + client_info=client_info, + ), self.set_scheduling: gapic_v1.method.wrap_method( self.set_scheduling, default_timeout=None, @@ -644,6 +649,15 @@ def set_min_cpu_platform( ]: raise NotImplementedError() + @property + def set_name( + self, + ) -> Callable[ + [compute.SetNameInstanceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def set_scheduling( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py index 76e2de98b433..d79e19e7b4ec 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py @@ -303,6 +303,14 @@ def post_set_min_cpu_platform(self, response): logging.log(f"Received response: {response}") return response + def pre_set_name(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_name(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_scheduling(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1087,6 +1095,27 @@ def post_set_min_cpu_platform( """ return response + def pre_set_name( + self, + request: compute.SetNameInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.SetNameInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_name + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_set_name(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for set_name + + Override in a subclass to manipulate the response + after it is returned by the Instances server but before + it is returned to user code. + """ + return response + def pre_set_scheduling( self, request: compute.SetSchedulingInstanceRequest, @@ -4650,6 +4679,117 @@ def __call__( resp = self._interceptor.post_set_min_cpu_platform(resp) return resp + class _SetName(InstancesRestStub): + def __hash__(self): + return hash("SetName") + + __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 + } + + def __call__( + self, + request: compute.SetNameInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set name method over HTTP. + + Args: + request (~.compute.SetNameInstanceRequest): + The request object. A request message for + Instances.SetName. 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zonalOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/setName", + "body": "instances_set_name_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_name(request, metadata) + pb_request = compute.SetNameInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_name(resp) + return resp + class _SetScheduling(InstancesRestStub): def __hash__(self): return hash("SetScheduling") @@ -6536,6 +6676,12 @@ def set_min_cpu_platform( # In C++ this would require a dynamic_cast return self._SetMinCpuPlatform(self._session, self._host, self._interceptor) # type: ignore + @property + def set_name(self) -> Callable[[compute.SetNameInstanceRequest], compute.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._SetName(self._session, self._host, self._interceptor) # type: ignore + @property def set_scheduling( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py index 28e1bbbc00b2..174ef67587ec 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_images/client.py @@ -637,8 +637,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.MachineImage: - r"""Returns the specified machine image. Gets a list of - available machine images by making a list() request. + r"""Returns the specified machine image. Args: request (Union[google.cloud.compute_v1.types.GetMachineImageRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py index fc254e1799fd..2ef035a3ba3d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/machine_types/client.py @@ -516,8 +516,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.MachineType: - r"""Returns the specified machine type. Gets a list of - available machine types by making a list() request. + r"""Returns the specified machine type. Args: request (Union[google.cloud.compute_v1.types.GetMachineTypeRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py index 294bff2929ea..97edaae76352 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/network_endpoint_groups/client.py @@ -1327,9 +1327,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.NetworkEndpointGroup: - r"""Returns the specified network endpoint group. Gets a - list of available network endpoint groups by making a - list() request. + r"""Returns the specified network endpoint group. Args: request (Union[google.cloud.compute_v1.types.GetNetworkEndpointGroupRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py index f00b139e53a8..7ec31b17f070 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/networks/client.py @@ -861,8 +861,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Network: - r"""Returns the specified network. Gets a list of - available networks by making a list() request. + r"""Returns the specified network. Args: request (Union[google.cloud.compute_v1.types.GetNetworkRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py index 9ac3ff450658..4d5e9d51e01f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_templates/client.py @@ -746,8 +746,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.NodeTemplate: - r"""Returns the specified node template. Gets a list of - available node templates by making a list() request. + r"""Returns the specified node template. Args: request (Union[google.cloud.compute_v1.types.GetNodeTemplateRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py index 2d524b1fd47d..895662b4e6cc 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/node_types/client.py @@ -514,8 +514,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.NodeType: - r"""Returns the specified node type. Gets a list of - available node types by making a list() request. + r"""Returns the specified node type. Args: request (Union[google.cloud.compute_v1.types.GetNodeTypeRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py index d6d10e2599dc..e1e9b6ae604a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_commitments/client.py @@ -522,9 +522,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Commitment: - r"""Returns the specified commitment resource. Gets a - list of available commitments by making a list() - request. + r"""Returns the specified commitment resource. Args: request (Union[google.cloud.compute_v1.types.GetRegionCommitmentRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py index 7fbe53eca604..8b8b689f2bdc 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disk_types/client.py @@ -431,8 +431,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.DiskType: - r"""Returns the specified regional disk type. Gets a list - of available disk types by making a list() request. + r"""Returns the specified regional disk type. Args: request (Union[google.cloud.compute_v1.types.GetRegionDiskTypeRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py index bf098b94210e..021cde85bf34 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/client.py @@ -2758,6 +2758,251 @@ def test_iam_permissions( # Done; return the response. return response + def update_unary( + self, + request: Optional[Union[compute.UpdateRegionDiskRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + disk: Optional[str] = None, + disk_resource: Optional[compute.Disk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Update the specified disk with the data included in the request. + Update is performed only on selected fields included as part of + update-mask. Only the following fields can be modified: + user_license. + + Args: + request (Union[google.cloud.compute_v1.types.UpdateRegionDiskRequest, dict]): + The request object. A request message for + RegionDisks.Update. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk (str): + The disk name for this request. + This corresponds to the ``disk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + This corresponds to the ``disk_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, disk, disk_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.UpdateRegionDiskRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.UpdateRegionDiskRequest): + request = compute.UpdateRegionDiskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if disk is not None: + request.disk = disk + if disk_resource is not None: + request.disk_resource = disk_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # 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), + ("region", request.region), + ("disk", request.disk), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update( + self, + request: Optional[Union[compute.UpdateRegionDiskRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + disk: Optional[str] = None, + disk_resource: Optional[compute.Disk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Update the specified disk with the data included in the request. + Update is performed only on selected fields included as part of + update-mask. Only the following fields can be modified: + user_license. + + Args: + request (Union[google.cloud.compute_v1.types.UpdateRegionDiskRequest, dict]): + The request object. A request message for + RegionDisks.Update. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk (str): + The disk name for this request. + This corresponds to the ``disk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + This corresponds to the ``disk_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, disk, disk_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.UpdateRegionDiskRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.UpdateRegionDiskRequest): + request = compute.UpdateRegionDiskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if disk is not None: + request.disk = disk + if disk_resource is not None: + request.disk_resource = disk_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update] + + # 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), + ("region", request.region), + ("disk", request.disk), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def __enter__(self) -> "RegionDisksClient": return self diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py index ab3484606abe..65bd5730d448 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/base.py @@ -187,6 +187,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.update: gapic_v1.method.wrap_method( + self.update, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -307,6 +312,15 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def update( + self, + ) -> Callable[ + [compute.UpdateRegionDiskRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py index 0eae50994e33..9cb1f614ac1b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_disks/transports/rest.py @@ -159,6 +159,14 @@ def post_test_iam_permissions(self, response): logging.log(f"Received response: {response}") return response + def pre_update(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update(self, response): + logging.log(f"Received response: {response}") + return response + transport = RegionDisksRestTransport(interceptor=MyCustomRegionDisksInterceptor()) client = RegionDisksClient(transport=transport) @@ -423,6 +431,27 @@ def post_test_iam_permissions( """ return response + def pre_update( + self, + request: compute.UpdateRegionDiskRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.UpdateRegionDiskRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionDisks server. + """ + return request, metadata + + def post_update(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for update + + Override in a subclass to manipulate the response + after it is returned by the RegionDisks server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class RegionDisksRestStub: @@ -1848,6 +1877,117 @@ def __call__( resp = self._interceptor.post_test_iam_permissions(resp) return resp + class _Update(RegionDisksRestStub): + def __hash__(self): + return hash("Update") + + __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 + } + + def __call__( + self, + request: compute.UpdateRegionDiskRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the update method over HTTP. + + Args: + request (~.compute.UpdateRegionDiskRequest): + The request object. A request message for + RegionDisks.Update. 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zonalOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/compute/v1/projects/{project}/regions/{region}/disks/{disk}", + "body": "disk_resource", + }, + ] + request, metadata = self._interceptor.pre_update(request, metadata) + pb_request = compute.UpdateRegionDiskRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update(resp) + return resp + @property def add_resource_policies( self, @@ -1936,6 +2076,12 @@ def test_iam_permissions( # In C++ this would require a dynamic_cast return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + @property + def update(self) -> Callable[[compute.UpdateRegionDiskRequest], compute.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._Update(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py index 3619bc228fe5..2bca079071fa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_health_checks/client.py @@ -661,9 +661,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.HealthCheck: - r"""Returns the specified HealthCheck resource. Gets a - list of available health checks by making a list() - request. + r"""Returns the specified HealthCheck resource. Args: request (Union[google.cloud.compute_v1.types.GetRegionHealthCheckRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/__init__.py new file mode 100644 index 000000000000..31937b910daa --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegionInstanceTemplatesClient + +__all__ = ("RegionInstanceTemplatesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py new file mode 100644 index 000000000000..96c328fa26be --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/client.py @@ -0,0 +1,1113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +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 extended_operation, 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_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1.services.region_instance_templates import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RegionInstanceTemplatesTransport +from .transports.rest import RegionInstanceTemplatesRestTransport + + +class RegionInstanceTemplatesClientMeta(type): + """Metaclass for the RegionInstanceTemplates 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[RegionInstanceTemplatesTransport]] + _transport_registry["rest"] = RegionInstanceTemplatesRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionInstanceTemplatesTransport]: + """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 RegionInstanceTemplatesClient(metaclass=RegionInstanceTemplatesClientMeta): + """The RegionInstanceTemplates API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + RegionInstanceTemplatesClient: 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: + RegionInstanceTemplatesClient: 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) -> RegionInstanceTemplatesTransport: + """Returns the transport used by the client instance. + + Returns: + RegionInstanceTemplatesTransport: 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 + ): + """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. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + 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 == "true": + 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 + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionInstanceTemplatesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region instance templates 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 (Union[str, RegionInstanceTemplatesTransport]): The + transport to use. 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. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(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. + if isinstance(transport, RegionInstanceTemplatesTransport): + # transport is a RegionInstanceTemplatesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + 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 = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def delete_unary( + self, + request: Optional[ + Union[compute.DeleteRegionInstanceTemplateRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instance_template: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified instance template. Deleting an + instance template is permanent and cannot be undone. + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRegionInstanceTemplateRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.Delete. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_template (str): + The name of the instance template to + delete. + + This corresponds to the ``instance_template`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instance_template]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteRegionInstanceTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteRegionInstanceTemplateRequest): + request = compute.DeleteRegionInstanceTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instance_template is not None: + request.instance_template = instance_template + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # 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), + ("region", request.region), + ("instance_template", request.instance_template), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[ + Union[compute.DeleteRegionInstanceTemplateRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instance_template: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes the specified instance template. Deleting an + instance template is permanent and cannot be undone. + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRegionInstanceTemplateRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.Delete. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_template (str): + The name of the instance template to + delete. + + This corresponds to the ``instance_template`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instance_template]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteRegionInstanceTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteRegionInstanceTemplateRequest): + request = compute.DeleteRegionInstanceTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instance_template is not None: + request.instance_template = instance_template + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # 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), + ("region", request.region), + ("instance_template", request.instance_template), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetRegionInstanceTemplateRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instance_template: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstanceTemplate: + r"""Returns the specified instance template. + + Args: + request (Union[google.cloud.compute_v1.types.GetRegionInstanceTemplateRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_template (str): + The name of the instance template. + This corresponds to the ``instance_template`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.InstanceTemplate: + Represents an Instance Template + resource. You can use instance templates + to create VM instances and managed + instance groups. For more information, + read Instance Templates. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instance_template]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetRegionInstanceTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetRegionInstanceTemplateRequest): + request = compute.GetRegionInstanceTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instance_template is not None: + request.instance_template = instance_template + + # 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), + ("region", request.region), + ("instance_template", request.instance_template), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_unary( + self, + request: Optional[ + Union[compute.InsertRegionInstanceTemplateRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instance_template_resource: Optional[compute.InstanceTemplate] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates an instance template in the specified project + and region using the global instance template whose URL + is included in the request. + + Args: + request (Union[google.cloud.compute_v1.types.InsertRegionInstanceTemplateRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.Insert. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_template_resource (google.cloud.compute_v1.types.InstanceTemplate): + The body resource for this request + This corresponds to the ``instance_template_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instance_template_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertRegionInstanceTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertRegionInstanceTemplateRequest): + request = compute.InsertRegionInstanceTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instance_template_resource is not None: + request.instance_template_resource = instance_template_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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), + ("region", request.region), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert( + self, + request: Optional[ + Union[compute.InsertRegionInstanceTemplateRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instance_template_resource: Optional[compute.InstanceTemplate] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates an instance template in the specified project + and region using the global instance template whose URL + is included in the request. + + Args: + request (Union[google.cloud.compute_v1.types.InsertRegionInstanceTemplateRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.Insert. 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. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_template_resource (google.cloud.compute_v1.types.InstanceTemplate): + The body resource for this request + This corresponds to the ``instance_template_resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instance_template_resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertRegionInstanceTemplateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertRegionInstanceTemplateRequest): + request = compute.InsertRegionInstanceTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instance_template_resource is not None: + request.instance_template_resource = instance_template_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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), + ("region", request.region), + ) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[ + Union[compute.ListRegionInstanceTemplatesRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Retrieves a list of instance templates that are + contained within the specified project and region. + + Args: + request (Union[google.cloud.compute_v1.types.ListRegionInstanceTemplatesRequest, dict]): + The request object. A request message for + RegionInstanceTemplates.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. + region (str): + The name of the regions for this + request. + + This corresponds to the ``region`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.region_instance_templates.pagers.ListPager: + A list of instance templates. + 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. + has_flattened_params = any([project, region]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.ListRegionInstanceTemplatesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListRegionInstanceTemplatesRequest): + request = compute.ListRegionInstanceTemplatesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # 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), + ("region", request.region), + ) + ), + ) + + # 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, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RegionInstanceTemplatesClient": + 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__ +) + + +__all__ = ("RegionInstanceTemplatesClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/pagers.py new file mode 100644 index 000000000000..73180e26e812 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/pagers.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, +) + +from google.cloud.compute_v1.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.InstanceTemplateList` 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_v1.types.InstanceTemplateList` + 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.InstanceTemplateList], + request: compute.ListRegionInstanceTemplatesRequest, + response: compute.InstanceTemplateList, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1.types.ListRegionInstanceTemplatesRequest): + The initial request object. + response (google.cloud.compute_v1.types.InstanceTemplateList): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = compute.ListRegionInstanceTemplatesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.InstanceTemplateList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[compute.InstanceTemplate]: + 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/google/cloud/compute_v1/services/region_instance_templates/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/__init__.py new file mode 100644 index 000000000000..819f6b7514a1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 RegionInstanceTemplatesTransport +from .rest import ( + RegionInstanceTemplatesRestInterceptor, + RegionInstanceTemplatesRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionInstanceTemplatesTransport]] +_transport_registry["rest"] = RegionInstanceTemplatesRestTransport + +__all__ = ( + "RegionInstanceTemplatesTransport", + "RegionInstanceTemplatesRestTransport", + "RegionInstanceTemplatesRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/base.py new file mode 100644 index 000000000000..5690a9aa3288 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/base.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import region_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class RegionInstanceTemplatesTransport(abc.ABC): + """Abstract transport class for RegionInstanceTemplates.""" + + AUTH_SCOPES = ( + "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. + 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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + 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 delete( + self, + ) -> Callable[ + [compute.DeleteRegionInstanceTemplateRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRegionInstanceTemplateRequest], + Union[compute.InstanceTemplate, Awaitable[compute.InstanceTemplate]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertRegionInstanceTemplateRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionInstanceTemplatesRequest], + Union[compute.InstanceTemplateList, Awaitable[compute.InstanceTemplateList]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _region_operations_client(self) -> region_operations.RegionOperationsClient: + ex_op_service = self._extended_operations_services.get("region_operations") + if not ex_op_service: + ex_op_service = region_operations.RegionOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["region_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RegionInstanceTemplatesTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/rest.py new file mode 100644 index 000000000000..affefefcb2c4 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instance_templates/transports/rest.py @@ -0,0 +1,728 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import RegionInstanceTemplatesTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RegionInstanceTemplatesRestInterceptor: + """Interceptor for RegionInstanceTemplates. + + 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 RegionInstanceTemplatesRestTransport. + + .. code-block:: python + class MyCustomRegionInstanceTemplatesInterceptor(RegionInstanceTemplatesRestInterceptor): + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + 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_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(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 = RegionInstanceTemplatesRestTransport(interceptor=MyCustomRegionInstanceTemplatesInterceptor()) + client = RegionInstanceTemplatesClient(transport=transport) + + + """ + + def pre_delete( + self, + request: compute.DeleteRegionInstanceTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.DeleteRegionInstanceTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstanceTemplates server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + Override in a subclass to manipulate the response + after it is returned by the RegionInstanceTemplates server but before + it is returned to user code. + """ + return response + + def pre_get( + self, + request: compute.GetRegionInstanceTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.GetRegionInstanceTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstanceTemplates server. + """ + return request, metadata + + def post_get(self, response: compute.InstanceTemplate) -> compute.InstanceTemplate: + """Post-rpc interceptor for get + + Override in a subclass to manipulate the response + after it is returned by the RegionInstanceTemplates server but before + it is returned to user code. + """ + return response + + def pre_insert( + self, + request: compute.InsertRegionInstanceTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.InsertRegionInstanceTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstanceTemplates server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + Override in a subclass to manipulate the response + after it is returned by the RegionInstanceTemplates server but before + it is returned to user code. + """ + return response + + def pre_list( + self, + request: compute.ListRegionInstanceTemplatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.ListRegionInstanceTemplatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstanceTemplates server. + """ + return request, metadata + + def post_list( + self, response: compute.InstanceTemplateList + ) -> compute.InstanceTemplateList: + """Post-rpc interceptor for list + + Override in a subclass to manipulate the response + after it is returned by the RegionInstanceTemplates server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RegionInstanceTemplatesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionInstanceTemplatesRestInterceptor + + +class RegionInstanceTemplatesRestTransport(RegionInstanceTemplatesTransport): + """REST backend transport for RegionInstanceTemplates. + + The RegionInstanceTemplates 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 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + 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[RegionInstanceTemplatesRestInterceptor] = 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. + 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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + 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, + ) + 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 RegionInstanceTemplatesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Delete(RegionInstanceTemplatesRestStub): + def __hash__(self): + return hash("Delete") + + __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 + } + + def __call__( + self, + request: compute.DeleteRegionInstanceTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteRegionInstanceTemplateRequest): + The request object. A request message for + RegionInstanceTemplates.Delete. 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zonalOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/compute/v1/projects/{project}/regions/{region}/instanceTemplates/{instance_template}", + }, + ] + request, metadata = self._interceptor.pre_delete(request, metadata) + pb_request = compute.DeleteRegionInstanceTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete(resp) + return resp + + class _Get(RegionInstanceTemplatesRestStub): + def __hash__(self): + return hash("Get") + + __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 + } + + def __call__( + self, + request: compute.GetRegionInstanceTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstanceTemplate: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRegionInstanceTemplateRequest): + The request object. A request message for + RegionInstanceTemplates.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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstanceTemplate: + Represents an Instance Template + resource. You can use instance templates + to create VM instances and managed + instance groups. For more information, + read Instance Templates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/instanceTemplates/{instance_template}", + }, + ] + request, metadata = self._interceptor.pre_get(request, metadata) + pb_request = compute.GetRegionInstanceTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.InstanceTemplate() + pb_resp = compute.InstanceTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get(resp) + return resp + + class _Insert(RegionInstanceTemplatesRestStub): + def __hash__(self): + return hash("Insert") + + __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 + } + + def __call__( + self, + request: compute.InsertRegionInstanceTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertRegionInstanceTemplateRequest): + The request object. A request message for + RegionInstanceTemplates.Insert. 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zonalOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/instanceTemplates", + "body": "instance_template_resource", + }, + ] + request, metadata = self._interceptor.pre_insert(request, metadata) + pb_request = compute.InsertRegionInstanceTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert(resp) + return resp + + class _List(RegionInstanceTemplatesRestStub): + def __hash__(self): + return hash("List") + + __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 + } + + def __call__( + self, + request: compute.ListRegionInstanceTemplatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstanceTemplateList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRegionInstanceTemplatesRequest): + The request object. A request message for + RegionInstanceTemplates.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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstanceTemplateList: + A list of instance templates. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/instanceTemplates", + }, + ] + request, metadata = self._interceptor.pre_list(request, metadata) + pb_request = compute.ListRegionInstanceTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.InstanceTemplateList() + pb_resp = compute.InstanceTemplateList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list(resp) + return resp + + @property + def delete( + self, + ) -> Callable[[compute.DeleteRegionInstanceTemplateRequest], compute.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._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get( + self, + ) -> Callable[[compute.GetRegionInstanceTemplateRequest], compute.InstanceTemplate]: + # 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 insert( + self, + ) -> Callable[[compute.InsertRegionInstanceTemplateRequest], compute.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._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionInstanceTemplatesRequest], compute.InstanceTemplateList + ]: + # 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__ = ("RegionInstanceTemplatesRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py index 3270c072e49c..32c149146039 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_network_endpoint_groups/client.py @@ -677,9 +677,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.NetworkEndpointGroup: - r"""Returns the specified network endpoint group. Gets a - list of available network endpoint groups by making a - list() request. + r"""Returns the specified network endpoint group. Args: request (Union[google.cloud.compute_v1.types.GetRegionNetworkEndpointGroupRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py index 0ba5bd283a5d..911f83d7f5a8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_http_proxies/client.py @@ -666,8 +666,7 @@ def get( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetHttpProxy: r"""Returns the specified TargetHttpProxy resource in the - specified region. Gets a list of available target HTTP - proxies by making a list() request. + specified region. Args: request (Union[google.cloud.compute_v1.types.GetRegionTargetHttpProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py index b6fecbbbe8a2..b09e46ce5d46 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_target_https_proxies/client.py @@ -666,8 +666,7 @@ def get( metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetHttpsProxy: r"""Returns the specified TargetHttpsProxy resource in - the specified region. Gets a list of available target - HTTP proxies by making a list() request. + the specified region. Args: request (Union[google.cloud.compute_v1.types.GetRegionTargetHttpsProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py index 64a9cd3b9972..494a16845307 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_url_maps/client.py @@ -659,8 +659,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.UrlMap: - r"""Returns the specified UrlMap resource. Gets a list of - available URL maps by making a list() request. + r"""Returns the specified UrlMap resource. Args: request (Union[google.cloud.compute_v1.types.GetRegionUrlMapRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py index 624c287b7ce2..4a135a8e6cc1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/regions/client.py @@ -428,15 +428,15 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Region: - r"""Returns the specified Region resource. Gets a list of available - regions by making a list() request. To decrease latency for this - method, you can optionally omit any unneeded information from - the response by using a field mask. This practice is especially - recommended for unused quota information (the ``quotas`` field). - To exclude one or more fields, set your request's ``fields`` - query parameter to only include the fields you need. For - example, to only include the ``id`` and ``selfLink`` fields, add - the query parameter ``?fields=id,selfLink`` to your request. + r"""Returns the specified Region resource. To decrease latency for + this method, you can optionally omit any unneeded information + from the response by using a field mask. This practice is + especially recommended for unused quota information (the + ``quotas`` field). To exclude one or more fields, set your + request's ``fields`` query parameter to only include the fields + you need. For example, to only include the ``id`` and + ``selfLink`` fields, add the query parameter + ``?fields=id,selfLink`` to your request. Args: request (Union[google.cloud.compute_v1.types.GetRegionRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py index fefbf7f8c7fe..eb084d1aa221 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py @@ -739,8 +739,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Router: - r"""Returns the specified Router resource. Gets a list of - available routers by making a list() request. + r"""Returns the specified Router resource. Args: request (Union[google.cloud.compute_v1.types.GetRouterRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py index 0749acecd71d..0d506aeba7aa 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routes/client.py @@ -629,8 +629,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Route: - r"""Returns the specified Route resource. Gets a list of - available routes by making a list() request. + r"""Returns the specified Route resource. Args: request (Union[google.cloud.compute_v1.types.GetRouteRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py index e2833124f538..05571a12fb2d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/snapshots/client.py @@ -647,8 +647,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Snapshot: - r"""Returns the specified Snapshot resource. Gets a list - of available snapshots by making a list() request. + r"""Returns the specified Snapshot resource. Args: request (Union[google.cloud.compute_v1.types.GetSnapshotRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py index 866b33c1d3a3..6cef0b86db90 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_certificates/client.py @@ -727,9 +727,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.SslCertificate: - r"""Returns the specified SslCertificate resource. Gets a - list of available SSL certificates by making a list() - request. + r"""Returns the specified SslCertificate resource. Args: request (Union[google.cloud.compute_v1.types.GetSslCertificateRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py index 0c0f5142d85a..f20169a1b68d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/ssl_policies/client.py @@ -824,9 +824,7 @@ def insert_unary( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: - r"""Returns the specified SSL policy resource. Gets a - list of available SSL policies by making a list() - request. + r"""Returns the specified SSL policy resource. Args: request (Union[google.cloud.compute_v1.types.InsertSslPolicyRequest, dict]): @@ -909,9 +907,7 @@ def insert( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> extended_operation.ExtendedOperation: - r"""Returns the specified SSL policy resource. Gets a - list of available SSL policies by making a list() - request. + r"""Returns the specified SSL policy resource. Args: request (Union[google.cloud.compute_v1.types.InsertSslPolicyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py index 6a83209f3953..e1ce42e34da0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/subnetworks/client.py @@ -1015,8 +1015,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Subnetwork: - r"""Returns the specified subnetwork. Gets a list of - available subnetworks list() request. + r"""Returns the specified subnetwork. Args: request (Union[google.cloud.compute_v1.types.GetSubnetworkRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py index ac775d871808..f5bb45d3b7d8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_http_proxies/client.py @@ -727,9 +727,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetHttpProxy: - r"""Returns the specified TargetHttpProxy resource. Gets - a list of available target HTTP proxies by making a - list() request. + r"""Returns the specified TargetHttpProxy resource. Args: request (Union[google.cloud.compute_v1.types.GetTargetHttpProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py index 1874dd851ddb..41b675dc013d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_https_proxies/client.py @@ -727,9 +727,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetHttpsProxy: - r"""Returns the specified TargetHttpsProxy resource. Gets - a list of available target HTTPS proxies by making a - list() request. + r"""Returns the specified TargetHttpsProxy resource. Args: request (Union[google.cloud.compute_v1.types.GetTargetHttpsProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py index 0b4cd367fd55..ede22d08667a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_instances/client.py @@ -748,9 +748,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetInstance: - r"""Returns the specified TargetInstance resource. Gets a - list of available target instances by making a list() - request. + r"""Returns the specified TargetInstance resource. Args: request (Union[google.cloud.compute_v1.types.GetTargetInstanceRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py index 74c931f00fb9..12fb016b6d4b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_pools/client.py @@ -1264,8 +1264,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetPool: - r"""Returns the specified target pool. Gets a list of - available target pools by making a list() request. + r"""Returns the specified target pool. Args: request (Union[google.cloud.compute_v1.types.GetTargetPoolRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py index c30934e68fdc..c5e3d2b1859e 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_ssl_proxies/client.py @@ -637,9 +637,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetSslProxy: - r"""Returns the specified TargetSslProxy resource. Gets a - list of available target SSL proxies by making a list() - request. + r"""Returns the specified TargetSslProxy resource. Args: request (Union[google.cloud.compute_v1.types.GetTargetSslProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py index 97a39f51be7f..00f30f9e4820 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_tcp_proxies/client.py @@ -727,9 +727,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetTcpProxy: - r"""Returns the specified TargetTcpProxy resource. Gets a - list of available target TCP proxies by making a list() - request. + r"""Returns the specified TargetTcpProxy resource. Args: request (Union[google.cloud.compute_v1.types.GetTargetTcpProxyRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py index 051c9e2f2982..960c807bb239 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/target_vpn_gateways/client.py @@ -744,9 +744,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TargetVpnGateway: - r"""Returns the specified target VPN gateway. Gets a list - of available target VPN gateways by making a list() - request. + r"""Returns the specified target VPN gateway. Args: request (Union[google.cloud.compute_v1.types.GetTargetVpnGatewayRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py index c42ce39e58b5..00be935ae5c4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/url_maps/client.py @@ -721,8 +721,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.UrlMap: - r"""Returns the specified UrlMap resource. Gets a list of - available URL maps by making a list() request. + r"""Returns the specified UrlMap resource. Args: request (Union[google.cloud.compute_v1.types.GetUrlMapRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py index be239ab6796e..5c229e8d5c57 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_gateways/client.py @@ -736,8 +736,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.VpnGateway: - r"""Returns the specified VPN gateway. Gets a list of - available VPN gateways by making a list() request. + r"""Returns the specified VPN gateway. Args: request (Union[google.cloud.compute_v1.types.GetVpnGatewayRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py index 9119ca052825..d365fd53f881 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/vpn_tunnels/client.py @@ -740,8 +740,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.VpnTunnel: - r"""Returns the specified VpnTunnel resource. Gets a list - of available VPN tunnels by making a list() request. + r"""Returns the specified VpnTunnel resource. Args: request (Union[google.cloud.compute_v1.types.GetVpnTunnelRequest, dict]): diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py index b783da123a79..c1e61ddbe376 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/zones/client.py @@ -428,8 +428,7 @@ def get( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Zone: - r"""Returns the specified Zone resource. Gets a list of - available zones by making a list() request. + r"""Returns the specified Zone resource. Args: request (Union[google.cloud.compute_v1.types.GetZoneRequest, dict]): 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 143c232be0be..f605578983a0 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 @@ -58,6 +58,7 @@ AggregatedListInstanceGroupManagersRequest, AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, + AggregatedListInstanceTemplatesRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -217,6 +218,7 @@ DeleteRegionHealthCheckRequest, DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, + DeleteRegionInstanceTemplateRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -397,6 +399,7 @@ GetRegionHealthCheckServiceRequest, GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, + GetRegionInstanceTemplateRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -526,6 +529,7 @@ InsertRegionHealthCheckRequest, InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, + InsertRegionInstanceTemplateRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -613,10 +617,13 @@ InstancesSetMachineResourcesRequest, InstancesSetMachineTypeRequest, InstancesSetMinCpuPlatformRequest, + InstancesSetNameRequest, InstancesSetServiceAccountRequest, InstancesStartWithEncryptionKeyRequest, InstanceTemplate, + InstanceTemplateAggregatedList, InstanceTemplateList, + InstanceTemplatesScopedList, InstanceWithNamedPorts, Int64RangeMatch, Interconnect, @@ -711,6 +718,7 @@ ListRegionHealthChecksRequest, ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, + ListRegionInstanceTemplatesRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -1049,6 +1057,9 @@ SecurityPolicyRuleHttpHeaderActionHttpHeaderOption, SecurityPolicyRuleMatcher, SecurityPolicyRuleMatcherConfig, + SecurityPolicyRulePreconfiguredWafConfig, + SecurityPolicyRulePreconfiguredWafConfigExclusion, + SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams, SecurityPolicyRuleRateLimitOptions, SecurityPolicyRuleRateLimitOptionsThreshold, SecurityPolicyRuleRedirectOptions, @@ -1119,6 +1130,7 @@ SetMinCpuPlatformInstanceRequest, SetNamedPortsInstanceGroupRequest, SetNamedPortsRegionInstanceGroupRequest, + SetNameInstanceRequest, SetNodeTemplateNodeGroupRequest, SetPrivateIpGoogleAccessSubnetworkRequest, SetProxyHeaderTargetSslProxyRequest, @@ -1262,6 +1274,7 @@ UpdateAutoscalerRequest, UpdateBackendBucketRequest, UpdateBackendServiceRequest, + UpdateDiskRequest, UpdateDisplayDeviceInstanceRequest, UpdateFirewallRequest, UpdateHealthCheckRequest, @@ -1273,6 +1286,7 @@ UpdateRegionAutoscalerRequest, UpdateRegionBackendServiceRequest, UpdateRegionCommitmentRequest, + UpdateRegionDiskRequest, UpdateRegionHealthCheckRequest, UpdateRegionUrlMapRequest, UpdateReservationRequest, @@ -1375,6 +1389,7 @@ "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", "AggregatedListInstancesRequest", + "AggregatedListInstanceTemplatesRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -1534,6 +1549,7 @@ "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", + "DeleteRegionInstanceTemplateRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -1714,6 +1730,7 @@ "GetRegionHealthCheckServiceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", + "GetRegionInstanceTemplateRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -1843,6 +1860,7 @@ "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", + "InsertRegionInstanceTemplateRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -1930,10 +1948,13 @@ "InstancesSetMachineResourcesRequest", "InstancesSetMachineTypeRequest", "InstancesSetMinCpuPlatformRequest", + "InstancesSetNameRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", "InstanceTemplate", + "InstanceTemplateAggregatedList", "InstanceTemplateList", + "InstanceTemplatesScopedList", "InstanceWithNamedPorts", "Int64RangeMatch", "Interconnect", @@ -2028,6 +2049,7 @@ "ListRegionHealthChecksRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", + "ListRegionInstanceTemplatesRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2366,6 +2388,9 @@ "SecurityPolicyRuleHttpHeaderActionHttpHeaderOption", "SecurityPolicyRuleMatcher", "SecurityPolicyRuleMatcherConfig", + "SecurityPolicyRulePreconfiguredWafConfig", + "SecurityPolicyRulePreconfiguredWafConfigExclusion", + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", "SecurityPolicyRuleRateLimitOptions", "SecurityPolicyRuleRateLimitOptionsThreshold", "SecurityPolicyRuleRedirectOptions", @@ -2436,6 +2461,7 @@ "SetMinCpuPlatformInstanceRequest", "SetNamedPortsInstanceGroupRequest", "SetNamedPortsRegionInstanceGroupRequest", + "SetNameInstanceRequest", "SetNodeTemplateNodeGroupRequest", "SetPrivateIpGoogleAccessSubnetworkRequest", "SetProxyHeaderTargetSslProxyRequest", @@ -2579,6 +2605,7 @@ "UpdateAutoscalerRequest", "UpdateBackendBucketRequest", "UpdateBackendServiceRequest", + "UpdateDiskRequest", "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateHealthCheckRequest", @@ -2590,6 +2617,7 @@ "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", + "UpdateRegionDiskRequest", "UpdateRegionHealthCheckRequest", "UpdateRegionUrlMapRequest", "UpdateReservationRequest", 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 5efaacc21e46..a1d7f7bb99e5 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 @@ -65,6 +65,7 @@ "AggregatedListHealthChecksRequest", "AggregatedListInstanceGroupManagersRequest", "AggregatedListInstanceGroupsRequest", + "AggregatedListInstanceTemplatesRequest", "AggregatedListInstancesRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", @@ -225,6 +226,7 @@ "DeleteRegionHealthCheckRequest", "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", + "DeleteRegionInstanceTemplateRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -406,6 +408,7 @@ "GetRegionHealthCheckServiceRequest", "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", + "GetRegionInstanceTemplateRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -534,6 +537,7 @@ "InsertRegionHealthCheckRequest", "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", + "InsertRegionInstanceTemplateRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -613,7 +617,9 @@ "InstanceProperties", "InstanceReference", "InstanceTemplate", + "InstanceTemplateAggregatedList", "InstanceTemplateList", + "InstanceTemplatesScopedList", "InstanceWithNamedPorts", "InstancesAddResourcePoliciesRequest", "InstancesGetEffectiveFirewallsResponse", @@ -624,6 +630,7 @@ "InstancesSetMachineResourcesRequest", "InstancesSetMachineTypeRequest", "InstancesSetMinCpuPlatformRequest", + "InstancesSetNameRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", "Int64RangeMatch", @@ -719,6 +726,7 @@ "ListRegionHealthChecksRequest", "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", + "ListRegionInstanceTemplatesRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -1058,6 +1066,9 @@ "SecurityPolicyRuleHttpHeaderActionHttpHeaderOption", "SecurityPolicyRuleMatcher", "SecurityPolicyRuleMatcherConfig", + "SecurityPolicyRulePreconfiguredWafConfig", + "SecurityPolicyRulePreconfiguredWafConfigExclusion", + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", "SecurityPolicyRuleRateLimitOptions", "SecurityPolicyRuleRateLimitOptionsThreshold", "SecurityPolicyRuleRedirectOptions", @@ -1126,6 +1137,7 @@ "SetMachineTypeInstanceRequest", "SetMetadataInstanceRequest", "SetMinCpuPlatformInstanceRequest", + "SetNameInstanceRequest", "SetNamedPortsInstanceGroupRequest", "SetNamedPortsRegionInstanceGroupRequest", "SetNodeTemplateNodeGroupRequest", @@ -1270,6 +1282,7 @@ "UpdateAutoscalerRequest", "UpdateBackendBucketRequest", "UpdateBackendServiceRequest", + "UpdateDiskRequest", "UpdateDisplayDeviceInstanceRequest", "UpdateFirewallRequest", "UpdateHealthCheckRequest", @@ -1281,6 +1294,7 @@ "UpdateRegionAutoscalerRequest", "UpdateRegionBackendServiceRequest", "UpdateRegionCommitmentRequest", + "UpdateRegionDiskRequest", "UpdateRegionHealthCheckRequest", "UpdateRegionUrlMapRequest", "UpdateReservationRequest", @@ -1835,9 +1849,12 @@ class AccessConfig(proto.Message): The first IPv6 address of the external IPv6 range associated with this instance, prefix length is stored in externalIpv6PrefixLength in - ipv6AccessConfig. The field is output only, an - IPv6 address from a subnetwork associated with - the instance will be allocated dynamically. + ipv6AccessConfig. To use a static external IP + address, it must be unused and in the same + region as the instance's zone. If not specified, + Google Cloud will automatically assign an + external IPv6 address from the instance's + subnetwork. This field is a member of `oneof`_ ``_external_ipv6``. external_ipv6_prefix_length (int): @@ -3396,7 +3413,7 @@ class Purpose(proto.Enum): attachment is created with the reserved IP address range, when creating a new VPN gateway, its interface IP address is allocated from the - associated VLAN attachment���s IP address range. + associated VLAN attachment’s IP address range. NAT_AUTO (163666477): External IP automatically reserved for Cloud NAT. @@ -5317,6 +5334,145 @@ class AggregatedListInstanceGroupsRequest(proto.Message): ) +class AggregatedListInstanceTemplatesRequest(proto.Message): + r"""A request message for InstanceTemplates.AggregatedList. 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. 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 ``:`` operator can be used + with string fields to match substrings. For non-string + fields it is equivalent to the ``=`` operator. 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 on + resource 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 + Google RE2 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``. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + 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): + Name of the project scoping 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. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + 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 AggregatedListInstancesRequest(proto.Message): r"""A request message for Instances.AggregatedList. See the method description for details. @@ -9390,12 +9546,13 @@ class AliasIpRange(proto.Message): class AllocationResourceStatus(proto.Message): - r""" + r"""[Output Only] Contains output only fields. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: specific_sku_allocation (google.cloud.compute_v1.types.AllocationResourceStatusSpecificSKUAllocation): + Allocation Properties of this reservation. This field is a member of `oneof`_ ``_specific_sku_allocation``. """ @@ -9411,12 +9568,14 @@ class AllocationResourceStatus(proto.Message): class AllocationResourceStatusSpecificSKUAllocation(proto.Message): - r""" + r"""Contains Properties set for the reservation. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: source_instance_template_id (str): + ID of the instance template used to populate + reservation properties. This field is a member of `oneof`_ ``_source_instance_template_id``. """ @@ -11760,8 +11919,7 @@ class AutoscalingPolicyScalingSchedule(proto.Message): The time zone to use when interpreting the schedule. The value of this field must be a time zone name from the tz database: http://en.wikipedia.org/wiki/Tz_database. This - field is assigned a default value of ���UTC��� if left - empty. + field is assigned a default value of “UTC” if left empty. This field is a member of `oneof`_ ``_time_zone``. """ @@ -12756,14 +12914,17 @@ class BackendService(proto.Message): This field is a member of `oneof`_ ``_load_balancing_scheme``. locality_lb_policies (MutableSequence[google.cloud.compute_v1.types.BackendServiceLocalityLoadBalancingPolicyConfig]): - A list of locality load balancing policies to - be used in order of preference. Either the - policy or the customPolicy field should be set. - Overrides any value set in the localityLbPolicy - field. localityLbPolicies is only supported when - the BackendService is referenced by a URL Map - that is referenced by a target gRPC proxy that - has the validateForProxyless field set to true. + A list of locality load-balancing policies to be used in + order of preference. When you use localityLbPolicies, you + must set at least one value for either the + localityLbPolicies[].policy or the + localityLbPolicies[].customPolicy field. localityLbPolicies + overrides any value set in the localityLbPolicy field. For + an example of how to use this field, see Define a list of + preferred policies. Caution: This field and its children are + intended for use in a service mesh that includes gRPC + clients only. Envoy proxies can't use backend services that + have this configuration. locality_lb_policy (str): The load balancing algorithm used within the scope of the locality. The possible values are: - ROUND_ROBIN: This is a @@ -13061,6 +13222,18 @@ class LocalityLbPolicy(proto.Enum): This is a simple policy in which each healthy backend is selected in round robin order. This is the default. + WEIGHTED_MAGLEV (254930962): + Per-instance weighted Load Balancing via health check + reported weights. If set, the Backend Service must configure + a non legacy HTTP-based Health Check, and health check + replies are expected to contain non-standard HTTP response + header field X-Load-Balancing-Endpoint-Weight to specify the + per-instance weights. If set, Load Balancing is weighted + based on the per-instance 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 option + is only supported in Network Load Balancing. """ UNDEFINED_LOCALITY_LB_POLICY = 0 INVALID_LB_POLICY = 323318707 @@ -13070,6 +13243,7 @@ class LocalityLbPolicy(proto.Enum): RANDOM = 262527171 RING_HASH = 432795069 ROUND_ROBIN = 153895801 + WEIGHTED_MAGLEV = 254930962 class Protocol(proto.Enum): r"""The protocol this BackendService uses to communicate with @@ -14229,14 +14403,15 @@ class BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy(proto.Message) This field is a member of `oneof`_ ``_data``. name (str): Identifies the custom policy. The value - should match the type the custom implementation - is registered with on the gRPC clients. It - should follow protocol buffer message naming - conventions and include the full path (e.g. + should match the name of a custom implementation + registered on the gRPC clients. It should follow + protocol buffer message naming conventions and + include the full path (for example, myorg.CustomLbPolicy). The maximum length is 256 - characters. Note that specifying the same custom - policy more than once for a backend is not a - valid configuration and will be rejected. + characters. Do not specify the same custom + policy more than once for a backend. If you do, + the configuration is rejected. For an example of + how to use this field, see Use a custom policy. This field is a member of `oneof`_ ``_name``. """ @@ -14260,26 +14435,23 @@ class BackendServiceLocalityLoadBalancingPolicyConfigPolicy(proto.Message): Attributes: name (str): - The name of a locality load balancer policy to be used. The - value should be one of the predefined ones as supported by - localityLbPolicy, although at the moment only ROUND_ROBIN is - supported. This field should only be populated when the - customPolicy field is not used. Note that specifying the - same policy more than once for a backend is not a valid - configuration and will be rejected. Check the Name enum for - the list of possible values. + The name of a locality load-balancing policy. Valid values + include ROUND_ROBIN and, for Java clients, LEAST_REQUEST. + For information about these values, see the description of + localityLbPolicy. Do not specify the same policy more than + once for a backend. If you do, the configuration is + rejected. Check the Name enum for the list of possible + values. This field is a member of `oneof`_ ``_name``. """ class Name(proto.Enum): - r"""The name of a locality load balancer policy to be used. The value - should be one of the predefined ones as supported by - localityLbPolicy, although at the moment only ROUND_ROBIN is - supported. This field should only be populated when the customPolicy - field is not used. Note that specifying the same policy more than - once for a backend is not a valid configuration and will be - rejected. + r"""The name of a locality load-balancing policy. Valid values include + ROUND_ROBIN and, for Java clients, LEAST_REQUEST. For information + about these values, see the description of localityLbPolicy. Do not + specify the same policy more than once for a backend. If you do, the + configuration is rejected. Values: UNDEFINED_NAME (0): @@ -14319,6 +14491,18 @@ class Name(proto.Enum): This is a simple policy in which each healthy backend is selected in round robin order. This is the default. + WEIGHTED_MAGLEV (254930962): + Per-instance weighted Load Balancing via health check + reported weights. If set, the Backend Service must configure + a non legacy HTTP-based Health Check, and health check + replies are expected to contain non-standard HTTP response + header field X-Load-Balancing-Endpoint-Weight to specify the + per-instance weights. If set, Load Balancing is weighted + based on the per-instance 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 option + is only supported in Network Load Balancing. """ UNDEFINED_NAME = 0 INVALID_LB_POLICY = 323318707 @@ -14328,6 +14512,7 @@ class Name(proto.Enum): RANDOM = 262527171 RING_HASH = 432795069 ROUND_ROBIN = 153895801 + WEIGHTED_MAGLEV = 254930962 name: str = proto.Field( proto.STRING, @@ -14350,6 +14535,23 @@ class BackendServiceLogConfig(proto.Message): service. The default value is false. This field is a member of `oneof`_ ``_enable``. + optional_fields (MutableSequence[str]): + This field can only be specified if logging + is enabled for this backend service and + "logConfig.optionalMode" was set to CUSTOM. + Contains a list of optional fields you want to + include in the logs. For example: + serverInstance, serverGkeDetails.cluster, + serverGkeDetails.pod.podNamespace + optional_mode (str): + This field can only be specified if logging is enabled for + this backend service. Configures whether all, none or a + subset of optional fields should be added to the reported + logs. One of [INCLUDE_ALL_OPTIONAL, EXCLUDE_ALL_OPTIONAL, + CUSTOM]. Default is EXCLUDE_ALL_OPTIONAL. Check the + OptionalMode enum for the list of possible values. + + This field is a member of `oneof`_ ``_optional_mode``. sample_rate (float): This field can only be specified if logging is enabled for this backend service. The value of the field must be in [0, @@ -14361,11 +14563,43 @@ class BackendServiceLogConfig(proto.Message): This field is a member of `oneof`_ ``_sample_rate``. """ + class OptionalMode(proto.Enum): + r"""This field can only be specified if logging is enabled for this + backend service. Configures whether all, none or a subset of + optional fields should be added to the reported logs. One of + [INCLUDE_ALL_OPTIONAL, EXCLUDE_ALL_OPTIONAL, CUSTOM]. Default is + EXCLUDE_ALL_OPTIONAL. + + Values: + UNDEFINED_OPTIONAL_MODE (0): + A value indicating that the enum field is not + set. + CUSTOM (388595569): + A subset of optional fields. + EXCLUDE_ALL_OPTIONAL (168636099): + None optional fields. + INCLUDE_ALL_OPTIONAL (535606965): + All optional fields. + """ + UNDEFINED_OPTIONAL_MODE = 0 + CUSTOM = 388595569 + EXCLUDE_ALL_OPTIONAL = 168636099 + INCLUDE_ALL_OPTIONAL = 535606965 + enable: bool = proto.Field( proto.BOOL, number=311764355, optional=True, ) + optional_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=528589944, + ) + optional_mode: str = proto.Field( + proto.STRING, + number=128697122, + optional=True, + ) sample_rate: float = proto.Field( proto.FLOAT, number=153193045, @@ -14989,6 +15223,9 @@ class Binding(proto.Message): ``my-project.svc.id.goog[my-namespace/my-kubernetes-sa]``. \* ``group:{emailid}``: An email address that represents a Google group. For example, ``admins@example.com``. \* + ``domain:{domain}``: The G Suite domain (primary) that + represents all the users of that domain. For example, + ``google.com`` or ``example.com``. \* ``deleted:user:{emailid}?uid={uniqueid}``: An email address (plus unique identifier) representing a user that has been recently deleted. For example, @@ -15008,9 +15245,7 @@ class Binding(proto.Message): ``admins@example.com?uid=123456789012345678901``. If the group is recovered, this value reverts to ``group:{emailid}`` and the recovered group retains the role - in the binding. \* ``domain:{domain}``: The G Suite domain - (primary) that represents all the users of that domain. For - example, ``google.com`` or ``example.com``. + in the binding. role (str): Role that is assigned to the list of ``members``, or principals. For example, ``roles/viewer``, ``roles/editor``, @@ -15834,7 +16069,9 @@ class Status(proto.Enum): ACTIVE (314733318): No description available. CANCELLED (41957681): - No description available. + Deprecate CANCELED status. Will use separate + status to differentiate cancel by mergeCud or + manual cancellation. CREATING (455564985): No description available. EXPIRED (482489093): @@ -15866,6 +16103,8 @@ class Type(proto.Enum): No description available. COMPUTE_OPTIMIZED_C2D (383246453): No description available. + COMPUTE_OPTIMIZED_C3 (428004784): + No description available. GENERAL_PURPOSE (299793543): No description available. GENERAL_PURPOSE_E2 (301911877): @@ -15887,6 +16126,7 @@ class Type(proto.Enum): ACCELERATOR_OPTIMIZED = 280848403 COMPUTE_OPTIMIZED = 158349023 COMPUTE_OPTIMIZED_C2D = 383246453 + COMPUTE_OPTIMIZED_C3 = 428004784 GENERAL_PURPOSE = 299793543 GENERAL_PURPOSE_E2 = 301911877 GENERAL_PURPOSE_N2 = 301912156 @@ -19343,6 +19583,59 @@ class DeleteRegionInstanceGroupManagerRequest(proto.Message): ) +class DeleteRegionInstanceTemplateRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.Delete. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_template (str): + The name of the instance template to delete. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + instance_template: str = proto.Field( + proto.STRING, + number=309248228, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class DeleteRegionNetworkEndpointGroupRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.Delete. See the method description for details. @@ -25127,6 +25420,15 @@ class ForwardingRule(proto.Message): balancer types. This field is a member of `oneof`_ ``_backend_service``. + base_forwarding_rule (str): + [Output Only] The URL for the corresponding base Forwarding + Rule. By base Forwarding Rule, we mean the Forwarding Rule + that has the same IP address, protocol, and port settings + with the current Forwarding Rule, but without sourceIPRanges + specified. Always empty if the current Forwarding Rule does + not have sourceIPRanges specified. + + This field is a member of `oneof`_ ``_base_forwarding_rule``. creation_timestamp (str): [Output Only] Creation timestamp in RFC3339 text format. @@ -25353,6 +25655,15 @@ class ForwardingRule(proto.Message): load balancing. This field is a member of `oneof`_ ``_service_name``. + source_ip_ranges (MutableSequence[str]): + If not empty, this Forwarding Rule will only forward the + traffic when the source IP address matches one of the IP + addresses or CIDR ranges set here. Note that a Forwarding + Rule can only have up to 64 source IP ranges, and this field + can only be used with a regional Forwarding Rule whose + scheme is EXTERNAL. Each source_ip_range entry should be + either an IP address (for example, 1.2.3.4) or a CIDR range + (for example, 1.2.3.0/24). subnetwork (str): This field identifies the subnetwork that the load balanced IP should belong to for this @@ -25561,6 +25872,11 @@ class PscConnectionStatus(proto.Enum): number=306946058, optional=True, ) + base_forwarding_rule: str = proto.Field( + proto.STRING, + number=524873104, + optional=True, + ) creation_timestamp: str = proto.Field( proto.STRING, number=30525366, @@ -25682,6 +25998,10 @@ class PscConnectionStatus(proto.Enum): number=359880149, optional=True, ) + source_ip_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=111563210, + ) subnetwork: str = proto.Field( proto.STRING, number=307827694, @@ -26549,7 +26869,9 @@ class GetFromFamilyImageRequest(proto.Message): family (str): Name of the image family to search for. project (str): - Project ID for this request. + The image project that the image belongs to. + For example, to get a CentOS image, specify + centos-cloud as the image project. """ family: str = proto.Field( @@ -28591,6 +28913,33 @@ class GetRegionInstanceGroupRequest(proto.Message): ) +class GetRegionInstanceTemplateRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.Get. See the + method description for details. + + Attributes: + instance_template (str): + The name of the instance template. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + """ + + instance_template: str = proto.Field( + proto.STRING, + number=309248228, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetRegionNetworkEndpointGroupRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.Get. See the method description for details. @@ -30214,9 +30563,10 @@ class GuestOsFeature(proto.Message): commas to separate values. Set to one or more of the following values: - VIRTIO_SCSI_MULTIQUEUE - WINDOWS - MULTI_IP_SUBNET - UEFI_COMPATIBLE - GVNIC - SEV_CAPABLE - - SUSPEND_RESUME_COMPATIBLE - SEV_SNP_CAPABLE For more - information, see Enabling guest operating system features. - Check the Type enum for the list of possible values. + SUSPEND_RESUME_COMPATIBLE - SEV_SNP_CAPABLE - TDX_CAPABLE + For more information, see Enabling guest operating system + features. Check the Type enum for the list of possible + values. This field is a member of `oneof`_ ``_type``. """ @@ -30226,7 +30576,8 @@ class Type(proto.Enum): separate values. Set to one or more of the following values: - VIRTIO_SCSI_MULTIQUEUE - WINDOWS - MULTI_IP_SUBNET - UEFI_COMPATIBLE - GVNIC - SEV_CAPABLE - SUSPEND_RESUME_COMPATIBLE - SEV_SNP_CAPABLE - For more information, see Enabling guest operating system features. + - TDX_CAPABLE For more information, see Enabling guest operating + system features. Values: UNDEFINED_TYPE (0): @@ -32977,11 +33328,17 @@ class Image(proto.Message): This field is a member of `oneof`_ ``_disk_size_gb``. family (str): The name of the image family to which this - image belongs. You can create disks by - specifying an image family instead of a specific - image name. The image family always returns its - latest image that is not deprecated. The name of - the image family must comply with RFC1035. + image belongs. The image family name can be from + a publicly managed image family provided by + Compute Engine, or from a custom image family + you create. For example, centos-stream-9 is a + publicly available image family. For more + information, see Image family best practices. + When creating disks, you can specify an image + family instead of a specific image name. The + image family always returns its latest image + that is not deprecated. The name of the image + family must comply with RFC1035. This field is a member of `oneof`_ ``_family``. guest_os_features (MutableSequence[google.cloud.compute_v1.types.GuestOsFeature]): @@ -35676,6 +36033,60 @@ class InsertRegionInstanceGroupManagerRequest(proto.Message): ) +class InsertRegionInstanceTemplateRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_template_resource (google.cloud.compute_v1.types.InstanceTemplate): + The body resource for this request + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + instance_template_resource: "InstanceTemplate" = proto.Field( + proto.MESSAGE, + number=10679561, + message="InstanceTemplate", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class InsertRegionNetworkEndpointGroupRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.Insert. See the method description for details. @@ -39524,8 +39935,8 @@ class InstanceGroupManagersApplyUpdatesRequest(proto.Message): Attributes: all_instances (bool): Flag to update all instances instead of - specified list of ���instances���. If the flag - is set to true then the instances may not be + specified list of “instances”. If the flag is + set to true then the instances may not be specified in the request. This field is a member of `oneof`_ ``_all_instances``. @@ -40951,6 +41362,11 @@ class InstanceTemplate(proto.Message): template. This field is a member of `oneof`_ ``_properties``. + region (str): + [Output Only] URL of the region where the instance template + resides. Only applicable for regional resources. + + This field is a member of `oneof`_ ``_region``. self_link (str): [Output Only] The URL for this instance template. The server defines this URL. @@ -41004,6 +41420,11 @@ class InstanceTemplate(proto.Message): optional=True, message="InstanceProperties", ) + region: str = proto.Field( + proto.STRING, + number=138946292, + optional=True, + ) self_link: str = proto.Field( proto.STRING, number=456214797, @@ -41022,6 +41443,81 @@ class InstanceTemplate(proto.Message): ) +class InstanceTemplateAggregatedList(proto.Message): + r"""Contains a list of InstanceTemplatesScopedList. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableMapping[str, google.cloud.compute_v1.types.InstanceTemplatesScopedList]): + A list of InstanceTemplatesScopedList + resources. + kind (str): + Type of resource. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger than maxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + [Output Only] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + 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: MutableMapping[str, "InstanceTemplatesScopedList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="InstanceTemplatesScopedList", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class InstanceTemplateList(proto.Message): r"""A list of instance templates. @@ -41097,6 +41593,35 @@ def raw_page(self): ) +class InstanceTemplatesScopedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_templates (MutableSequence[google.cloud.compute_v1.types.InstanceTemplate]): + [Output Only] A list of instance templates that are + contained within the specified project and zone. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] An informational warning that replaces the + list of instance templates when the list is empty. + + This field is a member of `oneof`_ ``_warning``. + """ + + instance_templates: MutableSequence["InstanceTemplate"] = proto.RepeatedField( + proto.MESSAGE, + number=459889679, + message="InstanceTemplate", + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class InstanceWithNamedPorts(proto.Message): r""" @@ -41428,6 +41953,37 @@ class InstancesSetMinCpuPlatformRequest(proto.Message): ) +class InstancesSetNameRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_name (str): + The current name of this resource, used to + prevent conflicts. Provide the latest name when + making a request to change name. + + This field is a member of `oneof`_ ``_current_name``. + name (str): + The name to be applied to the instance. Needs + to be RFC 1035 compliant. + + This field is a member of `oneof`_ ``_name``. + """ + + current_name: str = proto.Field( + proto.STRING, + number=394983825, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + + class InstancesSetServiceAccountRequest(proto.Message): r""" @@ -41651,9 +42207,7 @@ class Interconnect(proto.Message): This field is a member of `oneof`_ ``_requested_link_count``. satisfies_pzs (bool): - [Output Only] Set to true if the resource satisfies the zone - separation organization policy constraints and false - otherwise. Defaults to false if the field is not present. + [Output Only] Reserved for future use. This field is a member of `oneof`_ ``_satisfies_pzs``. self_link (str): @@ -42132,9 +42686,7 @@ class InterconnectAttachment(proto.Message): This field is a member of `oneof`_ ``_router``. satisfies_pzs (bool): - [Output Only] Set to true if the resource satisfies the zone - separation organization policy constraints and false - otherwise. Defaults to false if the field is not present. + [Output Only] Reserved for future use. This field is a member of `oneof`_ ``_satisfies_pzs``. self_link (str): @@ -42186,7 +42738,7 @@ class InterconnectAttachment(proto.Message): This field is a member of `oneof`_ ``_type``. vlan_tag8021q (int): The IEEE 802.1Q VLAN tag for this attachment, - in the range 2-4094. Only specified at creation + in the range 2-4093. Only specified at creation time. This field is a member of `oneof`_ ``_vlan_tag8021q``. @@ -43476,9 +44028,7 @@ class InterconnectLocation(proto.Message): This field is a member of `oneof`_ ``_status``. supports_pzs (bool): - [Output Only] Set to true for locations that support - physical zone separation. Defaults to false if the field is - not present. + [Output Only] Reserved for future use. This field is a member of `oneof`_ ``_supports_pzs``. """ @@ -46119,7 +46669,10 @@ class ListFirewallPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. parent_id (str): - Parent ID for this request. + Parent ID for this request. The ID can be either be + "folders/[FOLDER_ID]" if the parent is a folder or + "organizations/[ORGANIZATION_ID]" if the parent is an + organization. This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): @@ -52688,6 +53241,133 @@ class ListRegionInstanceGroupsRequest(proto.Message): ) +class ListRegionInstanceTemplatesRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.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. 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 ``:`` operator can be used + with string fields to match substrings. For non-string + fields it is equivalent to the ``=`` operator. 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 on + resource 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 + Google RE2 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``. + + 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. + region (str): + The name of the regions 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. + + 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, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListRegionNetworkEndpointGroupsRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.List. See the method description for details. @@ -59001,7 +59681,10 @@ class MoveFirewallPolicyRequest(proto.Message): firewall_policy (str): Name of the firewall policy to update. parent_id (str): - The new parent of the firewall policy. + The new parent of the firewall policy. The ID can be either + be "folders/[FOLDER_ID]" if the parent is a folder or + "organizations/[ORGANIZATION_ID]" if the parent is an + organization. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -61043,7 +61726,12 @@ class NetworkInterface(proto.Message): This field is a member of `oneof`_ ``_ipv6_access_type``. ipv6_address (str): An IPv6 internal network address for this - network interface. + network interface. To use a static internal IP + address, it must be unused and in the same + region as the instance's zone. If not specified, + Google Cloud will automatically assign an + internal IPv6 address from the instance's + subnetwork. This field is a member of `oneof`_ ``_ipv6_address``. kind (str): @@ -62731,11 +63419,7 @@ class NodeTemplate(proto.Message): This field is a member of `oneof`_ ``_node_type``. node_type_flexibility (google.cloud.compute_v1.types.NodeTemplateNodeTypeFlexibility): - The flexible properties of the desired node type. Node - groups that use this node template will create nodes of a - type that matches these properties. This field is mutually - exclusive with the node_type property; you can only define - one or the other, but not both. + Do not use. Instead, use the node_type property. This field is a member of `oneof`_ ``_node_type_flexibility``. region (str): @@ -69709,6 +70393,8 @@ class Metric(proto.Enum): No description available. NETWORKS (485481477): No description available. + NETWORK_ATTACHMENTS (149028575): + No description available. NETWORK_ENDPOINT_GROUPS (102144909): No description available. NETWORK_FIREWALL_POLICIES (101117374): @@ -69921,6 +70607,7 @@ class Metric(proto.Enum): N2D_CPUS = 351743370 N2_CPUS = 416465286 NETWORKS = 485481477 + NETWORK_ATTACHMENTS = 149028575 NETWORK_ENDPOINT_GROUPS = 102144909 NETWORK_FIREWALL_POLICIES = 101117374 NODE_GROUPS = 24624817 @@ -70845,8 +71532,8 @@ class RegionInstanceGroupManagersApplyUpdatesRequest(proto.Message): Attributes: all_instances (bool): Flag to update all instances instead of - specified list of ���instances���. If the flag - is set to true then the instances may not be + specified list of “instances”. If the flag is + set to true then the instances may not be specified in the request. This field is a member of `oneof`_ ``_all_instances``. @@ -72501,7 +73188,10 @@ class Reservation(proto.Message): This field is a member of `oneof`_ ``_name``. resource_policies (MutableMapping[str, str]): - + Resource policies to be added to this + reservation. The key is defined by user, and the + value is resource policy url. This is to define + placement policy with reservation. resource_status (google.cloud.compute_v1.types.AllocationResourceStatus): [Output Only] Status information for Reservation resource. @@ -73836,7 +74526,7 @@ class ResourcePolicyInstanceSchedulePolicy(proto.Message): Specifies the time zone to be used in interpreting Schedule.schedule. The value of this field must be a time zone name from the tz database: - http://en.wikipedia.org/wiki/Tz_database. + https://wikipedia.org/wiki/Tz_database. This field is a member of `oneof`_ ``_time_zone``. vm_start_schedule (google.cloud.compute_v1.types.ResourcePolicyInstanceSchedulePolicySchedule): @@ -75231,10 +75921,10 @@ class RouterBgpPeer(proto.Message): This field is a member of `oneof`_ ``_advertise_mode``. advertised_groups (MutableSequence[str]): User-specified list of prefix groups to advertise in custom - mode, which can take one of the following options: - - ALL_SUBNETS: Advertises all available subnets, including - peer VPC subnets. - ALL_VPC_SUBNETS: Advertises the router's - own VPC subnets. Note that this field can only be populated + mode, which currently supports the following option: - + ALL_SUBNETS: Advertises all of the router's own VPC subnets. + This excludes any routes learned for subnets that use VPC + Network Peering. Note that this field can only be populated if advertise_mode is CUSTOM and overrides the list defined for the router (in the "bgp" message). These groups are advertised in addition to any specified prefixes. Leave this @@ -78113,6 +78803,11 @@ class SecurityPolicy(proto.Message): internal service policies can be configured to filter HTTP requests targeting services managed by Traffic Director in a service mesh. They filter requests before the request is + served from the application. - CLOUD_ARMOR_NETWORK: Cloud + Armor network policies can be configured to filter packets + targeting network load balancing resources such as backend + services, target pools, target instances, and instances with + external IPs. They filter requests before the request is served from the application. This field can be set only at resource creation time. Check the Type enum for the list of possible values. @@ -78133,7 +78828,12 @@ class Type(proto.Enum): internal service policies can be configured to filter HTTP requests targeting services managed by Traffic Director in a service mesh. They filter requests before the request is served from the - application. This field can be set only at resource creation time. + application. - CLOUD_ARMOR_NETWORK: Cloud Armor network policies can + be configured to filter packets targeting network load balancing + resources such as backend services, target pools, target instances, + and instances with external IPs. They filter requests before the + request is served from the application. This field can be set only + at resource creation time. Values: UNDEFINED_TYPE (0): @@ -78548,18 +79248,18 @@ class SecurityPolicyRule(proto.Message): action (str): The Action to perform when the rule is matched. The following are the valid actions: - allow: allow access to - target. - deny(): deny access to target, returns the HTTP - response code specified (valid values are 403, 404, and - 502). - rate_based_ban: limit client traffic to the - configured threshold and ban the client if the traffic - exceeds the threshold. Configure parameters for this action - in RateLimitOptions. Requires rate_limit_options to be set. - - redirect: redirect to a different target. This can either - be an internal reCAPTCHA redirect, or an external URL-based - redirect via a 302 response. Parameters for this action can - be configured via redirectOptions. - throttle: limit client - traffic to the configured threshold. Configure parameters - for this action in rateLimitOptions. Requires + target. - deny(STATUS): deny access to target, returns the + HTTP response code specified. Valid values for ``STATUS`` + are 403, 404, and 502. - rate_based_ban: limit client + traffic to the configured threshold and ban the client if + the traffic exceeds the threshold. Configure parameters for + this action in RateLimitOptions. Requires rate_limit_options + to be set. - redirect: redirect to a different target. This + can either be an internal reCAPTCHA redirect, or an external + URL-based redirect via a 302 response. Parameters for this + action can be configured via redirectOptions. - throttle: + limit client traffic to the configured threshold. Configure + parameters for this action in rateLimitOptions. Requires rate_limit_options to be set for this. This field is a member of `oneof`_ ``_action``. @@ -78585,6 +79285,14 @@ class SecurityPolicyRule(proto.Message): corresponding 'action' is enforced. This field is a member of `oneof`_ ``_match``. + preconfigured_waf_config (google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfig): + Preconfigured WAF configuration to be applied + for the rule. If the rule does not evaluate + preconfigured WAF rules, i.e., if + evaluatePreconfiguredWaf() is not used, this + field will have no effect. + + This field is a member of `oneof`_ ``_preconfigured_waf_config``. preview (bool): If set to true, the specified action is not enforced. @@ -78638,6 +79346,12 @@ class SecurityPolicyRule(proto.Message): optional=True, message="SecurityPolicyRuleMatcher", ) + preconfigured_waf_config: "SecurityPolicyRulePreconfiguredWafConfig" = proto.Field( + proto.MESSAGE, + number=117805027, + optional=True, + message="SecurityPolicyRulePreconfiguredWafConfig", + ) preview: bool = proto.Field( proto.BOOL, number=218686408, @@ -78791,6 +79505,161 @@ class SecurityPolicyRuleMatcherConfig(proto.Message): ) +class SecurityPolicyRulePreconfiguredWafConfig(proto.Message): + r""" + + Attributes: + exclusions (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfigExclusion]): + A list of exclusions to apply during + preconfigured WAF evaluation. + """ + + exclusions: MutableSequence[ + "SecurityPolicyRulePreconfiguredWafConfigExclusion" + ] = proto.RepeatedField( + proto.MESSAGE, + number=208665701, + message="SecurityPolicyRulePreconfiguredWafConfigExclusion", + ) + + +class SecurityPolicyRulePreconfiguredWafConfigExclusion(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + request_cookies_to_exclude (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams]): + A list of request cookie names whose value + will be excluded from inspection during + preconfigured WAF evaluation. + request_headers_to_exclude (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams]): + A list of request header names whose value + will be excluded from inspection during + preconfigured WAF evaluation. + request_query_params_to_exclude (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams]): + A list of request query parameter names whose + value will be excluded from inspection during + preconfigured WAF evaluation. Note that the + parameter can be in the query string or in the + POST body. + request_uris_to_exclude (MutableSequence[google.cloud.compute_v1.types.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams]): + A list of request URIs from the request line + to be excluded from inspection during + preconfigured WAF evaluation. When specifying + this field, the query or fragment part should be + excluded. + target_rule_ids (MutableSequence[str]): + A list of target rule IDs under the WAF rule + set to apply the preconfigured WAF exclusion. If + omitted, it refers to all the rule IDs under the + WAF rule set. + target_rule_set (str): + Target WAF rule set to apply the + preconfigured WAF exclusion. + + This field is a member of `oneof`_ ``_target_rule_set``. + """ + + request_cookies_to_exclude: MutableSequence[ + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams" + ] = proto.RepeatedField( + proto.MESSAGE, + number=156757878, + message="SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", + ) + request_headers_to_exclude: MutableSequence[ + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams" + ] = proto.RepeatedField( + proto.MESSAGE, + number=63230495, + message="SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", + ) + request_query_params_to_exclude: MutableSequence[ + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams" + ] = proto.RepeatedField( + proto.MESSAGE, + number=340692744, + message="SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", + ) + request_uris_to_exclude: MutableSequence[ + "SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams" + ] = proto.RepeatedField( + proto.MESSAGE, + number=90690846, + message="SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams", + ) + target_rule_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=498430435, + ) + target_rule_set: str = proto.Field( + proto.STRING, + number=498440077, + optional=True, + ) + + +class SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + op (str): + The match operator for the field. + Check the Op enum for the list of possible + values. + + This field is a member of `oneof`_ ``_op``. + val (str): + The value of the field. + + This field is a member of `oneof`_ ``_val``. + """ + + class Op(proto.Enum): + r"""The match operator for the field. + + Values: + UNDEFINED_OP (0): + A value indicating that the enum field is not + set. + CONTAINS (215180831): + The operator matches if the field value + contains the specified value. + ENDS_WITH (490402221): + The operator matches if the field value ends + with the specified value. + EQUALS (442201023): + The operator matches if the field value + equals the specified value. + EQUALS_ANY (337226060): + The operator matches if the field value is + any value. + STARTS_WITH (139505652): + The operator matches if the field value + starts with the specified value. + """ + UNDEFINED_OP = 0 + CONTAINS = 215180831 + ENDS_WITH = 490402221 + EQUALS = 442201023 + EQUALS_ANY = 337226060 + STARTS_WITH = 139505652 + + op: str = proto.Field( + proto.STRING, + number=3553, + optional=True, + ) + val: str = proto.Field( + proto.STRING, + number=116513, + optional=True, + ) + + class SecurityPolicyRuleRateLimitOptions(proto.Message): r""" @@ -78855,14 +79724,13 @@ class SecurityPolicyRuleRateLimitOptions(proto.Message): This field is a member of `oneof`_ ``_enforce_on_key_name``. exceed_action (str): - Action to take for requests that are above - the configured rate limit threshold, to either - deny with a specified HTTP response code, or - redirect to a different endpoint. Valid options - are "deny(status)", where valid values for - status are 403, 404, 429, and 502, and - "redirect" where the redirect parameters come - from exceedRedirectOptions below. + Action to take for requests that are above the configured + rate limit threshold, to either deny with a specified HTTP + response code, or redirect to a different endpoint. Valid + options are ``deny(STATUS)``, where valid values for + ``STATUS`` are 403, 404, 429, and 502, and ``redirect``, + where the redirect parameters come from + ``exceedRedirectOptions`` below. This field is a member of `oneof`_ ``_exceed_action``. exceed_redirect_options (google.cloud.compute_v1.types.SecurityPolicyRuleRedirectOptions): @@ -81801,8 +82669,68 @@ class SetLabelsTargetVpnGatewayRequest(proto.Message): ) -class SetLabelsVpnGatewayRequest(proto.Message): - r"""A request message for VpnGateways.SetLabels. See the method +class SetLabelsVpnGatewayRequest(proto.Message): + r"""A request message for VpnGateways.SetLabels. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + region (str): + The region for this request. + region_set_labels_request_resource (google.cloud.compute_v1.types.RegionSetLabelsRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + resource (str): + Name or id of the resource for this request. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_set_labels_request_resource: "RegionSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=259357782, + message="RegionSetLabelsRequest", + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetLabelsVpnTunnelRequest(proto.Message): + r"""A request message for VpnTunnels.SetLabels. See the method description for details. @@ -81861,20 +82789,20 @@ class SetLabelsVpnGatewayRequest(proto.Message): ) -class SetLabelsVpnTunnelRequest(proto.Message): - r"""A request message for VpnTunnels.SetLabels. See the method - description for details. +class SetMachineResourcesInstanceRequest(proto.Message): + r"""A request message for Instances.SetMachineResources. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + instance (str): + Name of the instance scoping this request. + instances_set_machine_resources_request_resource (google.cloud.compute_v1.types.InstancesSetMachineResourcesRequest): + The body resource for this request project (str): Project ID for this request. - region (str): - The region for this request. - region_set_labels_request_resource (google.cloud.compute_v1.types.RegionSetLabelsRequest): - The body resource for this request request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -81893,36 +82821,36 @@ class SetLabelsVpnTunnelRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - resource (str): - Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( + instance: str = proto.Field( proto.STRING, - number=138946292, + number=18257045, ) - region_set_labels_request_resource: "RegionSetLabelsRequest" = proto.Field( + instances_set_machine_resources_request_resource: "InstancesSetMachineResourcesRequest" = proto.Field( proto.MESSAGE, - number=259357782, - message="RegionSetLabelsRequest", + number=196286318, + message="InstancesSetMachineResourcesRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - resource: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=195806222, + number=3744684, ) -class SetMachineResourcesInstanceRequest(proto.Message): - r"""A request message for Instances.SetMachineResources. See the +class SetMachineTypeInstanceRequest(proto.Message): + r"""A request message for Instances.SetMachineType. See the method description for details. @@ -81931,7 +82859,7 @@ class SetMachineResourcesInstanceRequest(proto.Message): Attributes: instance (str): Name of the instance scoping this request. - instances_set_machine_resources_request_resource (google.cloud.compute_v1.types.InstancesSetMachineResourcesRequest): + instances_set_machine_type_request_resource (google.cloud.compute_v1.types.InstancesSetMachineTypeRequest): The body resource for this request project (str): Project ID for this request. @@ -81961,10 +82889,12 @@ class SetMachineResourcesInstanceRequest(proto.Message): proto.STRING, number=18257045, ) - instances_set_machine_resources_request_resource: "InstancesSetMachineResourcesRequest" = proto.Field( - proto.MESSAGE, - number=196286318, - message="InstancesSetMachineResourcesRequest", + instances_set_machine_type_request_resource: "InstancesSetMachineTypeRequest" = ( + proto.Field( + proto.MESSAGE, + number=254157709, + message="InstancesSetMachineTypeRequest", + ) ) project: str = proto.Field( proto.STRING, @@ -81981,9 +82911,9 @@ class SetMachineResourcesInstanceRequest(proto.Message): ) -class SetMachineTypeInstanceRequest(proto.Message): - r"""A request message for Instances.SetMachineType. See the - method description for details. +class SetMetadataInstanceRequest(proto.Message): + r"""A request message for Instances.SetMetadata. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -81991,7 +82921,7 @@ class SetMachineTypeInstanceRequest(proto.Message): Attributes: instance (str): Name of the instance scoping this request. - instances_set_machine_type_request_resource (google.cloud.compute_v1.types.InstancesSetMachineTypeRequest): + metadata_resource (google.cloud.compute_v1.types.Metadata): The body resource for this request project (str): Project ID for this request. @@ -82021,12 +82951,10 @@ class SetMachineTypeInstanceRequest(proto.Message): proto.STRING, number=18257045, ) - instances_set_machine_type_request_resource: "InstancesSetMachineTypeRequest" = ( - proto.Field( - proto.MESSAGE, - number=254157709, - message="InstancesSetMachineTypeRequest", - ) + metadata_resource: "Metadata" = proto.Field( + proto.MESSAGE, + number=291086110, + message="Metadata", ) project: str = proto.Field( proto.STRING, @@ -82043,9 +82971,9 @@ class SetMachineTypeInstanceRequest(proto.Message): ) -class SetMetadataInstanceRequest(proto.Message): - r"""A request message for Instances.SetMetadata. See the method - description for details. +class SetMinCpuPlatformInstanceRequest(proto.Message): + r"""A request message for Instances.SetMinCpuPlatform. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82053,7 +82981,7 @@ class SetMetadataInstanceRequest(proto.Message): Attributes: instance (str): Name of the instance scoping this request. - metadata_resource (google.cloud.compute_v1.types.Metadata): + instances_set_min_cpu_platform_request_resource (google.cloud.compute_v1.types.InstancesSetMinCpuPlatformRequest): The body resource for this request project (str): Project ID for this request. @@ -82083,10 +83011,10 @@ class SetMetadataInstanceRequest(proto.Message): proto.STRING, number=18257045, ) - metadata_resource: "Metadata" = proto.Field( + instances_set_min_cpu_platform_request_resource: "InstancesSetMinCpuPlatformRequest" = proto.Field( proto.MESSAGE, - number=291086110, - message="Metadata", + number=148459368, + message="InstancesSetMinCpuPlatformRequest", ) project: str = proto.Field( proto.STRING, @@ -82103,17 +83031,17 @@ class SetMetadataInstanceRequest(proto.Message): ) -class SetMinCpuPlatformInstanceRequest(proto.Message): - r"""A request message for Instances.SetMinCpuPlatform. See the - method description for details. +class SetNameInstanceRequest(proto.Message): + r"""A request message for Instances.SetName. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: instance (str): - Name of the instance scoping this request. - instances_set_min_cpu_platform_request_resource (google.cloud.compute_v1.types.InstancesSetMinCpuPlatformRequest): + The instance name for this request. + instances_set_name_request_resource (google.cloud.compute_v1.types.InstancesSetNameRequest): The body resource for this request project (str): Project ID for this request. @@ -82143,10 +83071,10 @@ class SetMinCpuPlatformInstanceRequest(proto.Message): proto.STRING, number=18257045, ) - instances_set_min_cpu_platform_request_resource: "InstancesSetMinCpuPlatformRequest" = proto.Field( + instances_set_name_request_resource: "InstancesSetNameRequest" = proto.Field( proto.MESSAGE, - number=148459368, - message="InstancesSetMinCpuPlatformRequest", + number=272080980, + message="InstancesSetNameRequest", ) project: str = proto.Field( proto.STRING, @@ -91256,6 +92184,84 @@ class UpdateBackendServiceRequest(proto.Message): ) +class UpdateDiskRequest(proto.Message): + r"""A request message for Disks.Update. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk (str): + The disk name for this request. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + paths (str): + + This field is a member of `oneof`_ ``_paths``. + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + update_mask (str): + update_mask indicates fields to be updated as part of this + request. + + This field is a member of `oneof`_ ``_update_mask``. + zone (str): + The name of the zone for this request. + """ + + disk: str = proto.Field( + proto.STRING, + number=3083677, + ) + disk_resource: "Disk" = proto.Field( + proto.MESSAGE, + number=25880688, + message="Disk", + ) + paths: str = proto.Field( + proto.STRING, + number=106438894, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + update_mask: str = proto.Field( + proto.STRING, + number=500079778, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class UpdateDisplayDeviceInstanceRequest(proto.Message): r"""A request message for Instances.UpdateDisplayDevice. See the method description for details. @@ -91998,6 +93004,84 @@ class UpdateRegionCommitmentRequest(proto.Message): ) +class UpdateRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.Update. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk (str): + The disk name for this request. + disk_resource (google.cloud.compute_v1.types.Disk): + The body resource for this request + paths (str): + + This field is a member of `oneof`_ ``_paths``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + update_mask (str): + update_mask indicates fields to be updated as part of this + request. + + This field is a member of `oneof`_ ``_update_mask``. + """ + + disk: str = proto.Field( + proto.STRING, + number=3083677, + ) + disk_resource: "Disk" = proto.Field( + proto.MESSAGE, + number=25880688, + message="Disk", + ) + paths: str = proto.Field( + proto.STRING, + number=106438894, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + update_mask: str = proto.Field( + proto.STRING, + number=500079778, + optional=True, + ) + + class UpdateRegionHealthCheckRequest(proto.Message): r"""A request message for RegionHealthChecks.Update. See the method description for details. @@ -93822,7 +94906,7 @@ class VpnGateway(proto.Message): or change labels, otherwise the request will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request to - retrieve an VpnGateway. + retrieve a VpnGateway. This field is a member of `oneof`_ ``_label_fingerprint``. labels (MutableMapping[str, str]): @@ -94996,6 +96080,13 @@ class WafExpressionSetExpression(proto.Message): false positive. required This field is a member of `oneof`_ ``_id``. + sensitivity (int): + The sensitivity value associated with the WAF + rule ID. This corresponds to the ModSecurity + paranoia level, ranging from 1 to 4. 0 is + reserved for opt-in only rules. + + This field is a member of `oneof`_ ``_sensitivity``. """ id: str = proto.Field( @@ -95003,6 +96094,11 @@ class WafExpressionSetExpression(proto.Message): number=3355, optional=True, ) + sensitivity: int = proto.Field( + proto.INT32, + number=27532959, + optional=True, + ) class WaitGlobalOperationRequest(proto.Message): diff --git a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py index 3306de99734c..4c3953150889 100644 --- a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py +++ b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py @@ -139,6 +139,7 @@ class computeCallTransformer(cst.CSTTransformer): 'set_machine_type': ('instance', 'instances_set_machine_type_request_resource', 'project', 'zone', 'request_id', ), 'set_metadata': ('instance', 'metadata_resource', 'project', 'zone', 'request_id', ), 'set_min_cpu_platform': ('instance', 'instances_set_min_cpu_platform_request_resource', 'project', 'zone', 'request_id', ), + 'set_name': ('instance', 'instances_set_name_request_resource', 'project', 'zone', 'request_id', ), 'set_named_ports': ('instance_group', 'instance_groups_set_named_ports_request_resource', 'project', 'zone', 'request_id', ), 'set_node_template': ('node_group', 'node_groups_set_node_template_request_resource', 'project', 'zone', 'request_id', ), 'set_private_ip_google_access': ('project', 'region', 'subnetwork', 'subnetworks_set_private_ip_google_access_request_resource', 'request_id', ), 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 be68034378e0..56cf309d1315 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 @@ -3927,7 +3927,12 @@ def test_insert_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4302,7 +4307,12 @@ def test_insert_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4548,7 +4558,12 @@ def test_insert_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4903,7 +4918,12 @@ def test_insert_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -5497,7 +5517,12 @@ def test_patch_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -5877,7 +5902,12 @@ def test_patch_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -6125,7 +6155,12 @@ def test_patch_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -6485,7 +6520,12 @@ def test_patch_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -8489,7 +8529,12 @@ def test_update_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -8869,7 +8914,12 @@ def test_update_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -9117,7 +9167,12 @@ def test_update_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -9477,7 +9532,12 @@ def test_update_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py index a0e6bae72986..62e945bbfff2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_disks.py @@ -7554,6 +7554,850 @@ def test_test_iam_permissions_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + compute.UpdateDiskRequest, + dict, + ], +) +def test_update_rest(request_type): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_update_rest_required_fields(request_type=compute.UpdateDiskRequest): + transport_class = transports.DisksRestTransport + + request_init = {} + request_init["disk"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["disk"] = "disk_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "paths", + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "disk" in jsonified_request + assert jsonified_request["disk"] == "disk_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_rest_unset_required_fields(): + transport = transports.DisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "paths", + "requestId", + "updateMask", + ) + ) + & set( + ( + "disk", + "diskResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_rest_interceptors(null_interceptor): + transport = transports.DisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DisksRestInterceptor(), + ) + client = DisksClient(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.DisksRestInterceptor, "post_update" + ) as post, mock.patch.object( + transports.DisksRestInterceptor, "pre_update" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.UpdateDiskRequest.pb(compute.UpdateDiskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.UpdateDiskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.update( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_rest_bad_request( + transport: str = "rest", request_type=compute.UpdateDiskRequest +): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update(request) + + +def test_update_rest_flattened(): + client = DisksClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update(**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/v1/projects/{project}/zones/{zone}/disks/{disk}" + % client.transport._host, + args[1], + ) + + +def test_update_rest_flattened_error(transport: str = "rest"): + client = DisksClient( + 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( + compute.UpdateDiskRequest(), + project="project_value", + zone="zone_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + + +def test_update_rest_error(): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.UpdateDiskRequest, + dict, + ], +) +def test_update_unary_rest(request_type): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_update_unary_rest_required_fields(request_type=compute.UpdateDiskRequest): + transport_class = transports.DisksRestTransport + + request_init = {} + request_init["disk"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["disk"] = "disk_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "paths", + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "disk" in jsonified_request + assert jsonified_request["disk"] == "disk_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_unary_rest_unset_required_fields(): + transport = transports.DisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "paths", + "requestId", + "updateMask", + ) + ) + & set( + ( + "disk", + "diskResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_unary_rest_interceptors(null_interceptor): + transport = transports.DisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DisksRestInterceptor(), + ) + client = DisksClient(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.DisksRestInterceptor, "post_update" + ) as post, mock.patch.object( + transports.DisksRestInterceptor, "pre_update" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.UpdateDiskRequest.pb(compute.UpdateDiskRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.UpdateDiskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.update_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_unary_rest_bad_request( + transport: str = "rest", request_type=compute.UpdateDiskRequest +): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_unary(request) + + +def test_update_unary_rest_flattened(): + client = DisksClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "zone": "sample2", "disk": "sample3"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_unary(**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/v1/projects/{project}/zones/{zone}/disks/{disk}" + % client.transport._host, + args[1], + ) + + +def test_update_unary_rest_flattened_error(transport: str = "rest"): + client = DisksClient( + 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_unary( + compute.UpdateDiskRequest(), + project="project_value", + zone="zone_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + + +def test_update_unary_rest_error(): + client = DisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DisksRestTransport( @@ -7677,6 +8521,7 @@ def test_disks_base_transport(): "set_iam_policy", "set_labels", "test_iam_permissions", + "update", ) for method in methods: with pytest.raises(NotImplementedError): @@ -7853,6 +8698,9 @@ def test_disks_client_transport_session_collision(transport_name): session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 + session1 = client1.transport.update._session + session2 = client2.transport.update._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py index fd7acb244718..53eb744cf17e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py @@ -1632,6 +1632,7 @@ def test_get_rest(request_type): all_ports=True, allow_global_access=True, backend_service="backend_service_value", + base_forwarding_rule="base_forwarding_rule_value", creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", @@ -1653,6 +1654,7 @@ def test_get_rest(request_type): self_link="self_link_value", service_label="service_label_value", service_name="service_name_value", + source_ip_ranges=["source_ip_ranges_value"], subnetwork="subnetwork_value", target="target_value", ) @@ -1674,6 +1676,7 @@ def test_get_rest(request_type): assert response.all_ports is True assert response.allow_global_access is True assert response.backend_service == "backend_service_value" + assert response.base_forwarding_rule == "base_forwarding_rule_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" @@ -1695,6 +1698,7 @@ def test_get_rest(request_type): assert response.self_link == "self_link_value" assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" + assert response.source_ip_ranges == ["source_ip_ranges_value"] assert response.subnetwork == "subnetwork_value" assert response.target == "target_value" @@ -1976,6 +1980,7 @@ def test_insert_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2011,6 +2016,7 @@ def test_insert_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2251,6 +2257,7 @@ def test_insert_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2286,6 +2293,7 @@ def test_insert_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2394,6 +2402,7 @@ def test_insert_unary_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2429,6 +2438,7 @@ def test_insert_unary_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2649,6 +2659,7 @@ def test_insert_unary_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2684,6 +2695,7 @@ def test_insert_unary_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3155,6 +3167,7 @@ def test_patch_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3190,6 +3203,7 @@ def test_patch_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3439,6 +3453,7 @@ def test_patch_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3474,6 +3489,7 @@ def test_patch_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3592,6 +3608,7 @@ def test_patch_unary_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3627,6 +3644,7 @@ def test_patch_unary_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3856,6 +3874,7 @@ def test_patch_unary_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3891,6 +3910,7 @@ def test_patch_unary_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py index 838e9eb4ca27..4d73ca721d37 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py @@ -1238,6 +1238,7 @@ def test_get_rest(request_type): all_ports=True, allow_global_access=True, backend_service="backend_service_value", + base_forwarding_rule="base_forwarding_rule_value", creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", @@ -1259,6 +1260,7 @@ def test_get_rest(request_type): self_link="self_link_value", service_label="service_label_value", service_name="service_name_value", + source_ip_ranges=["source_ip_ranges_value"], subnetwork="subnetwork_value", target="target_value", ) @@ -1280,6 +1282,7 @@ def test_get_rest(request_type): assert response.all_ports is True assert response.allow_global_access is True assert response.backend_service == "backend_service_value" + assert response.base_forwarding_rule == "base_forwarding_rule_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" @@ -1301,6 +1304,7 @@ def test_get_rest(request_type): assert response.self_link == "self_link_value" assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" + assert response.source_ip_ranges == ["source_ip_ranges_value"] assert response.subnetwork == "subnetwork_value" assert response.target == "target_value" @@ -1567,6 +1571,7 @@ def test_insert_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -1602,6 +1607,7 @@ def test_insert_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -1839,6 +1845,7 @@ def test_insert_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -1874,6 +1881,7 @@ def test_insert_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -1980,6 +1988,7 @@ def test_insert_unary_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2015,6 +2024,7 @@ def test_insert_unary_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2230,6 +2240,7 @@ def test_insert_unary_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2265,6 +2276,7 @@ def test_insert_unary_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2721,6 +2733,7 @@ def test_patch_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -2756,6 +2769,7 @@ def test_patch_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -2998,6 +3012,7 @@ def test_patch_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3033,6 +3048,7 @@ def test_patch_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3141,6 +3157,7 @@ def test_patch_unary_rest(request_type): "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3176,6 +3193,7 @@ def test_patch_unary_rest(request_type): ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } @@ -3396,6 +3414,7 @@ def test_patch_unary_rest_bad_request( "all_ports": True, "allow_global_access": True, "backend_service": "backend_service_value", + "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", @@ -3431,6 +3450,7 @@ def test_patch_unary_rest_bad_request( ], "service_label": "service_label_value", "service_name": "service_name_value", + "source_ip_ranges": ["source_ip_ranges_value1", "source_ip_ranges_value2"], "subnetwork": "subnetwork_value", "target": "target_value", } diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index 65d28db13133..ca4e308b5640 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -578,6 +578,372 @@ def test_instance_templates_client_client_options_credentials_file( ) +@pytest.mark.parametrize( + "request_type", + [ + compute.AggregatedListInstanceTemplatesRequest, + dict, + ], +) +def test_aggregated_list_rest(request_type): + client = InstanceTemplatesClient( + 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.InstanceTemplateAggregatedList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.InstanceTemplateAggregatedList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.aggregated_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregatedListPager) + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +def test_aggregated_list_rest_required_fields( + request_type=compute.AggregatedListInstanceTemplatesRequest, +): + transport_class = transports.InstanceTemplatesRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregated_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() + ).aggregated_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", + "include_all_scopes", + "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 = InstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstanceTemplateAggregatedList() + # 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 + + pb_return_value = compute.InstanceTemplateAggregatedList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.aggregated_list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_aggregated_list_rest_unset_required_fields(): + transport = transports.InstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.aggregated_list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "includeAllScopes", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregated_list_rest_interceptors(null_interceptor): + transport = transports.InstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstanceTemplatesRestInterceptor(), + ) + client = InstanceTemplatesClient(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.InstanceTemplatesRestInterceptor, "post_aggregated_list" + ) as post, mock.patch.object( + transports.InstanceTemplatesRestInterceptor, "pre_aggregated_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.AggregatedListInstanceTemplatesRequest.pb( + compute.AggregatedListInstanceTemplatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstanceTemplateAggregatedList.to_json( + compute.InstanceTemplateAggregatedList() + ) + + request = compute.AggregatedListInstanceTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstanceTemplateAggregatedList() + + client.aggregated_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_aggregated_list_rest_bad_request( + transport: str = "rest", request_type=compute.AggregatedListInstanceTemplatesRequest +): + client = InstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.aggregated_list(request) + + +def test_aggregated_list_rest_flattened(): + client = InstanceTemplatesClient( + 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.InstanceTemplateAggregatedList() + + # 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 + pb_return_value = compute.InstanceTemplateAggregatedList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.aggregated_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/v1/projects/{project}/aggregated/instanceTemplates" + % client.transport._host, + args[1], + ) + + +def test_aggregated_list_rest_flattened_error(transport: str = "rest"): + client = InstanceTemplatesClient( + 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.aggregated_list( + compute.AggregatedListInstanceTemplatesRequest(), + project="project_value", + ) + + +def test_aggregated_list_rest_pager(transport: str = "rest"): + client = InstanceTemplatesClient( + 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.InstanceTemplateAggregatedList( + items={ + "a": compute.InstanceTemplatesScopedList(), + "b": compute.InstanceTemplatesScopedList(), + "c": compute.InstanceTemplatesScopedList(), + }, + next_page_token="abc", + ), + compute.InstanceTemplateAggregatedList( + items={}, + next_page_token="def", + ), + compute.InstanceTemplateAggregatedList( + items={ + "g": compute.InstanceTemplatesScopedList(), + }, + next_page_token="ghi", + ), + compute.InstanceTemplateAggregatedList( + items={ + "h": compute.InstanceTemplatesScopedList(), + "i": compute.InstanceTemplatesScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.InstanceTemplateAggregatedList.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.aggregated_list(request=sample_request) + + assert isinstance(pager.get("a"), compute.InstanceTemplatesScopedList) + assert pager.get("h") is None + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tuple) for i in results) + for result in results: + assert isinstance(result, tuple) + assert tuple(type(t) for t in result) == ( + str, + compute.InstanceTemplatesScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.InstanceTemplatesScopedList) + + pages = list(client.aggregated_list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + @pytest.mark.parametrize( "request_type", [ @@ -1230,6 +1596,7 @@ def test_get_rest(request_type): id=205, kind="kind_value", name="name_value", + region="region_value", self_link="self_link_value", source_instance="source_instance_value", ) @@ -1251,6 +1618,7 @@ def test_get_rest(request_type): assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" + assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.source_instance == "source_instance_value" @@ -1961,6 +2329,7 @@ def test_insert_rest(request_type): "items": ["items_value1", "items_value2"], }, }, + "region": "region_value", "self_link": "self_link_value", "source_instance": "source_instance_value", "source_instance_params": { @@ -2366,6 +2735,7 @@ def test_insert_rest_bad_request( "items": ["items_value1", "items_value2"], }, }, + "region": "region_value", "self_link": "self_link_value", "source_instance": "source_instance_value", "source_instance_params": { @@ -2640,6 +3010,7 @@ def test_insert_unary_rest(request_type): "items": ["items_value1", "items_value2"], }, }, + "region": "region_value", "self_link": "self_link_value", "source_instance": "source_instance_value", "source_instance_params": { @@ -3023,6 +3394,7 @@ def test_insert_unary_rest_bad_request( "items": ["items_value1", "items_value2"], }, }, + "region": "region_value", "self_link": "self_link_value", "source_instance": "source_instance_value", "source_instance_params": { @@ -4319,6 +4691,7 @@ def test_instance_templates_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "aggregated_list", "delete", "get", "get_iam_policy", @@ -4463,6 +4836,9 @@ def test_instance_templates_client_transport_session_collision(transport_name): credentials=creds2, transport=transport_name, ) + session1 = client1.transport.aggregated_list._session + session2 = client2.transport.aggregated_list._session + assert session1 != session2 session1 = client1.transport.delete._session session2 = client2.transport.delete._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index bd49d8ee9254..775aafc75fa1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -18260,6 +18260,676 @@ def test_set_min_cpu_platform_unary_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + compute.SetNameInstanceRequest, + dict, + ], +) +def test_set_name_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request_init["instances_set_name_request_resource"] = { + "current_name": "current_name_value", + "name": "name_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_name(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_set_name_rest_required_fields(request_type=compute.SetNameInstanceRequest): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_name._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_name._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_name(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_name_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_name._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instance", + "instancesSetNameRequestResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_name_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(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.InstancesRestInterceptor, "post_set_name" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "pre_set_name" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetNameInstanceRequest.pb(compute.SetNameInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetNameInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_name( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_name_rest_bad_request( + transport: str = "rest", request_type=compute.SetNameInstanceRequest +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request_init["instances_set_name_request_resource"] = { + "current_name": "current_name_value", + "name": "name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_name(request) + + +def test_set_name_rest_flattened(): + client = InstancesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instance": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instance="instance_value", + instances_set_name_request_resource=compute.InstancesSetNameRequest( + current_name="current_name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_name(**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/v1/projects/{project}/zones/{zone}/instances/{instance}/setName" + % client.transport._host, + args[1], + ) + + +def test_set_name_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + 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.set_name( + compute.SetNameInstanceRequest(), + project="project_value", + zone="zone_value", + instance="instance_value", + instances_set_name_request_resource=compute.InstancesSetNameRequest( + current_name="current_name_value" + ), + ) + + +def test_set_name_rest_error(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetNameInstanceRequest, + dict, + ], +) +def test_set_name_unary_rest(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request_init["instances_set_name_request_resource"] = { + "current_name": "current_name_value", + "name": "name_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_name_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_set_name_unary_rest_required_fields( + request_type=compute.SetNameInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_name._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_name._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_name_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_name_unary_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_name._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instance", + "instancesSetNameRequestResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_name_unary_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(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.InstancesRestInterceptor, "post_set_name" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "pre_set_name" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetNameInstanceRequest.pb(compute.SetNameInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetNameInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_name_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_name_unary_rest_bad_request( + transport: str = "rest", request_type=compute.SetNameInstanceRequest +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request_init["instances_set_name_request_resource"] = { + "current_name": "current_name_value", + "name": "name_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_name_unary(request) + + +def test_set_name_unary_rest_flattened(): + client = InstancesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instance": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instance="instance_value", + instances_set_name_request_resource=compute.InstancesSetNameRequest( + current_name="current_name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_name_unary(**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/v1/projects/{project}/zones/{zone}/instances/{instance}/setName" + % client.transport._host, + args[1], + ) + + +def test_set_name_unary_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + 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.set_name_unary( + compute.SetNameInstanceRequest(), + project="project_value", + zone="zone_value", + instance="instance_value", + instances_set_name_request_resource=compute.InstancesSetNameRequest( + current_name="current_name_value" + ), + ) + + +def test_set_name_unary_rest_error(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + @pytest.mark.parametrize( "request_type", [ @@ -29127,6 +29797,7 @@ def test_instances_base_transport(): "set_machine_type", "set_metadata", "set_min_cpu_platform", + "set_name", "set_scheduling", "set_service_account", "set_shielded_instance_integrity_policy", @@ -29369,6 +30040,9 @@ def test_instances_client_transport_session_collision(transport_name): session1 = client1.transport.set_min_cpu_platform._session session2 = client2.transport.set_min_cpu_platform._session assert session1 != session2 + session1 = client1.transport.set_name._session + session2 = client2.transport.set_name._session + assert session1 != session2 session1 = client1.transport.set_scheduling._session session2 = client2.transport.set_scheduling._session assert session1 != session2 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 b29ecf2fb4f7..199572351a20 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 @@ -2335,7 +2335,12 @@ def test_insert_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -2717,7 +2722,12 @@ def test_insert_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -2965,7 +2975,12 @@ def test_insert_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -3325,7 +3340,12 @@ def test_insert_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -3938,7 +3958,12 @@ def test_patch_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4329,7 +4354,12 @@ def test_patch_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4587,7 +4617,12 @@ def test_patch_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -4956,7 +4991,12 @@ def test_patch_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -5672,7 +5712,12 @@ def test_update_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -6063,7 +6108,12 @@ def test_update_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -6321,7 +6371,12 @@ def test_update_unary_rest(request_type): } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", @@ -6690,7 +6745,12 @@ def test_update_unary_rest_bad_request( } ], "locality_lb_policy": "locality_lb_policy_value", - "log_config": {"enable": True, "sample_rate": 0.1165}, + "log_config": { + "enable": True, + "optional_fields": ["optional_fields_value1", "optional_fields_value2"], + "optional_mode": "optional_mode_value", + "sample_rate": 0.1165, + }, "max_stream_duration": {}, "name": "name_value", "network": "network_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py index b651953e47e8..d2b324b82a1e 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_disks.py @@ -7256,6 +7256,860 @@ def test_test_iam_permissions_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + compute.UpdateRegionDiskRequest, + dict, + ], +) +def test_update_rest(request_type): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_update_rest_required_fields(request_type=compute.UpdateRegionDiskRequest): + transport_class = transports.RegionDisksRestTransport + + request_init = {} + request_init["disk"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["disk"] = "disk_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "paths", + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "disk" in jsonified_request + assert jsonified_request["disk"] == "disk_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_rest_unset_required_fields(): + transport = transports.RegionDisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "paths", + "requestId", + "updateMask", + ) + ) + & set( + ( + "disk", + "diskResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_rest_interceptors(null_interceptor): + transport = transports.RegionDisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionDisksRestInterceptor(), + ) + client = RegionDisksClient(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.RegionDisksRestInterceptor, "post_update" + ) as post, mock.patch.object( + transports.RegionDisksRestInterceptor, "pre_update" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.UpdateRegionDiskRequest.pb( + compute.UpdateRegionDiskRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.UpdateRegionDiskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.update( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_rest_bad_request( + transport: str = "rest", request_type=compute.UpdateRegionDiskRequest +): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update(request) + + +def test_update_rest_flattened(): + client = RegionDisksClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2", "disk": "sample3"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update(**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/v1/projects/{project}/regions/{region}/disks/{disk}" + % client.transport._host, + args[1], + ) + + +def test_update_rest_flattened_error(transport: str = "rest"): + client = RegionDisksClient( + 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( + compute.UpdateRegionDiskRequest(), + project="project_value", + region="region_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + + +def test_update_rest_error(): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.UpdateRegionDiskRequest, + dict, + ], +) +def test_update_unary_rest(request_type): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_update_unary_rest_required_fields( + request_type=compute.UpdateRegionDiskRequest, +): + transport_class = transports.RegionDisksRestTransport + + request_init = {} + request_init["disk"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["disk"] = "disk_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "paths", + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "disk" in jsonified_request + assert jsonified_request["disk"] == "disk_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_unary_rest_unset_required_fields(): + transport = transports.RegionDisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "paths", + "requestId", + "updateMask", + ) + ) + & set( + ( + "disk", + "diskResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_unary_rest_interceptors(null_interceptor): + transport = transports.RegionDisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionDisksRestInterceptor(), + ) + client = RegionDisksClient(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.RegionDisksRestInterceptor, "post_update" + ) as post, mock.patch.object( + transports.RegionDisksRestInterceptor, "pre_update" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.UpdateRegionDiskRequest.pb( + compute.UpdateRegionDiskRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.UpdateRegionDiskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.update_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_unary_rest_bad_request( + transport: str = "rest", request_type=compute.UpdateRegionDiskRequest +): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "disk": "sample3"} + request_init["disk_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "guest_os_features": [{"type_": "type__value"}], + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "last_attach_timestamp": "last_attach_timestamp_value", + "last_detach_timestamp": "last_detach_timestamp_value", + "license_codes": [1361, 1362], + "licenses": ["licenses_value1", "licenses_value2"], + "location_hint": "location_hint_value", + "name": "name_value", + "options": "options_value", + "params": {"resource_manager_tags": {}}, + "physical_block_size_bytes": 2663, + "provisioned_iops": 1740, + "region": "region_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "resource_policies": ["resource_policies_value1", "resource_policies_value2"], + "satisfies_pzs": True, + "self_link": "self_link_value", + "size_gb": 739, + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_image_id": "source_image_id_value", + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + "source_snapshot_id": "source_snapshot_id_value", + "source_storage_object": "source_storage_object_value", + "status": "status_value", + "type_": "type__value", + "users": ["users_value1", "users_value2"], + "zone": "zone_value", + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_unary(request) + + +def test_update_unary_rest_flattened(): + client = RegionDisksClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2", "disk": "sample3"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_unary(**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/v1/projects/{project}/regions/{region}/disks/{disk}" + % client.transport._host, + args[1], + ) + + +def test_update_unary_rest_flattened_error(transport: str = "rest"): + client = RegionDisksClient( + 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_unary( + compute.UpdateRegionDiskRequest(), + project="project_value", + region="region_value", + disk="disk_value", + disk_resource=compute.Disk(architecture="architecture_value"), + ) + + +def test_update_unary_rest_error(): + client = RegionDisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.RegionDisksRestTransport( @@ -7378,6 +8232,7 @@ def test_region_disks_base_transport(): "set_iam_policy", "set_labels", "test_iam_permissions", + "update", ) for method in methods: with pytest.raises(NotImplementedError): @@ -7551,6 +8406,9 @@ def test_region_disks_client_transport_session_collision(transport_name): session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 + session1 = client1.transport.update._session + session2 = client2.transport.update._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py new file mode 100644 index 000000000000..1e28ae8e10fd --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py @@ -0,0 +1,3739 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.compute_v1.services.region_instance_templates import ( + RegionInstanceTemplatesClient, + pagers, + transports, +) +from google.cloud.compute_v1.types import compute + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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 + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegionInstanceTemplatesClient._get_default_mtls_endpoint(None) is None + assert ( + RegionInstanceTemplatesClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstanceTemplatesClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstanceTemplatesClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstanceTemplatesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstanceTemplatesClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionInstanceTemplatesClient, "rest"), + ], +) +def test_region_instance_templates_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.RegionInstanceTemplatesRestTransport, "rest"), + ], +) +def test_region_instance_templates_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", + [ + (RegionInstanceTemplatesClient, "rest"), + ], +) +def test_region_instance_templates_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_region_instance_templates_client_get_transport_class(): + transport = RegionInstanceTemplatesClient.get_transport_class() + available_transports = [ + transports.RegionInstanceTemplatesRestTransport, + ] + assert transport in available_transports + + transport = RegionInstanceTemplatesClient.get_transport_class("rest") + assert transport == transports.RegionInstanceTemplatesRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionInstanceTemplatesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstanceTemplatesClient), +) +def test_region_instance_templates_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(RegionInstanceTemplatesClient, "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(RegionInstanceTemplatesClient, "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, + 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): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # 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, + 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, + 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", + [ + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + "rest", + "true", + ), + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionInstanceTemplatesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstanceTemplatesClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_instance_templates_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 + 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 + 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, + 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", [RegionInstanceTemplatesClient]) +@mock.patch.object( + RegionInstanceTemplatesClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstanceTemplatesClient), +) +def test_region_instance_templates_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_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 + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + "rest", + ), + ], +) +def test_region_instance_templates_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, + 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", + [ + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + "rest", + None, + ), + ], +) +def test_region_instance_templates_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, + 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( + "request_type", + [ + compute.DeleteRegionInstanceTemplateRequest, + dict, + ], +) +def test_delete_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_delete_rest_required_fields( + request_type=compute.DeleteRegionInstanceTemplateRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["instance_template"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instanceTemplate"] = "instance_template_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instanceTemplate" in jsonified_request + assert jsonified_request["instanceTemplate"] == "instance_template_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instanceTemplate", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteRegionInstanceTemplateRequest.pb( + compute.DeleteRegionInstanceTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteRegionInstanceTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteRegionInstanceTemplateRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete(request) + + +def test_delete_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instance_template": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete(**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/v1/projects/{project}/regions/{region}/instanceTemplates/{instance_template}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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( + compute.DeleteRegionInstanceTemplateRequest(), + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + + +def test_delete_rest_error(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRegionInstanceTemplateRequest, + dict, + ], +) +def test_delete_unary_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_delete_unary_rest_required_fields( + request_type=compute.DeleteRegionInstanceTemplateRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["instance_template"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instanceTemplate"] = "instance_template_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instanceTemplate" in jsonified_request + assert jsonified_request["instanceTemplate"] == "instance_template_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instanceTemplate", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_unary_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteRegionInstanceTemplateRequest.pb( + compute.DeleteRegionInstanceTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteRegionInstanceTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_unary_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteRegionInstanceTemplateRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_unary(request) + + +def test_delete_unary_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instance_template": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_unary(**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/v1/projects/{project}/regions/{region}/instanceTemplates/{instance_template}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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_unary( + compute.DeleteRegionInstanceTemplateRequest(), + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + + +def test_delete_unary_rest_error(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRegionInstanceTemplateRequest, + dict, + ], +) +def test_get_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = compute.InstanceTemplate( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + region="region_value", + self_link="self_link_value", + source_instance="source_instance_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.InstanceTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.InstanceTemplate) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.source_instance == "source_instance_value" + + +def test_get_rest_required_fields( + request_type=compute.GetRegionInstanceTemplateRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["instance_template"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + 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["instanceTemplate"] = "instance_template_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "instanceTemplate" in jsonified_request + assert jsonified_request["instanceTemplate"] == "instance_template_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstanceTemplate() + # 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 + + pb_return_value = compute.InstanceTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instanceTemplate", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.GetRegionInstanceTemplateRequest.pb( + compute.GetRegionInstanceTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstanceTemplate.to_json( + compute.InstanceTemplate() + ) + + request = compute.GetRegionInstanceTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstanceTemplate() + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_rest_bad_request( + transport: str = "rest", request_type=compute.GetRegionInstanceTemplateRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instance_template": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get(request) + + +def test_get_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.InstanceTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instance_template": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.InstanceTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + 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/v1/projects/{project}/regions/{region}/instanceTemplates/{instance_template}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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.GetRegionInstanceTemplateRequest(), + project="project_value", + region="region_value", + instance_template="instance_template_value", + ) + + +def test_get_rest_error(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionInstanceTemplateRequest, + dict, + ], +) +def test_insert_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instance_template_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "properties": { + "advanced_machine_features": { + "enable_nested_virtualization": True, + "enable_uefi_networking": True, + "threads_per_core": 1689, + "visible_core_count": 1918, + }, + "can_ip_forward": True, + "confidential_instance_config": {"enable_confidential_compute": True}, + "description": "description_value", + "disks": [ + { + "architecture": "architecture_value", + "auto_delete": True, + "boot": True, + "device_name": "device_name_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "disk_size_gb": 1261, + "force_attach": True, + "guest_os_features": [{"type_": "type__value"}], + "index": 536, + "initialize_params": { + "architecture": "architecture_value", + "description": "description_value", + "disk_name": "disk_name_value", + "disk_size_gb": 1261, + "disk_type": "disk_type_value", + "labels": {}, + "licenses": ["licenses_value1", "licenses_value2"], + "on_update_action": "on_update_action_value", + "provisioned_iops": 1740, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + }, + "interface": "interface_value", + "kind": "kind_value", + "licenses": ["licenses_value1", "licenses_value2"], + "mode": "mode_value", + "shielded_instance_initial_state": { + "dbs": [ + {"content": "content_value", "file_type": "file_type_value"} + ], + "dbxs": {}, + "keks": {}, + "pk": {}, + }, + "source": "source_value", + "type_": "type__value", + } + ], + "guest_accelerators": [ + { + "accelerator_count": 1805, + "accelerator_type": "accelerator_type_value", + } + ], + "key_revocation_action_type": "key_revocation_action_type_value", + "labels": {}, + "machine_type": "machine_type_value", + "metadata": { + "fingerprint": "fingerprint_value", + "items": [{"key": "key_value", "value": "value_value"}], + "kind": "kind_value", + }, + "min_cpu_platform": "min_cpu_platform_value", + "network_interfaces": [ + { + "access_configs": [ + { + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "kind": "kind_value", + "name": "name_value", + "nat_i_p": "nat_i_p_value", + "network_tier": "network_tier_value", + "public_ptr_domain_name": "public_ptr_domain_name_value", + "set_public_ptr": True, + "type_": "type__value", + } + ], + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "fingerprint": "fingerprint_value", + "internal_ipv6_prefix_length": 2831, + "ipv6_access_configs": {}, + "ipv6_access_type": "ipv6_access_type_value", + "ipv6_address": "ipv6_address_value", + "kind": "kind_value", + "name": "name_value", + "network": "network_value", + "network_attachment": "network_attachment_value", + "network_i_p": "network_i_p_value", + "nic_type": "nic_type_value", + "queue_count": 1197, + "stack_type": "stack_type_value", + "subnetwork": "subnetwork_value", + } + ], + "network_performance_config": { + "total_egress_bandwidth_tier": "total_egress_bandwidth_tier_value" + }, + "private_ipv6_google_access": "private_ipv6_google_access_value", + "reservation_affinity": { + "consume_reservation_type": "consume_reservation_type_value", + "key": "key_value", + "values": ["values_value1", "values_value2"], + }, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "scheduling": { + "automatic_restart": True, + "instance_termination_action": "instance_termination_action_value", + "location_hint": "location_hint_value", + "min_node_cpus": 1379, + "node_affinities": [ + { + "key": "key_value", + "operator": "operator_value", + "values": ["values_value1", "values_value2"], + } + ], + "on_host_maintenance": "on_host_maintenance_value", + "preemptible": True, + "provisioning_model": "provisioning_model_value", + }, + "service_accounts": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "shielded_instance_config": { + "enable_integrity_monitoring": True, + "enable_secure_boot": True, + "enable_vtpm": True, + }, + "tags": { + "fingerprint": "fingerprint_value", + "items": ["items_value1", "items_value2"], + }, + }, + "region": "region_value", + "self_link": "self_link_value", + "source_instance": "source_instance_value", + "source_instance_params": { + "disk_configs": [ + { + "auto_delete": True, + "custom_image": "custom_image_value", + "device_name": "device_name_value", + "instantiate_from": "instantiate_from_value", + } + ] + }, + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_insert_rest_required_fields( + request_type=compute.InsertRegionInstanceTemplateRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._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" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instanceTemplateResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertRegionInstanceTemplateRequest.pb( + compute.InsertRegionInstanceTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertRegionInstanceTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_rest_bad_request( + transport: str = "rest", request_type=compute.InsertRegionInstanceTemplateRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instance_template_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "properties": { + "advanced_machine_features": { + "enable_nested_virtualization": True, + "enable_uefi_networking": True, + "threads_per_core": 1689, + "visible_core_count": 1918, + }, + "can_ip_forward": True, + "confidential_instance_config": {"enable_confidential_compute": True}, + "description": "description_value", + "disks": [ + { + "architecture": "architecture_value", + "auto_delete": True, + "boot": True, + "device_name": "device_name_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "disk_size_gb": 1261, + "force_attach": True, + "guest_os_features": [{"type_": "type__value"}], + "index": 536, + "initialize_params": { + "architecture": "architecture_value", + "description": "description_value", + "disk_name": "disk_name_value", + "disk_size_gb": 1261, + "disk_type": "disk_type_value", + "labels": {}, + "licenses": ["licenses_value1", "licenses_value2"], + "on_update_action": "on_update_action_value", + "provisioned_iops": 1740, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + }, + "interface": "interface_value", + "kind": "kind_value", + "licenses": ["licenses_value1", "licenses_value2"], + "mode": "mode_value", + "shielded_instance_initial_state": { + "dbs": [ + {"content": "content_value", "file_type": "file_type_value"} + ], + "dbxs": {}, + "keks": {}, + "pk": {}, + }, + "source": "source_value", + "type_": "type__value", + } + ], + "guest_accelerators": [ + { + "accelerator_count": 1805, + "accelerator_type": "accelerator_type_value", + } + ], + "key_revocation_action_type": "key_revocation_action_type_value", + "labels": {}, + "machine_type": "machine_type_value", + "metadata": { + "fingerprint": "fingerprint_value", + "items": [{"key": "key_value", "value": "value_value"}], + "kind": "kind_value", + }, + "min_cpu_platform": "min_cpu_platform_value", + "network_interfaces": [ + { + "access_configs": [ + { + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "kind": "kind_value", + "name": "name_value", + "nat_i_p": "nat_i_p_value", + "network_tier": "network_tier_value", + "public_ptr_domain_name": "public_ptr_domain_name_value", + "set_public_ptr": True, + "type_": "type__value", + } + ], + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "fingerprint": "fingerprint_value", + "internal_ipv6_prefix_length": 2831, + "ipv6_access_configs": {}, + "ipv6_access_type": "ipv6_access_type_value", + "ipv6_address": "ipv6_address_value", + "kind": "kind_value", + "name": "name_value", + "network": "network_value", + "network_attachment": "network_attachment_value", + "network_i_p": "network_i_p_value", + "nic_type": "nic_type_value", + "queue_count": 1197, + "stack_type": "stack_type_value", + "subnetwork": "subnetwork_value", + } + ], + "network_performance_config": { + "total_egress_bandwidth_tier": "total_egress_bandwidth_tier_value" + }, + "private_ipv6_google_access": "private_ipv6_google_access_value", + "reservation_affinity": { + "consume_reservation_type": "consume_reservation_type_value", + "key": "key_value", + "values": ["values_value1", "values_value2"], + }, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "scheduling": { + "automatic_restart": True, + "instance_termination_action": "instance_termination_action_value", + "location_hint": "location_hint_value", + "min_node_cpus": 1379, + "node_affinities": [ + { + "key": "key_value", + "operator": "operator_value", + "values": ["values_value1", "values_value2"], + } + ], + "on_host_maintenance": "on_host_maintenance_value", + "preemptible": True, + "provisioning_model": "provisioning_model_value", + }, + "service_accounts": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "shielded_instance_config": { + "enable_integrity_monitoring": True, + "enable_secure_boot": True, + "enable_vtpm": True, + }, + "tags": { + "fingerprint": "fingerprint_value", + "items": ["items_value1", "items_value2"], + }, + }, + "region": "region_value", + "self_link": "self_link_value", + "source_instance": "source_instance_value", + "source_instance_params": { + "disk_configs": [ + { + "auto_delete": True, + "custom_image": "custom_image_value", + "device_name": "device_name_value", + "instantiate_from": "instantiate_from_value", + } + ] + }, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert(request) + + +def test_insert_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instance_template_resource=compute.InstanceTemplate( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert(**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/v1/projects/{project}/regions/{region}/instanceTemplates" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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.insert( + compute.InsertRegionInstanceTemplateRequest(), + project="project_value", + region="region_value", + instance_template_resource=compute.InstanceTemplate( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_insert_rest_error(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionInstanceTemplateRequest, + dict, + ], +) +def test_insert_unary_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instance_template_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "properties": { + "advanced_machine_features": { + "enable_nested_virtualization": True, + "enable_uefi_networking": True, + "threads_per_core": 1689, + "visible_core_count": 1918, + }, + "can_ip_forward": True, + "confidential_instance_config": {"enable_confidential_compute": True}, + "description": "description_value", + "disks": [ + { + "architecture": "architecture_value", + "auto_delete": True, + "boot": True, + "device_name": "device_name_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "disk_size_gb": 1261, + "force_attach": True, + "guest_os_features": [{"type_": "type__value"}], + "index": 536, + "initialize_params": { + "architecture": "architecture_value", + "description": "description_value", + "disk_name": "disk_name_value", + "disk_size_gb": 1261, + "disk_type": "disk_type_value", + "labels": {}, + "licenses": ["licenses_value1", "licenses_value2"], + "on_update_action": "on_update_action_value", + "provisioned_iops": 1740, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + }, + "interface": "interface_value", + "kind": "kind_value", + "licenses": ["licenses_value1", "licenses_value2"], + "mode": "mode_value", + "shielded_instance_initial_state": { + "dbs": [ + {"content": "content_value", "file_type": "file_type_value"} + ], + "dbxs": {}, + "keks": {}, + "pk": {}, + }, + "source": "source_value", + "type_": "type__value", + } + ], + "guest_accelerators": [ + { + "accelerator_count": 1805, + "accelerator_type": "accelerator_type_value", + } + ], + "key_revocation_action_type": "key_revocation_action_type_value", + "labels": {}, + "machine_type": "machine_type_value", + "metadata": { + "fingerprint": "fingerprint_value", + "items": [{"key": "key_value", "value": "value_value"}], + "kind": "kind_value", + }, + "min_cpu_platform": "min_cpu_platform_value", + "network_interfaces": [ + { + "access_configs": [ + { + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "kind": "kind_value", + "name": "name_value", + "nat_i_p": "nat_i_p_value", + "network_tier": "network_tier_value", + "public_ptr_domain_name": "public_ptr_domain_name_value", + "set_public_ptr": True, + "type_": "type__value", + } + ], + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "fingerprint": "fingerprint_value", + "internal_ipv6_prefix_length": 2831, + "ipv6_access_configs": {}, + "ipv6_access_type": "ipv6_access_type_value", + "ipv6_address": "ipv6_address_value", + "kind": "kind_value", + "name": "name_value", + "network": "network_value", + "network_attachment": "network_attachment_value", + "network_i_p": "network_i_p_value", + "nic_type": "nic_type_value", + "queue_count": 1197, + "stack_type": "stack_type_value", + "subnetwork": "subnetwork_value", + } + ], + "network_performance_config": { + "total_egress_bandwidth_tier": "total_egress_bandwidth_tier_value" + }, + "private_ipv6_google_access": "private_ipv6_google_access_value", + "reservation_affinity": { + "consume_reservation_type": "consume_reservation_type_value", + "key": "key_value", + "values": ["values_value1", "values_value2"], + }, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "scheduling": { + "automatic_restart": True, + "instance_termination_action": "instance_termination_action_value", + "location_hint": "location_hint_value", + "min_node_cpus": 1379, + "node_affinities": [ + { + "key": "key_value", + "operator": "operator_value", + "values": ["values_value1", "values_value2"], + } + ], + "on_host_maintenance": "on_host_maintenance_value", + "preemptible": True, + "provisioning_model": "provisioning_model_value", + }, + "service_accounts": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "shielded_instance_config": { + "enable_integrity_monitoring": True, + "enable_secure_boot": True, + "enable_vtpm": True, + }, + "tags": { + "fingerprint": "fingerprint_value", + "items": ["items_value1", "items_value2"], + }, + }, + "region": "region_value", + "self_link": "self_link_value", + "source_instance": "source_instance_value", + "source_instance_params": { + "disk_configs": [ + { + "auto_delete": True, + "custom_image": "custom_image_value", + "device_name": "device_name_value", + "instantiate_from": "instantiate_from_value", + } + ] + }, + } + 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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_insert_unary_rest_required_fields( + request_type=compute.InsertRegionInstanceTemplateRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._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" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.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 + + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instanceTemplateResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_unary_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertRegionInstanceTemplateRequest.pb( + compute.InsertRegionInstanceTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertRegionInstanceTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_unary_rest_bad_request( + transport: str = "rest", request_type=compute.InsertRegionInstanceTemplateRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instance_template_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "name": "name_value", + "properties": { + "advanced_machine_features": { + "enable_nested_virtualization": True, + "enable_uefi_networking": True, + "threads_per_core": 1689, + "visible_core_count": 1918, + }, + "can_ip_forward": True, + "confidential_instance_config": {"enable_confidential_compute": True}, + "description": "description_value", + "disks": [ + { + "architecture": "architecture_value", + "auto_delete": True, + "boot": True, + "device_name": "device_name_value", + "disk_encryption_key": { + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "sha256": "sha256_value", + }, + "disk_size_gb": 1261, + "force_attach": True, + "guest_os_features": [{"type_": "type__value"}], + "index": 536, + "initialize_params": { + "architecture": "architecture_value", + "description": "description_value", + "disk_name": "disk_name_value", + "disk_size_gb": 1261, + "disk_type": "disk_type_value", + "labels": {}, + "licenses": ["licenses_value1", "licenses_value2"], + "on_update_action": "on_update_action_value", + "provisioned_iops": 1740, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "source_image": "source_image_value", + "source_image_encryption_key": {}, + "source_snapshot": "source_snapshot_value", + "source_snapshot_encryption_key": {}, + }, + "interface": "interface_value", + "kind": "kind_value", + "licenses": ["licenses_value1", "licenses_value2"], + "mode": "mode_value", + "shielded_instance_initial_state": { + "dbs": [ + {"content": "content_value", "file_type": "file_type_value"} + ], + "dbxs": {}, + "keks": {}, + "pk": {}, + }, + "source": "source_value", + "type_": "type__value", + } + ], + "guest_accelerators": [ + { + "accelerator_count": 1805, + "accelerator_type": "accelerator_type_value", + } + ], + "key_revocation_action_type": "key_revocation_action_type_value", + "labels": {}, + "machine_type": "machine_type_value", + "metadata": { + "fingerprint": "fingerprint_value", + "items": [{"key": "key_value", "value": "value_value"}], + "kind": "kind_value", + }, + "min_cpu_platform": "min_cpu_platform_value", + "network_interfaces": [ + { + "access_configs": [ + { + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "kind": "kind_value", + "name": "name_value", + "nat_i_p": "nat_i_p_value", + "network_tier": "network_tier_value", + "public_ptr_domain_name": "public_ptr_domain_name_value", + "set_public_ptr": True, + "type_": "type__value", + } + ], + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "fingerprint": "fingerprint_value", + "internal_ipv6_prefix_length": 2831, + "ipv6_access_configs": {}, + "ipv6_access_type": "ipv6_access_type_value", + "ipv6_address": "ipv6_address_value", + "kind": "kind_value", + "name": "name_value", + "network": "network_value", + "network_attachment": "network_attachment_value", + "network_i_p": "network_i_p_value", + "nic_type": "nic_type_value", + "queue_count": 1197, + "stack_type": "stack_type_value", + "subnetwork": "subnetwork_value", + } + ], + "network_performance_config": { + "total_egress_bandwidth_tier": "total_egress_bandwidth_tier_value" + }, + "private_ipv6_google_access": "private_ipv6_google_access_value", + "reservation_affinity": { + "consume_reservation_type": "consume_reservation_type_value", + "key": "key_value", + "values": ["values_value1", "values_value2"], + }, + "resource_manager_tags": {}, + "resource_policies": [ + "resource_policies_value1", + "resource_policies_value2", + ], + "scheduling": { + "automatic_restart": True, + "instance_termination_action": "instance_termination_action_value", + "location_hint": "location_hint_value", + "min_node_cpus": 1379, + "node_affinities": [ + { + "key": "key_value", + "operator": "operator_value", + "values": ["values_value1", "values_value2"], + } + ], + "on_host_maintenance": "on_host_maintenance_value", + "preemptible": True, + "provisioning_model": "provisioning_model_value", + }, + "service_accounts": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "shielded_instance_config": { + "enable_integrity_monitoring": True, + "enable_secure_boot": True, + "enable_vtpm": True, + }, + "tags": { + "fingerprint": "fingerprint_value", + "items": ["items_value1", "items_value2"], + }, + }, + "region": "region_value", + "self_link": "self_link_value", + "source_instance": "source_instance_value", + "source_instance_params": { + "disk_configs": [ + { + "auto_delete": True, + "custom_image": "custom_image_value", + "device_name": "device_name_value", + "instantiate_from": "instantiate_from_value", + } + ] + }, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert_unary(request) + + +def test_insert_unary_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instance_template_resource=compute.InstanceTemplate( + creation_timestamp="creation_timestamp_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert_unary(**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/v1/projects/{project}/regions/{region}/instanceTemplates" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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.insert_unary( + compute.InsertRegionInstanceTemplateRequest(), + project="project_value", + region="region_value", + instance_template_resource=compute.InstanceTemplate( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_insert_unary_rest_error(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRegionInstanceTemplatesRequest, + dict, + ], +) +def test_list_rest(request_type): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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.InstanceTemplateList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.InstanceTemplateList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + 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.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +def test_list_rest_required_fields( + request_type=compute.ListRegionInstanceTemplatesRequest, +): + transport_class = transports.RegionInstanceTemplatesRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + 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" + jsonified_request["region"] = "region_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" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstanceTemplateList() + # 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 + + pb_return_value = compute.InstanceTemplateList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstanceTemplatesRestInterceptor(), + ) + client = RegionInstanceTemplatesClient(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.RegionInstanceTemplatesRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.RegionInstanceTemplatesRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.ListRegionInstanceTemplatesRequest.pb( + compute.ListRegionInstanceTemplatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstanceTemplateList.to_json( + compute.InstanceTemplateList() + ) + + request = compute.ListRegionInstanceTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstanceTemplateList() + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_rest_bad_request( + transport: str = "rest", request_type=compute.ListRegionInstanceTemplatesRequest +): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list(request) + + +def test_list_rest_flattened(): + client = RegionInstanceTemplatesClient( + 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.InstanceTemplateList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = compute.InstanceTemplateList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + 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/v1/projects/{project}/regions/{region}/instanceTemplates" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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.ListRegionInstanceTemplatesRequest(), + project="project_value", + region="region_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RegionInstanceTemplatesClient( + 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.InstanceTemplateList( + items=[ + compute.InstanceTemplate(), + compute.InstanceTemplate(), + compute.InstanceTemplate(), + ], + next_page_token="abc", + ), + compute.InstanceTemplateList( + items=[], + next_page_token="def", + ), + compute.InstanceTemplateList( + items=[ + compute.InstanceTemplate(), + ], + next_page_token="ghi", + ), + compute.InstanceTemplateList( + items=[ + compute.InstanceTemplate(), + compute.InstanceTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.InstanceTemplateList.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", "region": "sample2"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.InstanceTemplate) 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.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstanceTemplatesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionInstanceTemplatesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionInstanceTemplatesClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstanceTemplatesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionInstanceTemplatesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionInstanceTemplatesClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionInstanceTemplatesRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_transport_kind(transport_name): + transport = RegionInstanceTemplatesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_region_instance_templates_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionInstanceTemplatesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_instance_templates_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.region_instance_templates.transports.RegionInstanceTemplatesTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionInstanceTemplatesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "insert", + "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_region_instance_templates_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_v1.services.region_instance_templates.transports.RegionInstanceTemplatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstanceTemplatesTransport( + 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", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_region_instance_templates_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_v1.services.region_instance_templates.transports.RegionInstanceTemplatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstanceTemplatesTransport() + adc.assert_called_once() + + +def test_region_instance_templates_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) + RegionInstanceTemplatesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_region_instance_templates_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.RegionInstanceTemplatesRestTransport( + 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_region_instance_templates_host_no_port(transport_name): + client = RegionInstanceTemplatesClient( + 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_region_instance_templates_host_with_port(transport_name): + client = RegionInstanceTemplatesClient( + 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_region_instance_templates_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionInstanceTemplatesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionInstanceTemplatesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._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 = RegionInstanceTemplatesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionInstanceTemplatesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstanceTemplatesClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RegionInstanceTemplatesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionInstanceTemplatesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstanceTemplatesClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RegionInstanceTemplatesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionInstanceTemplatesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstanceTemplatesClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RegionInstanceTemplatesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionInstanceTemplatesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstanceTemplatesClient.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 = RegionInstanceTemplatesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionInstanceTemplatesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstanceTemplatesClient.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.RegionInstanceTemplatesTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionInstanceTemplatesTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionInstanceTemplatesClient.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(): + transports = { + "rest": "_session", + } + + for transport, close_name in transports.items(): + client = RegionInstanceTemplatesClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = RegionInstanceTemplatesClient( + 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", + [ + ( + RegionInstanceTemplatesClient, + transports.RegionInstanceTemplatesRestTransport, + ), + ], +) +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, + 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/tests/unit/gapic/compute_v1/test_region_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py index 3d17312e8ca2..c17628a33160 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py @@ -1633,6 +1633,23 @@ def test_insert_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -1948,6 +1965,23 @@ def test_insert_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -2127,6 +2161,23 @@ def test_insert_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -2420,6 +2471,23 @@ def test_insert_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -2962,6 +3030,23 @@ def test_patch_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3276,6 +3361,23 @@ def test_patch_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3465,6 +3567,23 @@ def test_patch_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3757,6 +3876,23 @@ def test_patch_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py index 20b0a8d2a691..6c9788dea2a2 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py @@ -617,6 +617,23 @@ def test_add_rule_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -891,6 +908,23 @@ def test_add_rule_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -1031,6 +1065,23 @@ def test_add_rule_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -1283,6 +1334,23 @@ def test_add_rule_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3032,6 +3100,23 @@ def test_insert_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3340,6 +3425,23 @@ def test_insert_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3517,6 +3619,23 @@ def test_insert_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -3805,6 +3924,23 @@ def test_insert_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -4639,6 +4775,23 @@ def test_patch_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -4942,6 +5095,23 @@ def test_patch_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -5121,6 +5291,23 @@ def test_patch_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -5404,6 +5591,23 @@ def test_patch_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -5556,6 +5760,23 @@ def test_patch_rule_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -5840,6 +6061,23 @@ def test_patch_rule_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -5980,6 +6218,23 @@ def test_patch_rule_unary_rest(request_type): }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": { @@ -6242,6 +6497,23 @@ def test_patch_rule_unary_rest_bad_request( }, "versioned_expr": "versioned_expr_value", }, + "preconfigured_waf_config": { + "exclusions": [ + { + "request_cookies_to_exclude": [ + {"op": "op_value", "val": "val_value"} + ], + "request_headers_to_exclude": {}, + "request_query_params_to_exclude": {}, + "request_uris_to_exclude": {}, + "target_rule_ids": [ + "target_rule_ids_value1", + "target_rule_ids_value2", + ], + "target_rule_set": "target_rule_set_value", + } + ] + }, "preview": True, "priority": 898, "rate_limit_options": {