diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_certificates.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_certificates.rst index d47fbee3b5a1..03ac3108415c 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_certificates.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_certificates.rst @@ -5,7 +5,6 @@ AuthorizedCertificates :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.authorized_certificates.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_domains.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_domains.rst index c3f3e7c9807d..d02102abdddd 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_domains.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/authorized_domains.rst @@ -5,7 +5,6 @@ AuthorizedDomains :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.authorized_domains.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/domain_mappings.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/domain_mappings.rst index 58dc8c20cd20..89af15b43e85 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/domain_mappings.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/domain_mappings.rst @@ -5,7 +5,6 @@ DomainMappings :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.domain_mappings.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/firewall.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/firewall.rst index ccf12e6922dc..ce343d137e60 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/firewall.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/firewall.rst @@ -5,7 +5,6 @@ Firewall :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.firewall.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/instances.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/instances.rst index 04bccfbe9e64..57f5079d5ae9 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/instances.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/instances.rst @@ -5,7 +5,6 @@ Instances :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.instances.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/versions.rst b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/versions.rst index c0e44d86bf48..58a0f632b87e 100644 --- a/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/versions.rst +++ b/packages/google-cloud-appengine-admin/docs/appengine_admin_v1/versions.rst @@ -5,7 +5,6 @@ Versions :members: :inherited-members: - .. automodule:: google.cloud.appengine_admin_v1.services.versions.pagers :members: :inherited-members: diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/__init__.py index bc871b95edac..579693bac6ae 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,60 +14,60 @@ # limitations under the License. # -from google.cloud.appengine_admin_v1.services.applications.async_client import ( - ApplicationsAsyncClient, -) from google.cloud.appengine_admin_v1.services.applications.client import ( ApplicationsClient, ) -from google.cloud.appengine_admin_v1.services.authorized_certificates.async_client import ( - AuthorizedCertificatesAsyncClient, +from google.cloud.appengine_admin_v1.services.applications.async_client import ( + ApplicationsAsyncClient, ) from google.cloud.appengine_admin_v1.services.authorized_certificates.client import ( AuthorizedCertificatesClient, ) -from google.cloud.appengine_admin_v1.services.authorized_domains.async_client import ( - AuthorizedDomainsAsyncClient, +from google.cloud.appengine_admin_v1.services.authorized_certificates.async_client import ( + AuthorizedCertificatesAsyncClient, ) from google.cloud.appengine_admin_v1.services.authorized_domains.client import ( AuthorizedDomainsClient, ) -from google.cloud.appengine_admin_v1.services.domain_mappings.async_client import ( - DomainMappingsAsyncClient, +from google.cloud.appengine_admin_v1.services.authorized_domains.async_client import ( + AuthorizedDomainsAsyncClient, ) from google.cloud.appengine_admin_v1.services.domain_mappings.client import ( DomainMappingsClient, ) +from google.cloud.appengine_admin_v1.services.domain_mappings.async_client import ( + DomainMappingsAsyncClient, +) +from google.cloud.appengine_admin_v1.services.firewall.client import FirewallClient from google.cloud.appengine_admin_v1.services.firewall.async_client import ( FirewallAsyncClient, ) -from google.cloud.appengine_admin_v1.services.firewall.client import FirewallClient +from google.cloud.appengine_admin_v1.services.instances.client import InstancesClient from google.cloud.appengine_admin_v1.services.instances.async_client import ( InstancesAsyncClient, ) -from google.cloud.appengine_admin_v1.services.instances.client import InstancesClient +from google.cloud.appengine_admin_v1.services.services.client import ServicesClient from google.cloud.appengine_admin_v1.services.services.async_client import ( ServicesAsyncClient, ) -from google.cloud.appengine_admin_v1.services.services.client import ServicesClient +from google.cloud.appengine_admin_v1.services.versions.client import VersionsClient from google.cloud.appengine_admin_v1.services.versions.async_client import ( VersionsAsyncClient, ) -from google.cloud.appengine_admin_v1.services.versions.client import VersionsClient + from google.cloud.appengine_admin_v1.types.app_yaml import ApiConfigHandler from google.cloud.appengine_admin_v1.types.app_yaml import ApiEndpointHandler -from google.cloud.appengine_admin_v1.types.app_yaml import AuthFailAction from google.cloud.appengine_admin_v1.types.app_yaml import ErrorHandler from google.cloud.appengine_admin_v1.types.app_yaml import HealthCheck from google.cloud.appengine_admin_v1.types.app_yaml import Library from google.cloud.appengine_admin_v1.types.app_yaml import LivenessCheck -from google.cloud.appengine_admin_v1.types.app_yaml import LoginRequirement from google.cloud.appengine_admin_v1.types.app_yaml import ReadinessCheck from google.cloud.appengine_admin_v1.types.app_yaml import ScriptHandler -from google.cloud.appengine_admin_v1.types.app_yaml import SecurityLevel from google.cloud.appengine_admin_v1.types.app_yaml import StaticFilesHandler from google.cloud.appengine_admin_v1.types.app_yaml import UrlMap -from google.cloud.appengine_admin_v1.types.appengine import AuthorizedCertificateView +from google.cloud.appengine_admin_v1.types.app_yaml import AuthFailAction +from google.cloud.appengine_admin_v1.types.app_yaml import LoginRequirement +from google.cloud.appengine_admin_v1.types.app_yaml import SecurityLevel from google.cloud.appengine_admin_v1.types.appengine import ( BatchUpdateIngressRulesRequest, ) @@ -91,7 +90,6 @@ from google.cloud.appengine_admin_v1.types.appengine import DeleteInstanceRequest from google.cloud.appengine_admin_v1.types.appengine import DeleteServiceRequest from google.cloud.appengine_admin_v1.types.appengine import DeleteVersionRequest -from google.cloud.appengine_admin_v1.types.appengine import DomainOverrideStrategy from google.cloud.appengine_admin_v1.types.appengine import GetApplicationRequest from google.cloud.appengine_admin_v1.types.appengine import ( GetAuthorizedCertificateRequest, @@ -130,6 +128,8 @@ from google.cloud.appengine_admin_v1.types.appengine import UpdateIngressRuleRequest from google.cloud.appengine_admin_v1.types.appengine import UpdateServiceRequest from google.cloud.appengine_admin_v1.types.appengine import UpdateVersionRequest +from google.cloud.appengine_admin_v1.types.appengine import AuthorizedCertificateView +from google.cloud.appengine_admin_v1.types.appengine import DomainOverrideStrategy from google.cloud.appengine_admin_v1.types.appengine import VersionView from google.cloud.appengine_admin_v1.types.application import Application from google.cloud.appengine_admin_v1.types.application import UrlDispatchRule @@ -163,47 +163,54 @@ from google.cloud.appengine_admin_v1.types.version import DiskUtilization from google.cloud.appengine_admin_v1.types.version import EndpointsApiService from google.cloud.appengine_admin_v1.types.version import Entrypoint -from google.cloud.appengine_admin_v1.types.version import InboundServiceType from google.cloud.appengine_admin_v1.types.version import ManualScaling from google.cloud.appengine_admin_v1.types.version import Network from google.cloud.appengine_admin_v1.types.version import NetworkUtilization from google.cloud.appengine_admin_v1.types.version import RequestUtilization from google.cloud.appengine_admin_v1.types.version import Resources -from google.cloud.appengine_admin_v1.types.version import ServingStatus from google.cloud.appengine_admin_v1.types.version import StandardSchedulerSettings from google.cloud.appengine_admin_v1.types.version import Version from google.cloud.appengine_admin_v1.types.version import Volume from google.cloud.appengine_admin_v1.types.version import VpcAccessConnector +from google.cloud.appengine_admin_v1.types.version import InboundServiceType +from google.cloud.appengine_admin_v1.types.version import ServingStatus __all__ = ( - "ApiConfigHandler", - "ApiEndpointHandler", - "Application", - "ApplicationsAsyncClient", "ApplicationsClient", - "AuditData", - "AuthFailAction", - "AuthorizedCertificate", - "AuthorizedCertificateView", - "AuthorizedCertificatesAsyncClient", + "ApplicationsAsyncClient", "AuthorizedCertificatesClient", - "AuthorizedDomain", - "AuthorizedDomainsAsyncClient", + "AuthorizedCertificatesAsyncClient", "AuthorizedDomainsClient", - "AutomaticScaling", - "BasicScaling", + "AuthorizedDomainsAsyncClient", + "DomainMappingsClient", + "DomainMappingsAsyncClient", + "FirewallClient", + "FirewallAsyncClient", + "InstancesClient", + "InstancesAsyncClient", + "ServicesClient", + "ServicesAsyncClient", + "VersionsClient", + "VersionsAsyncClient", + "ApiConfigHandler", + "ApiEndpointHandler", + "ErrorHandler", + "HealthCheck", + "Library", + "LivenessCheck", + "ReadinessCheck", + "ScriptHandler", + "StaticFilesHandler", + "UrlMap", + "AuthFailAction", + "LoginRequirement", + "SecurityLevel", "BatchUpdateIngressRulesRequest", "BatchUpdateIngressRulesResponse", - "CertificateRawData", - "CloudBuildOptions", - "ContainerInfo", - "CpuUtilization", "CreateApplicationRequest", "CreateAuthorizedCertificateRequest", "CreateDomainMappingRequest", "CreateIngressRuleRequest", - "CreateVersionMetadataV1", - "CreateVersionMethod", "CreateVersionRequest", "DebugInstanceRequest", "DeleteAuthorizedCertificateRequest", @@ -212,19 +219,6 @@ "DeleteInstanceRequest", "DeleteServiceRequest", "DeleteVersionRequest", - "Deployment", - "DiskUtilization", - "DomainMapping", - "DomainMappingsAsyncClient", - "DomainMappingsClient", - "DomainOverrideStrategy", - "EndpointsApiService", - "Entrypoint", - "ErrorHandler", - "FileInfo", - "FirewallAsyncClient", - "FirewallClient", - "FirewallRule", "GetApplicationRequest", "GetAuthorizedCertificateRequest", "GetDomainMappingRequest", @@ -232,12 +226,6 @@ "GetInstanceRequest", "GetServiceRequest", "GetVersionRequest", - "HealthCheck", - "InboundServiceType", - "Instance", - "InstancesAsyncClient", - "InstancesClient", - "Library", "ListAuthorizedCertificatesRequest", "ListAuthorizedCertificatesResponse", "ListAuthorizedDomainsRequest", @@ -252,45 +240,57 @@ "ListServicesResponse", "ListVersionsRequest", "ListVersionsResponse", - "LivenessCheck", - "LocationMetadata", - "LoginRequirement", - "ManagedCertificate", - "ManagementStatus", - "ManualScaling", - "Network", - "NetworkSettings", - "NetworkUtilization", - "OperationMetadataV1", - "ReadinessCheck", "RepairApplicationRequest", - "RequestUtilization", - "ResourceRecord", - "Resources", - "ScriptHandler", - "SecurityLevel", - "Service", - "ServicesAsyncClient", - "ServicesClient", - "ServingStatus", - "SslSettings", - "StandardSchedulerSettings", - "StaticFilesHandler", - "TrafficSplit", "UpdateApplicationRequest", "UpdateAuthorizedCertificateRequest", "UpdateDomainMappingRequest", "UpdateIngressRuleRequest", - "UpdateServiceMethod", "UpdateServiceRequest", "UpdateVersionRequest", + "AuthorizedCertificateView", + "DomainOverrideStrategy", + "VersionView", + "Application", "UrlDispatchRule", - "UrlMap", + "AuditData", + "CreateVersionMethod", + "UpdateServiceMethod", + "AuthorizedCertificate", + "CertificateRawData", + "ManagedCertificate", + "ManagementStatus", + "CloudBuildOptions", + "ContainerInfo", + "Deployment", + "FileInfo", + "ZipInfo", + "AuthorizedDomain", + "DomainMapping", + "ResourceRecord", + "SslSettings", + "FirewallRule", + "Instance", + "LocationMetadata", + "NetworkSettings", + "CreateVersionMetadataV1", + "OperationMetadataV1", + "Service", + "TrafficSplit", + "AutomaticScaling", + "BasicScaling", + "CpuUtilization", + "DiskUtilization", + "EndpointsApiService", + "Entrypoint", + "ManualScaling", + "Network", + "NetworkUtilization", + "RequestUtilization", + "Resources", + "StandardSchedulerSettings", "Version", - "VersionView", - "VersionsAsyncClient", - "VersionsClient", "Volume", "VpcAccessConnector", - "ZipInfo", + "InboundServiceType", + "ServingStatus", ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/__init__.py index a463e618d72b..9bb498e5d747 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,27 +15,35 @@ # from .services.applications import ApplicationsClient +from .services.applications import ApplicationsAsyncClient from .services.authorized_certificates import AuthorizedCertificatesClient +from .services.authorized_certificates import AuthorizedCertificatesAsyncClient from .services.authorized_domains import AuthorizedDomainsClient +from .services.authorized_domains import AuthorizedDomainsAsyncClient from .services.domain_mappings import DomainMappingsClient +from .services.domain_mappings import DomainMappingsAsyncClient from .services.firewall import FirewallClient +from .services.firewall import FirewallAsyncClient from .services.instances import InstancesClient +from .services.instances import InstancesAsyncClient from .services.services import ServicesClient +from .services.services import ServicesAsyncClient from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + from .types.app_yaml import ApiConfigHandler from .types.app_yaml import ApiEndpointHandler -from .types.app_yaml import AuthFailAction from .types.app_yaml import ErrorHandler from .types.app_yaml import HealthCheck from .types.app_yaml import Library from .types.app_yaml import LivenessCheck -from .types.app_yaml import LoginRequirement from .types.app_yaml import ReadinessCheck from .types.app_yaml import ScriptHandler -from .types.app_yaml import SecurityLevel from .types.app_yaml import StaticFilesHandler from .types.app_yaml import UrlMap -from .types.appengine import AuthorizedCertificateView +from .types.app_yaml import AuthFailAction +from .types.app_yaml import LoginRequirement +from .types.app_yaml import SecurityLevel from .types.appengine import BatchUpdateIngressRulesRequest from .types.appengine import BatchUpdateIngressRulesResponse from .types.appengine import CreateApplicationRequest @@ -51,7 +58,6 @@ from .types.appengine import DeleteInstanceRequest from .types.appengine import DeleteServiceRequest from .types.appengine import DeleteVersionRequest -from .types.appengine import DomainOverrideStrategy from .types.appengine import GetApplicationRequest from .types.appengine import GetAuthorizedCertificateRequest from .types.appengine import GetDomainMappingRequest @@ -80,6 +86,8 @@ from .types.appengine import UpdateIngressRuleRequest from .types.appengine import UpdateServiceRequest from .types.appengine import UpdateVersionRequest +from .types.appengine import AuthorizedCertificateView +from .types.appengine import DomainOverrideStrategy from .types.appengine import VersionView from .types.application import Application from .types.application import UrlDispatchRule @@ -113,23 +121,31 @@ from .types.version import DiskUtilization from .types.version import EndpointsApiService from .types.version import Entrypoint -from .types.version import InboundServiceType from .types.version import ManualScaling from .types.version import Network from .types.version import NetworkUtilization from .types.version import RequestUtilization from .types.version import Resources -from .types.version import ServingStatus from .types.version import StandardSchedulerSettings from .types.version import Version from .types.version import Volume from .types.version import VpcAccessConnector - +from .types.version import InboundServiceType +from .types.version import ServingStatus __all__ = ( + "ApplicationsAsyncClient", + "AuthorizedCertificatesAsyncClient", + "AuthorizedDomainsAsyncClient", + "DomainMappingsAsyncClient", + "FirewallAsyncClient", + "InstancesAsyncClient", + "ServicesAsyncClient", + "VersionsAsyncClient", "ApiConfigHandler", "ApiEndpointHandler", "Application", + "ApplicationsClient", "AuditData", "AuthFailAction", "AuthorizedCertificate", @@ -235,5 +251,4 @@ "Volume", "VpcAccessConnector", "ZipInfo", - "ApplicationsClient", ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_metadata.json b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_metadata.json new file mode 100644 index 000000000000..0bb65832e9a2 --- /dev/null +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/gapic_metadata.json @@ -0,0 +1,461 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.appengine_admin_v1", + "protoPackage": "google.appengine.v1", + "schema": "1.0", + "services": { + "Applications": { + "clients": { + "grpc": { + "libraryClient": "ApplicationsClient", + "rpcs": { + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "RepairApplication": { + "methods": [ + "repair_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ApplicationsAsyncClient", + "rpcs": { + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "RepairApplication": { + "methods": [ + "repair_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + } + } + } + } + }, + "AuthorizedCertificates": { + "clients": { + "grpc": { + "libraryClient": "AuthorizedCertificatesClient", + "rpcs": { + "CreateAuthorizedCertificate": { + "methods": [ + "create_authorized_certificate" + ] + }, + "DeleteAuthorizedCertificate": { + "methods": [ + "delete_authorized_certificate" + ] + }, + "GetAuthorizedCertificate": { + "methods": [ + "get_authorized_certificate" + ] + }, + "ListAuthorizedCertificates": { + "methods": [ + "list_authorized_certificates" + ] + }, + "UpdateAuthorizedCertificate": { + "methods": [ + "update_authorized_certificate" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AuthorizedCertificatesAsyncClient", + "rpcs": { + "CreateAuthorizedCertificate": { + "methods": [ + "create_authorized_certificate" + ] + }, + "DeleteAuthorizedCertificate": { + "methods": [ + "delete_authorized_certificate" + ] + }, + "GetAuthorizedCertificate": { + "methods": [ + "get_authorized_certificate" + ] + }, + "ListAuthorizedCertificates": { + "methods": [ + "list_authorized_certificates" + ] + }, + "UpdateAuthorizedCertificate": { + "methods": [ + "update_authorized_certificate" + ] + } + } + } + } + }, + "AuthorizedDomains": { + "clients": { + "grpc": { + "libraryClient": "AuthorizedDomainsClient", + "rpcs": { + "ListAuthorizedDomains": { + "methods": [ + "list_authorized_domains" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AuthorizedDomainsAsyncClient", + "rpcs": { + "ListAuthorizedDomains": { + "methods": [ + "list_authorized_domains" + ] + } + } + } + } + }, + "DomainMappings": { + "clients": { + "grpc": { + "libraryClient": "DomainMappingsClient", + "rpcs": { + "CreateDomainMapping": { + "methods": [ + "create_domain_mapping" + ] + }, + "DeleteDomainMapping": { + "methods": [ + "delete_domain_mapping" + ] + }, + "GetDomainMapping": { + "methods": [ + "get_domain_mapping" + ] + }, + "ListDomainMappings": { + "methods": [ + "list_domain_mappings" + ] + }, + "UpdateDomainMapping": { + "methods": [ + "update_domain_mapping" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DomainMappingsAsyncClient", + "rpcs": { + "CreateDomainMapping": { + "methods": [ + "create_domain_mapping" + ] + }, + "DeleteDomainMapping": { + "methods": [ + "delete_domain_mapping" + ] + }, + "GetDomainMapping": { + "methods": [ + "get_domain_mapping" + ] + }, + "ListDomainMappings": { + "methods": [ + "list_domain_mappings" + ] + }, + "UpdateDomainMapping": { + "methods": [ + "update_domain_mapping" + ] + } + } + } + } + }, + "Firewall": { + "clients": { + "grpc": { + "libraryClient": "FirewallClient", + "rpcs": { + "BatchUpdateIngressRules": { + "methods": [ + "batch_update_ingress_rules" + ] + }, + "CreateIngressRule": { + "methods": [ + "create_ingress_rule" + ] + }, + "DeleteIngressRule": { + "methods": [ + "delete_ingress_rule" + ] + }, + "GetIngressRule": { + "methods": [ + "get_ingress_rule" + ] + }, + "ListIngressRules": { + "methods": [ + "list_ingress_rules" + ] + }, + "UpdateIngressRule": { + "methods": [ + "update_ingress_rule" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FirewallAsyncClient", + "rpcs": { + "BatchUpdateIngressRules": { + "methods": [ + "batch_update_ingress_rules" + ] + }, + "CreateIngressRule": { + "methods": [ + "create_ingress_rule" + ] + }, + "DeleteIngressRule": { + "methods": [ + "delete_ingress_rule" + ] + }, + "GetIngressRule": { + "methods": [ + "get_ingress_rule" + ] + }, + "ListIngressRules": { + "methods": [ + "list_ingress_rules" + ] + }, + "UpdateIngressRule": { + "methods": [ + "update_ingress_rule" + ] + } + } + } + } + }, + "Instances": { + "clients": { + "grpc": { + "libraryClient": "InstancesClient", + "rpcs": { + "DebugInstance": { + "methods": [ + "debug_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + } + } + }, + "grpc-async": { + "libraryClient": "InstancesAsyncClient", + "rpcs": { + "DebugInstance": { + "methods": [ + "debug_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + } + } + } + } + }, + "Services": { + "clients": { + "grpc": { + "libraryClient": "ServicesClient", + "rpcs": { + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServicesAsyncClient", + "rpcs": { + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/__init__.py index 42ffdf2bc43d..4de65971c238 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/__init__.py index e512cac09b30..77403bc97783 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ApplicationsClient from .async_client import ApplicationsAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/async_client.py index 98474c7b3864..29ffd860dc75 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation as gac_operation # type: ignore @@ -33,8 +31,7 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import duration_pb2 as duration # type: ignore - +from google.protobuf import duration_pb2 # type: ignore from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport from .client import ApplicationsClient @@ -54,20 +51,16 @@ class ApplicationsAsyncClient: parse_common_billing_account_path = staticmethod( ApplicationsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ApplicationsClient.common_folder_path) parse_common_folder_path = staticmethod(ApplicationsClient.parse_common_folder_path) - common_organization_path = staticmethod(ApplicationsClient.common_organization_path) parse_common_organization_path = staticmethod( ApplicationsClient.parse_common_organization_path ) - common_project_path = staticmethod(ApplicationsClient.common_project_path) parse_common_project_path = staticmethod( ApplicationsClient.parse_common_project_path ) - common_location_path = staticmethod(ApplicationsClient.common_location_path) parse_common_location_path = staticmethod( ApplicationsClient.parse_common_location_path @@ -75,7 +68,8 @@ class ApplicationsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +84,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -107,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ApplicationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ApplicationsTransport: The transport used by the client instance. @@ -121,12 +115,12 @@ def transport(self) -> ApplicationsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ApplicationsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the applications client. + """Instantiates the applications client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -158,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ApplicationsClient( credentials=credentials, transport=transport, @@ -180,7 +173,6 @@ async def get_application( request (:class:`google.cloud.appengine_admin_v1.types.GetApplicationRequest`): The request object. Request message for `Applications.GetApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -195,7 +187,6 @@ async def get_application( """ # Create or coerce a protobuf request object. - request = appengine.GetApplicationRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -242,7 +233,6 @@ async def create_application( request (:class:`google.cloud.appengine_admin_v1.types.CreateApplicationRequest`): The request object. Request message for `Applications.CreateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -258,7 +248,6 @@ async def create_application( """ # Create or coerce a protobuf request object. - request = appengine.CreateApplicationRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -303,7 +292,6 @@ async def update_application( request (:class:`google.cloud.appengine_admin_v1.types.UpdateApplicationRequest`): The request object. Request message for `Applications.UpdateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -319,7 +307,6 @@ async def update_application( """ # Create or coerce a protobuf request object. - request = appengine.UpdateApplicationRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -374,7 +361,6 @@ async def repair_application( request (:class:`google.cloud.appengine_admin_v1.types.RepairApplicationRequest`): The request object. Request message for 'Applications.RepairApplication'. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -390,7 +376,6 @@ async def repair_application( """ # Create or coerce a protobuf request object. - request = appengine.RepairApplicationRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py index 36e7bbcde5e6..58a29ed103fa 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,8 +35,7 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import duration_pb2 as duration # type: ignore - +from google.protobuf import duration_pb2 # type: ignore from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ApplicationsGrpcTransport from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class ApplicationsClientMeta(type): _transport_registry["grpc_asyncio"] = ApplicationsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ApplicationsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class ApplicationsClient(metaclass=ApplicationsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ApplicationsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ApplicationsTransport: The transport used by the client instance. + ApplicationsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -172,7 +172,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -183,7 +183,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -194,7 +194,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -205,7 +205,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -219,12 +219,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ApplicationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the applications client. + """Instantiates the applications client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -279,9 +279,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -293,12 +294,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -313,8 +316,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -343,7 +346,6 @@ def get_application( request (google.cloud.appengine_admin_v1.types.GetApplicationRequest): The request object. Request message for `Applications.GetApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -358,7 +360,6 @@ def get_application( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetApplicationRequest. # There's no risk of modifying the input as we've already verified @@ -406,7 +407,6 @@ def create_application( request (google.cloud.appengine_admin_v1.types.CreateApplicationRequest): The request object. Request message for `Applications.CreateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -422,7 +422,6 @@ def create_application( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.CreateApplicationRequest. # There's no risk of modifying the input as we've already verified @@ -468,7 +467,6 @@ def update_application( request (google.cloud.appengine_admin_v1.types.UpdateApplicationRequest): The request object. Request message for `Applications.UpdateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -484,7 +482,6 @@ def update_application( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateApplicationRequest. # There's no risk of modifying the input as we've already verified @@ -540,7 +537,6 @@ def repair_application( request (google.cloud.appengine_admin_v1.types.RepairApplicationRequest): The request object. Request message for 'Applications.RepairApplication'. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -556,7 +552,6 @@ def repair_application( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.RepairApplicationRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py index 946f6e4291d0..0acb98c43e82 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/base.py index e03081a1bd23..d3873c0aeada 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ApplicationsTransport(abc.ABC): """Abstract transport class for Applications.""" @@ -50,21 +60,24 @@ class ApplicationsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -135,38 +195,36 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def get_application( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetApplicationRequest], - typing.Union[ - application.Application, typing.Awaitable[application.Application] - ], + Union[application.Application, Awaitable[application.Application]], ]: raise NotImplementedError() @property def create_application( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.CreateApplicationRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_application( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateApplicationRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def repair_application( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.RepairApplicationRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py index b18f7ed5a3b1..779505db407f 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -268,7 +268,7 @@ def get_application( @property def create_application( self, - ) -> Callable[[appengine.CreateApplicationRequest], operations.Operation]: + ) -> Callable[[appengine.CreateApplicationRequest], operations_pb2.Operation]: r"""Return a callable for the create application method over gRPC. Creates an App Engine application for a Google Cloud Platform @@ -297,14 +297,14 @@ def create_application( self._stubs["create_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/CreateApplication", request_serializer=appengine.CreateApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_application"] @property def update_application( self, - ) -> Callable[[appengine.UpdateApplicationRequest], operations.Operation]: + ) -> Callable[[appengine.UpdateApplicationRequest], operations_pb2.Operation]: r"""Return a callable for the update application method over gRPC. Updates the specified Application resource. You can update the @@ -329,14 +329,14 @@ def update_application( self._stubs["update_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/UpdateApplication", request_serializer=appengine.UpdateApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_application"] @property def repair_application( self, - ) -> Callable[[appengine.RepairApplicationRequest], operations.Operation]: + ) -> Callable[[appengine.RepairApplicationRequest], operations_pb2.Operation]: r"""Return a callable for the repair application method over gRPC. Recreates the required App Engine features for the specified App @@ -365,7 +365,7 @@ def repair_application( self._stubs["repair_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/RepairApplication", request_serializer=appengine.RepairApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["repair_application"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py index 292200001ba0..ac93ffb49146 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO from .grpc import ApplicationsGrpcTransport @@ -56,7 +53,7 @@ class ApplicationsGrpcAsyncIOTransport(ApplicationsTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -277,7 +276,7 @@ def get_application( def create_application( self, ) -> Callable[ - [appengine.CreateApplicationRequest], Awaitable[operations.Operation] + [appengine.CreateApplicationRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create application method over gRPC. @@ -307,7 +306,7 @@ def create_application( self._stubs["create_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/CreateApplication", request_serializer=appengine.CreateApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_application"] @@ -315,7 +314,7 @@ def create_application( def update_application( self, ) -> Callable[ - [appengine.UpdateApplicationRequest], Awaitable[operations.Operation] + [appengine.UpdateApplicationRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update application method over gRPC. @@ -341,7 +340,7 @@ def update_application( self._stubs["update_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/UpdateApplication", request_serializer=appengine.UpdateApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_application"] @@ -349,7 +348,7 @@ def update_application( def repair_application( self, ) -> Callable[ - [appengine.RepairApplicationRequest], Awaitable[operations.Operation] + [appengine.RepairApplicationRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the repair application method over gRPC. @@ -379,7 +378,7 @@ def repair_application( self._stubs["repair_application"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Applications/RepairApplication", request_serializer=appengine.RepairApplicationRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["repair_application"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py index 0e8d6652bd67..2fc98322b75e 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AuthorizedCertificatesClient from .async_client import AuthorizedCertificatesAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py index 7f16cd50e472..1110e385e098 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport from .client import AuthorizedCertificatesClient @@ -55,24 +52,20 @@ class AuthorizedCertificatesAsyncClient: parse_common_billing_account_path = staticmethod( AuthorizedCertificatesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AuthorizedCertificatesClient.common_folder_path) parse_common_folder_path = staticmethod( AuthorizedCertificatesClient.parse_common_folder_path ) - common_organization_path = staticmethod( AuthorizedCertificatesClient.common_organization_path ) parse_common_organization_path = staticmethod( AuthorizedCertificatesClient.parse_common_organization_path ) - common_project_path = staticmethod(AuthorizedCertificatesClient.common_project_path) parse_common_project_path = staticmethod( AuthorizedCertificatesClient.parse_common_project_path ) - common_location_path = staticmethod( AuthorizedCertificatesClient.common_location_path ) @@ -82,7 +75,8 @@ class AuthorizedCertificatesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +91,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -114,7 +108,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AuthorizedCertificatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AuthorizedCertificatesTransport: The transport used by the client instance. @@ -129,12 +123,12 @@ def transport(self) -> AuthorizedCertificatesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AuthorizedCertificatesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the authorized certificates client. + """Instantiates the authorized certificates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -166,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AuthorizedCertificatesClient( credentials=credentials, transport=transport, @@ -189,7 +182,6 @@ async def list_authorized_certificates( request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest`): The request object. Request message for `AuthorizedCertificates.ListAuthorizedCertificates`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -206,7 +198,6 @@ async def list_authorized_certificates( """ # Create or coerce a protobuf request object. - request = appengine.ListAuthorizedCertificatesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -249,7 +240,6 @@ async def get_authorized_certificate( request (:class:`google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest`): The request object. Request message for `AuthorizedCertificates.GetAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -266,7 +256,6 @@ async def get_authorized_certificate( """ # Create or coerce a protobuf request object. - request = appengine.GetAuthorizedCertificateRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -303,7 +292,6 @@ async def create_authorized_certificate( request (:class:`google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest`): The request object. Request message for `AuthorizedCertificates.CreateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -320,7 +308,6 @@ async def create_authorized_certificate( """ # Create or coerce a protobuf request object. - request = appengine.CreateAuthorizedCertificateRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -362,7 +349,6 @@ async def update_authorized_certificate( request (:class:`google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest`): The request object. Request message for `AuthorizedCertificates.UpdateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -379,7 +365,6 @@ async def update_authorized_certificate( """ # Create or coerce a protobuf request object. - request = appengine.UpdateAuthorizedCertificateRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -416,7 +401,6 @@ async def delete_authorized_certificate( request (:class:`google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest`): The request object. Request message for `AuthorizedCertificates.DeleteAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -424,7 +408,6 @@ async def delete_authorized_certificate( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - request = appengine.DeleteAuthorizedCertificateRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py index dad6dab6bf59..79bdf59488a4 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AuthorizedCertificatesGrpcTransport from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class AuthorizedCertificatesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[AuthorizedCertificatesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +82,8 @@ class AuthorizedCertificatesClient(metaclass=AuthorizedCertificatesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -119,7 +117,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +135,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,16 +154,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AuthorizedCertificatesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AuthorizedCertificatesTransport: The transport used by the client instance. + AuthorizedCertificatesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -177,7 +177,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -188,7 +188,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -199,7 +199,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -210,7 +210,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -224,12 +224,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AuthorizedCertificatesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the authorized certificates client. + """Instantiates the authorized certificates client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -284,9 +284,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -298,12 +299,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -318,8 +321,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -349,7 +352,6 @@ def list_authorized_certificates( request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): The request object. Request message for `AuthorizedCertificates.ListAuthorizedCertificates`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -366,7 +368,6 @@ def list_authorized_certificates( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListAuthorizedCertificatesRequest. # There's no risk of modifying the input as we've already verified @@ -412,7 +413,6 @@ def get_authorized_certificate( request (google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest): The request object. Request message for `AuthorizedCertificates.GetAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -429,7 +429,6 @@ def get_authorized_certificate( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetAuthorizedCertificateRequest. # There's no risk of modifying the input as we've already verified @@ -469,7 +468,6 @@ def create_authorized_certificate( request (google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest): The request object. Request message for `AuthorizedCertificates.CreateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -486,7 +484,6 @@ def create_authorized_certificate( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.CreateAuthorizedCertificateRequest. # There's no risk of modifying the input as we've already verified @@ -531,7 +528,6 @@ def update_authorized_certificate( request (google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest): The request object. Request message for `AuthorizedCertificates.UpdateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -548,7 +544,6 @@ def update_authorized_certificate( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateAuthorizedCertificateRequest. # There's no risk of modifying the input as we've already verified @@ -588,7 +583,6 @@ def delete_authorized_certificate( request (google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest): The request object. Request message for `AuthorizedCertificates.DeleteAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -596,7 +590,6 @@ def delete_authorized_certificate( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteAuthorizedCertificateRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py index 24d981953a2d..25f943dd8909 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py index 6ba068cec86c..c273e23d7c90 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py index 1da6da0b3e67..0f5102fef06f 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AuthorizedCertificatesTransport(abc.ABC): """Abstract transport class for AuthorizedCertificates.""" @@ -49,21 +59,24 @@ class AuthorizedCertificatesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -142,11 +202,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_authorized_certificates( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListAuthorizedCertificatesRequest], - typing.Union[ + Union[ appengine.ListAuthorizedCertificatesResponse, - typing.Awaitable[appengine.ListAuthorizedCertificatesResponse], + Awaitable[appengine.ListAuthorizedCertificatesResponse], ], ]: raise NotImplementedError() @@ -154,11 +214,11 @@ def list_authorized_certificates( @property def get_authorized_certificate( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetAuthorizedCertificateRequest], - typing.Union[ + Union[ certificate.AuthorizedCertificate, - typing.Awaitable[certificate.AuthorizedCertificate], + Awaitable[certificate.AuthorizedCertificate], ], ]: raise NotImplementedError() @@ -166,11 +226,11 @@ def get_authorized_certificate( @property def create_authorized_certificate( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.CreateAuthorizedCertificateRequest], - typing.Union[ + Union[ certificate.AuthorizedCertificate, - typing.Awaitable[certificate.AuthorizedCertificate], + Awaitable[certificate.AuthorizedCertificate], ], ]: raise NotImplementedError() @@ -178,11 +238,11 @@ def create_authorized_certificate( @property def update_authorized_certificate( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateAuthorizedCertificateRequest], - typing.Union[ + Union[ certificate.AuthorizedCertificate, - typing.Awaitable[certificate.AuthorizedCertificate], + Awaitable[certificate.AuthorizedCertificate], ], ]: raise NotImplementedError() @@ -190,9 +250,9 @@ def update_authorized_certificate( @property def delete_authorized_certificate( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteAuthorizedCertificateRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py index ae2731551b67..41269641d9ab 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -353,7 +353,7 @@ def update_authorized_certificate( @property def delete_authorized_certificate( self, - ) -> Callable[[appengine.DeleteAuthorizedCertificateRequest], empty.Empty]: + ) -> Callable[[appengine.DeleteAuthorizedCertificateRequest], empty_pb2.Empty]: r"""Return a callable for the delete authorized certificate method over gRPC. Deletes the specified SSL certificate. @@ -374,7 +374,7 @@ def delete_authorized_certificate( ] = self.grpc_channel.unary_unary( "/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate", request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_authorized_certificate"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py index 1e6467b25b41..2646f059670f 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO from .grpc import AuthorizedCertificatesGrpcTransport @@ -57,7 +54,7 @@ class AuthorizedCertificatesGrpcAsyncIOTransport(AuthorizedCertificatesTransport def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -359,7 +358,7 @@ def update_authorized_certificate( def delete_authorized_certificate( self, ) -> Callable[ - [appengine.DeleteAuthorizedCertificateRequest], Awaitable[empty.Empty] + [appengine.DeleteAuthorizedCertificateRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete authorized certificate method over gRPC. @@ -381,7 +380,7 @@ def delete_authorized_certificate( ] = self.grpc_channel.unary_unary( "/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate", request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_authorized_certificate"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py index 61c9194ab8ad..f8ce19e95e1c 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AuthorizedDomainsClient from .async_client import AuthorizedDomainsAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py index 2d3a6a47c302..cba0655e808e 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.appengine_admin_v1.services.authorized_domains import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain - from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport from .client import AuthorizedDomainsClient @@ -54,24 +51,20 @@ class AuthorizedDomainsAsyncClient: parse_common_billing_account_path = staticmethod( AuthorizedDomainsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AuthorizedDomainsClient.common_folder_path) parse_common_folder_path = staticmethod( AuthorizedDomainsClient.parse_common_folder_path ) - common_organization_path = staticmethod( AuthorizedDomainsClient.common_organization_path ) parse_common_organization_path = staticmethod( AuthorizedDomainsClient.parse_common_organization_path ) - common_project_path = staticmethod(AuthorizedDomainsClient.common_project_path) parse_common_project_path = staticmethod( AuthorizedDomainsClient.parse_common_project_path ) - common_location_path = staticmethod(AuthorizedDomainsClient.common_location_path) parse_common_location_path = staticmethod( AuthorizedDomainsClient.parse_common_location_path @@ -79,7 +72,8 @@ class AuthorizedDomainsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -94,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -111,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AuthorizedDomainsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AuthorizedDomainsTransport: The transport used by the client instance. @@ -125,12 +119,12 @@ def transport(self) -> AuthorizedDomainsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AuthorizedDomainsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the authorized domains client. + """Instantiates the authorized domains client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AuthorizedDomainsClient( credentials=credentials, transport=transport, @@ -185,7 +178,6 @@ async def list_authorized_domains( request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest`): The request object. Request message for `AuthorizedDomains.ListAuthorizedDomains`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -202,7 +194,6 @@ async def list_authorized_domains( """ # Create or coerce a protobuf request object. - request = appengine.ListAuthorizedDomainsRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py index 91b4e68ca265..c427da1a56bb 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,7 +33,6 @@ from google.cloud.appengine_admin_v1.services.authorized_domains import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain - from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AuthorizedDomainsGrpcTransport from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class AuthorizedDomainsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[AuthorizedDomainsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class AuthorizedDomainsClient(metaclass=AuthorizedDomainsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,16 +153,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AuthorizedDomainsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AuthorizedDomainsTransport: The transport used by the client instance. + AuthorizedDomainsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -176,7 +176,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -187,7 +187,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -198,7 +198,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -209,7 +209,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -223,12 +223,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AuthorizedDomainsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the authorized domains client. + """Instantiates the authorized domains client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -283,9 +283,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -297,12 +298,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -317,8 +320,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -348,7 +351,6 @@ def list_authorized_domains( request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): The request object. Request message for `AuthorizedDomains.ListAuthorizedDomains`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -365,7 +367,6 @@ def list_authorized_domains( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListAuthorizedDomainsRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py index 2d3a650406c2..5d34d4759eef 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py index fbd760d46d88..e602ae68e75e 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py index d2555acc89de..7af208144f74 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AuthorizedDomainsTransport(abc.ABC): """Abstract transport class for AuthorizedDomains.""" @@ -47,21 +57,24 @@ class AuthorizedDomainsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -70,7 +83,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,11 +180,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_authorized_domains( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListAuthorizedDomainsRequest], - typing.Union[ + Union[ appengine.ListAuthorizedDomainsResponse, - typing.Awaitable[appengine.ListAuthorizedDomainsResponse], + Awaitable[appengine.ListAuthorizedDomainsResponse], ], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py index 9a29baeef4f5..e94675702645 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine - from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py index cae7fc5c710d..25da7193563a 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine - from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO from .grpc import AuthorizedDomainsGrpcTransport @@ -55,7 +52,7 @@ class AuthorizedDomainsGrpcAsyncIOTransport(AuthorizedDomainsTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py index 2d1c70921432..a05b43be6738 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import DomainMappingsClient from .async_client import DomainMappingsAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py index fc4c406a4aed..7bd11b6347a3 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation as gac_operation # type: ignore @@ -34,8 +32,7 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport from .client import DomainMappingsClient @@ -55,24 +52,20 @@ class DomainMappingsAsyncClient: parse_common_billing_account_path = staticmethod( DomainMappingsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DomainMappingsClient.common_folder_path) parse_common_folder_path = staticmethod( DomainMappingsClient.parse_common_folder_path ) - common_organization_path = staticmethod( DomainMappingsClient.common_organization_path ) parse_common_organization_path = staticmethod( DomainMappingsClient.parse_common_organization_path ) - common_project_path = staticmethod(DomainMappingsClient.common_project_path) parse_common_project_path = staticmethod( DomainMappingsClient.parse_common_project_path ) - common_location_path = staticmethod(DomainMappingsClient.common_location_path) parse_common_location_path = staticmethod( DomainMappingsClient.parse_common_location_path @@ -80,7 +73,8 @@ class DomainMappingsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DomainMappingsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: DomainMappingsTransport: The transport used by the client instance. @@ -126,12 +120,12 @@ def transport(self) -> DomainMappingsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DomainMappingsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the domain mappings client. + """Instantiates the domain mappings client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DomainMappingsClient( credentials=credentials, transport=transport, @@ -185,7 +178,6 @@ async def list_domain_mappings( request (:class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest`): The request object. Request message for `DomainMappings.ListDomainMappings`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -201,7 +193,6 @@ async def list_domain_mappings( """ # Create or coerce a protobuf request object. - request = appengine.ListDomainMappingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -244,7 +235,6 @@ async def get_domain_mapping( request (:class:`google.cloud.appengine_admin_v1.types.GetDomainMappingRequest`): The request object. Request message for `DomainMappings.GetDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -258,7 +248,6 @@ async def get_domain_mapping( """ # Create or coerce a protobuf request object. - request = appengine.GetDomainMappingRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -298,7 +287,6 @@ async def create_domain_mapping( request (:class:`google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest`): The request object. Request message for `DomainMappings.CreateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -315,7 +303,6 @@ async def create_domain_mapping( """ # Create or coerce a protobuf request object. - request = appengine.CreateDomainMappingRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -364,7 +351,6 @@ async def update_domain_mapping( request (:class:`google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest`): The request object. Request message for `DomainMappings.UpdateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -381,7 +367,6 @@ async def update_domain_mapping( """ # Create or coerce a protobuf request object. - request = appengine.UpdateDomainMappingRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -428,7 +413,6 @@ async def delete_domain_mapping( request (:class:`google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest`): The request object. Request message for `DomainMappings.DeleteDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -455,7 +439,6 @@ async def delete_domain_mapping( """ # Create or coerce a protobuf request object. - request = appengine.DeleteDomainMappingRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -479,7 +462,7 @@ async def delete_domain_mapping( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py index 569b272acfb3..01ca9eb5fbf4 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,8 +36,7 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DomainMappingsGrpcTransport from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class DomainMappingsClientMeta(type): _transport_registry["grpc_asyncio"] = DomainMappingsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[DomainMappingsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class DomainMappingsClient(metaclass=DomainMappingsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,16 +152,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> DomainMappingsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - DomainMappingsTransport: The transport used by the client instance. + DomainMappingsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -175,7 +175,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -186,7 +186,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -197,7 +197,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -208,7 +208,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -222,12 +222,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, DomainMappingsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the domain mappings client. + """Instantiates the domain mappings client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -282,9 +282,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -296,12 +297,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -316,8 +319,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -346,7 +349,6 @@ def list_domain_mappings( request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): The request object. Request message for `DomainMappings.ListDomainMappings`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -362,7 +364,6 @@ def list_domain_mappings( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListDomainMappingsRequest. # There's no risk of modifying the input as we've already verified @@ -406,7 +407,6 @@ def get_domain_mapping( request (google.cloud.appengine_admin_v1.types.GetDomainMappingRequest): The request object. Request message for `DomainMappings.GetDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -420,7 +420,6 @@ def get_domain_mapping( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetDomainMappingRequest. # There's no risk of modifying the input as we've already verified @@ -461,7 +460,6 @@ def create_domain_mapping( request (google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest): The request object. Request message for `DomainMappings.CreateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -478,7 +476,6 @@ def create_domain_mapping( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.CreateDomainMappingRequest. # There's no risk of modifying the input as we've already verified @@ -528,7 +525,6 @@ def update_domain_mapping( request (google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest): The request object. Request message for `DomainMappings.UpdateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -545,7 +541,6 @@ def update_domain_mapping( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateDomainMappingRequest. # There's no risk of modifying the input as we've already verified @@ -593,7 +588,6 @@ def delete_domain_mapping( request (google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest): The request object. Request message for `DomainMappings.DeleteDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -620,7 +614,6 @@ def delete_domain_mapping( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteDomainMappingRequest. # There's no risk of modifying the input as we've already verified @@ -645,7 +638,7 @@ def delete_domain_mapping( response = gac_operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py index 2ff7e223ccaf..478312d10da4 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py index 39be11cac722..aa6671df43dc 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py index a80a7064d2eb..6e109872599a 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class DomainMappingsTransport(abc.ABC): """Abstract transport class for DomainMappings.""" @@ -50,21 +60,24 @@ class DomainMappingsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -146,11 +206,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_domain_mappings( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListDomainMappingsRequest], - typing.Union[ + Union[ appengine.ListDomainMappingsResponse, - typing.Awaitable[appengine.ListDomainMappingsResponse], + Awaitable[appengine.ListDomainMappingsResponse], ], ]: raise NotImplementedError() @@ -158,38 +218,36 @@ def list_domain_mappings( @property def get_domain_mapping( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetDomainMappingRequest], - typing.Union[ - domain_mapping.DomainMapping, typing.Awaitable[domain_mapping.DomainMapping] - ], + Union[domain_mapping.DomainMapping, Awaitable[domain_mapping.DomainMapping]], ]: raise NotImplementedError() @property def create_domain_mapping( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.CreateDomainMappingRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_domain_mapping( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateDomainMappingRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_domain_mapping( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteDomainMappingRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py index 2ceae214ee7b..2bfa1a835a8c 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -296,7 +296,7 @@ def get_domain_mapping( @property def create_domain_mapping( self, - ) -> Callable[[appengine.CreateDomainMappingRequest], operations.Operation]: + ) -> Callable[[appengine.CreateDomainMappingRequest], operations_pb2.Operation]: r"""Return a callable for the create domain mapping method over gRPC. Maps a domain to an application. A user must be authorized to @@ -318,14 +318,14 @@ def create_domain_mapping( self._stubs["create_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/CreateDomainMapping", request_serializer=appengine.CreateDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_domain_mapping"] @property def update_domain_mapping( self, - ) -> Callable[[appengine.UpdateDomainMappingRequest], operations.Operation]: + ) -> Callable[[appengine.UpdateDomainMappingRequest], operations_pb2.Operation]: r"""Return a callable for the update domain mapping method over gRPC. Updates the specified domain mapping. To map an SSL certificate @@ -348,14 +348,14 @@ def update_domain_mapping( self._stubs["update_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/UpdateDomainMapping", request_serializer=appengine.UpdateDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_domain_mapping"] @property def delete_domain_mapping( self, - ) -> Callable[[appengine.DeleteDomainMappingRequest], operations.Operation]: + ) -> Callable[[appengine.DeleteDomainMappingRequest], operations_pb2.Operation]: r"""Return a callable for the delete domain mapping method over gRPC. Deletes the specified domain mapping. A user must be authorized @@ -376,7 +376,7 @@ def delete_domain_mapping( self._stubs["delete_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/DeleteDomainMapping", request_serializer=appengine.DeleteDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_domain_mapping"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py index 15c769c4c49b..b4ed8d377752 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO from .grpc import DomainMappingsGrpcTransport @@ -56,7 +53,7 @@ class DomainMappingsGrpcAsyncIOTransport(DomainMappingsTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -306,7 +305,7 @@ def get_domain_mapping( def create_domain_mapping( self, ) -> Callable[ - [appengine.CreateDomainMappingRequest], Awaitable[operations.Operation] + [appengine.CreateDomainMappingRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create domain mapping method over gRPC. @@ -329,7 +328,7 @@ def create_domain_mapping( self._stubs["create_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/CreateDomainMapping", request_serializer=appengine.CreateDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_domain_mapping"] @@ -337,7 +336,7 @@ def create_domain_mapping( def update_domain_mapping( self, ) -> Callable[ - [appengine.UpdateDomainMappingRequest], Awaitable[operations.Operation] + [appengine.UpdateDomainMappingRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update domain mapping method over gRPC. @@ -361,7 +360,7 @@ def update_domain_mapping( self._stubs["update_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/UpdateDomainMapping", request_serializer=appengine.UpdateDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_domain_mapping"] @@ -369,7 +368,7 @@ def update_domain_mapping( def delete_domain_mapping( self, ) -> Callable[ - [appengine.DeleteDomainMappingRequest], Awaitable[operations.Operation] + [appengine.DeleteDomainMappingRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the delete domain mapping method over gRPC. @@ -391,7 +390,7 @@ def delete_domain_mapping( self._stubs["delete_domain_mapping"] = self.grpc_channel.unary_unary( "/google.appengine.v1.DomainMappings/DeleteDomainMapping", request_serializer=appengine.DeleteDomainMappingRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_domain_mapping"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/__init__.py index 25db5e3df880..a240af001f2f 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import FirewallClient from .async_client import FirewallAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/async_client.py index cc22d8821d3c..fe8786f30a7d 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.appengine_admin_v1.services.firewall import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall - from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport from .client import FirewallClient @@ -62,24 +59,21 @@ class FirewallAsyncClient: parse_common_billing_account_path = staticmethod( FirewallClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(FirewallClient.common_folder_path) parse_common_folder_path = staticmethod(FirewallClient.parse_common_folder_path) - common_organization_path = staticmethod(FirewallClient.common_organization_path) parse_common_organization_path = staticmethod( FirewallClient.parse_common_organization_path ) - common_project_path = staticmethod(FirewallClient.common_project_path) parse_common_project_path = staticmethod(FirewallClient.parse_common_project_path) - common_location_path = staticmethod(FirewallClient.common_location_path) parse_common_location_path = staticmethod(FirewallClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -94,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -111,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FirewallTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: FirewallTransport: The transport used by the client instance. @@ -125,12 +119,12 @@ def transport(self) -> FirewallTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, FirewallTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the firewall client. + """Instantiates the firewall client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = FirewallClient( credentials=credentials, transport=transport, @@ -184,7 +177,6 @@ async def list_ingress_rules( request (:class:`google.cloud.appengine_admin_v1.types.ListIngressRulesRequest`): The request object. Request message for `Firewall.ListIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -200,7 +192,6 @@ async def list_ingress_rules( """ # Create or coerce a protobuf request object. - request = appengine.ListIngressRulesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -249,7 +240,6 @@ async def batch_update_ingress_rules( request (:class:`google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest`): The request object. Request message for `Firewall.BatchUpdateIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -261,7 +251,6 @@ async def batch_update_ingress_rules( Response message for Firewall.UpdateAllIngressRules. """ # Create or coerce a protobuf request object. - request = appengine.BatchUpdateIngressRulesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -298,7 +287,6 @@ async def create_ingress_rule( request (:class:`google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest`): The request object. Request message for `Firewall.CreateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -314,7 +302,6 @@ async def create_ingress_rule( """ # Create or coerce a protobuf request object. - request = appengine.CreateIngressRuleRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -351,7 +338,6 @@ async def get_ingress_rule( request (:class:`google.cloud.appengine_admin_v1.types.GetIngressRuleRequest`): The request object. Request message for `Firewall.GetIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -367,7 +353,6 @@ async def get_ingress_rule( """ # Create or coerce a protobuf request object. - request = appengine.GetIngressRuleRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -404,7 +389,6 @@ async def update_ingress_rule( request (:class:`google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest`): The request object. Request message for `Firewall.UpdateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -420,7 +404,6 @@ async def update_ingress_rule( """ # Create or coerce a protobuf request object. - request = appengine.UpdateIngressRuleRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -457,7 +440,6 @@ async def delete_ingress_rule( request (:class:`google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest`): The request object. Request message for `Firewall.DeleteIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -465,7 +447,6 @@ async def delete_ingress_rule( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - request = appengine.DeleteIngressRuleRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py index e1705516f211..ba7b180a0435 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,7 +33,6 @@ from google.cloud.appengine_admin_v1.services.firewall import pagers from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall - from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FirewallGrpcTransport from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class FirewallClientMeta(type): _transport_registry["grpc_asyncio"] = FirewallGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[FirewallTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class FirewallClient(metaclass=FirewallClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,16 +157,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FirewallTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - FirewallTransport: The transport used by the client instance. + FirewallTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -180,7 +180,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -191,7 +191,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -227,12 +227,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, FirewallTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the firewall client. + """Instantiates the firewall client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -287,9 +287,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -301,12 +302,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -321,8 +324,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -351,7 +354,6 @@ def list_ingress_rules( request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): The request object. Request message for `Firewall.ListIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -367,7 +369,6 @@ def list_ingress_rules( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListIngressRulesRequest. # There's no risk of modifying the input as we've already verified @@ -417,7 +418,6 @@ def batch_update_ingress_rules( request (google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest): The request object. Request message for `Firewall.BatchUpdateIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -429,7 +429,6 @@ def batch_update_ingress_rules( Response message for Firewall.UpdateAllIngressRules. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.BatchUpdateIngressRulesRequest. # There's no risk of modifying the input as we've already verified @@ -469,7 +468,6 @@ def create_ingress_rule( request (google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest): The request object. Request message for `Firewall.CreateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -485,7 +483,6 @@ def create_ingress_rule( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.CreateIngressRuleRequest. # There's no risk of modifying the input as we've already verified @@ -523,7 +520,6 @@ def get_ingress_rule( request (google.cloud.appengine_admin_v1.types.GetIngressRuleRequest): The request object. Request message for `Firewall.GetIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -539,7 +535,6 @@ def get_ingress_rule( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetIngressRuleRequest. # There's no risk of modifying the input as we've already verified @@ -577,7 +572,6 @@ def update_ingress_rule( request (google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest): The request object. Request message for `Firewall.UpdateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -593,7 +587,6 @@ def update_ingress_rule( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateIngressRuleRequest. # There's no risk of modifying the input as we've already verified @@ -631,7 +624,6 @@ def delete_ingress_rule( request (google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest): The request object. Request message for `Firewall.DeleteIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -639,7 +631,6 @@ def delete_ingress_rule( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteIngressRuleRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/pagers.py index 27838be1bc2a..81f2787bc4f7 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py index a82dfe0a6809..dc4aacde42a1 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/base.py index a8ad7f8b16c3..c34954b779bc 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class FirewallTransport(abc.ABC): """Abstract transport class for Firewall.""" @@ -49,21 +59,24 @@ class FirewallTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -72,7 +85,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -137,11 +197,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_ingress_rules( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListIngressRulesRequest], - typing.Union[ + Union[ appengine.ListIngressRulesResponse, - typing.Awaitable[appengine.ListIngressRulesResponse], + Awaitable[appengine.ListIngressRulesResponse], ], ]: raise NotImplementedError() @@ -149,11 +209,11 @@ def list_ingress_rules( @property def batch_update_ingress_rules( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.BatchUpdateIngressRulesRequest], - typing.Union[ + Union[ appengine.BatchUpdateIngressRulesResponse, - typing.Awaitable[appengine.BatchUpdateIngressRulesResponse], + Awaitable[appengine.BatchUpdateIngressRulesResponse], ], ]: raise NotImplementedError() @@ -161,36 +221,36 @@ def batch_update_ingress_rules( @property def create_ingress_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.CreateIngressRuleRequest], - typing.Union[firewall.FirewallRule, typing.Awaitable[firewall.FirewallRule]], + Union[firewall.FirewallRule, Awaitable[firewall.FirewallRule]], ]: raise NotImplementedError() @property def get_ingress_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetIngressRuleRequest], - typing.Union[firewall.FirewallRule, typing.Awaitable[firewall.FirewallRule]], + Union[firewall.FirewallRule, Awaitable[firewall.FirewallRule]], ]: raise NotImplementedError() @property def update_ingress_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateIngressRuleRequest], - typing.Union[firewall.FirewallRule, typing.Awaitable[firewall.FirewallRule]], + Union[firewall.FirewallRule, Awaitable[firewall.FirewallRule]], ]: raise NotImplementedError() @property def delete_ingress_rule( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteIngressRuleRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py index 968c259158b7..0800f201f6b1 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import FirewallTransport, DEFAULT_CLIENT_INFO @@ -62,7 +59,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -76,7 +73,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -186,7 +184,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -217,13 +215,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -377,7 +377,7 @@ def update_ingress_rule( @property def delete_ingress_rule( self, - ) -> Callable[[appengine.DeleteIngressRuleRequest], empty.Empty]: + ) -> Callable[[appengine.DeleteIngressRuleRequest], empty_pb2.Empty]: r"""Return a callable for the delete ingress rule method over gRPC. Deletes the specified firewall rule. @@ -396,7 +396,7 @@ def delete_ingress_rule( self._stubs["delete_ingress_rule"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Firewall/DeleteIngressRule", request_serializer=appengine.DeleteIngressRuleRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_ingress_rule"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py index 29c4f2f78ce1..854586afb6a7 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import FirewallTransport, DEFAULT_CLIENT_INFO from .grpc import FirewallGrpcTransport @@ -65,7 +62,7 @@ class FirewallGrpcAsyncIOTransport(FirewallTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -92,13 +89,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -106,7 +105,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -120,7 +119,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +178,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -386,7 +385,7 @@ def update_ingress_rule( @property def delete_ingress_rule( self, - ) -> Callable[[appengine.DeleteIngressRuleRequest], Awaitable[empty.Empty]]: + ) -> Callable[[appengine.DeleteIngressRuleRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete ingress rule method over gRPC. Deletes the specified firewall rule. @@ -405,7 +404,7 @@ def delete_ingress_rule( self._stubs["delete_ingress_rule"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Firewall/DeleteIngressRule", request_serializer=appengine.DeleteIngressRuleRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_ingress_rule"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/__init__.py index 5eeb8a057807..9e55542aafc1 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import InstancesClient from .async_client import InstancesAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/async_client.py index f1fc7efc98c4..9033e01261ca 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation as gac_operation # type: ignore @@ -34,9 +32,8 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport from .client import InstancesClient @@ -52,25 +49,20 @@ class InstancesAsyncClient: instance_path = staticmethod(InstancesClient.instance_path) parse_instance_path = staticmethod(InstancesClient.parse_instance_path) - common_billing_account_path = staticmethod( InstancesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( InstancesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(InstancesClient.common_folder_path) parse_common_folder_path = staticmethod(InstancesClient.parse_common_folder_path) - common_organization_path = staticmethod(InstancesClient.common_organization_path) parse_common_organization_path = staticmethod( InstancesClient.parse_common_organization_path ) - common_project_path = staticmethod(InstancesClient.common_project_path) parse_common_project_path = staticmethod(InstancesClient.parse_common_project_path) - common_location_path = staticmethod(InstancesClient.common_location_path) parse_common_location_path = staticmethod( InstancesClient.parse_common_location_path @@ -78,7 +70,8 @@ class InstancesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -93,7 +86,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -110,7 +103,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstancesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: InstancesTransport: The transport used by the client instance. @@ -124,12 +117,12 @@ def transport(self) -> InstancesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, InstancesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instances client. + """Instantiates the instances client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -161,7 +154,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = InstancesClient( credentials=credentials, transport=transport, @@ -187,7 +179,6 @@ async def list_instances( request (:class:`google.cloud.appengine_admin_v1.types.ListInstancesRequest`): The request object. Request message for `Instances.ListInstances`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -203,7 +194,6 @@ async def list_instances( """ # Create or coerce a protobuf request object. - request = appengine.ListInstancesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -246,7 +236,6 @@ async def get_instance( request (:class:`google.cloud.appengine_admin_v1.types.GetInstanceRequest`): The request object. Request message for `Instances.GetInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -261,7 +250,6 @@ async def get_instance( """ # Create or coerce a protobuf request object. - request = appengine.GetInstanceRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -312,7 +300,6 @@ async def delete_instance( request (:class:`google.cloud.appengine_admin_v1.types.DeleteInstanceRequest`): The request object. Request message for `Instances.DeleteInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -339,7 +326,6 @@ async def delete_instance( """ # Create or coerce a protobuf request object. - request = appengine.DeleteInstanceRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -363,7 +349,7 @@ async def delete_instance( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) @@ -393,7 +379,6 @@ async def debug_instance( request (:class:`google.cloud.appengine_admin_v1.types.DebugInstanceRequest`): The request object. Request message for `Instances.DebugInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -409,7 +394,6 @@ async def debug_instance( """ # Create or coerce a protobuf request object. - request = appengine.DebugInstanceRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py index e2d12f3f4c12..d8348367f885 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -38,9 +36,8 @@ from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import InstancesGrpcTransport from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class InstancesClientMeta(type): _transport_registry["grpc_asyncio"] = InstancesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[InstancesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class InstancesClient(metaclass=InstancesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,23 +151,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> InstancesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - InstancesTransport: The transport used by the client instance. + InstancesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def instance_path(app: str, service: str, version: str, instance: str,) -> str: - """Return a fully-qualified instance string.""" + """Returns a fully-qualified instance string.""" return "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format( app=app, service=service, version=version, instance=instance, ) @staticmethod def parse_instance_path(path: str) -> Dict[str, str]: - """Parse a instance path into its component segments.""" + """Parses a instance path into its component segments.""" m = re.match( r"^apps/(?P.+?)/services/(?P.+?)/versions/(?P.+?)/instances/(?P.+?)$", path, @@ -177,7 +177,7 @@ def parse_instance_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -190,7 +190,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -201,7 +201,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -237,12 +237,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, InstancesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the instances client. + """Instantiates the instances client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -297,9 +297,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -311,12 +312,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -331,8 +334,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -365,7 +368,6 @@ def list_instances( request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): The request object. Request message for `Instances.ListInstances`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -381,7 +383,6 @@ def list_instances( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListInstancesRequest. # There's no risk of modifying the input as we've already verified @@ -425,7 +426,6 @@ def get_instance( request (google.cloud.appengine_admin_v1.types.GetInstanceRequest): The request object. Request message for `Instances.GetInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -440,7 +440,6 @@ def get_instance( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetInstanceRequest. # There's no risk of modifying the input as we've already verified @@ -492,7 +491,6 @@ def delete_instance( request (google.cloud.appengine_admin_v1.types.DeleteInstanceRequest): The request object. Request message for `Instances.DeleteInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -519,7 +517,6 @@ def delete_instance( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteInstanceRequest. # There's no risk of modifying the input as we've already verified @@ -544,7 +541,7 @@ def delete_instance( response = gac_operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) @@ -574,7 +571,6 @@ def debug_instance( request (google.cloud.appengine_admin_v1.types.DebugInstanceRequest): The request object. Request message for `Instances.DebugInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -590,7 +586,6 @@ def debug_instance( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DebugInstanceRequest. # There's no risk of modifying the input as we've already verified diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/pagers.py index 56421e69a62c..44090c25e28a 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py index 0f3cd9355482..7ff9ef5db7f5 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/base.py index 0d375bf2ec4d..9fbb973bce88 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class InstancesTransport(abc.ABC): """Abstract transport class for Instances.""" @@ -50,21 +60,24 @@ class InstancesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -135,11 +195,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_instances( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListInstancesRequest], - typing.Union[ - appengine.ListInstancesResponse, - typing.Awaitable[appengine.ListInstancesResponse], + Union[ + appengine.ListInstancesResponse, Awaitable[appengine.ListInstancesResponse] ], ]: raise NotImplementedError() @@ -147,27 +206,27 @@ def list_instances( @property def get_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetInstanceRequest], - typing.Union[instance.Instance, typing.Awaitable[instance.Instance]], + Union[instance.Instance, Awaitable[instance.Instance]], ]: raise NotImplementedError() @property def delete_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteInstanceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def debug_instance( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DebugInstanceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py index 44c0c8536d04..826c415cac16 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import InstancesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -298,7 +298,7 @@ def get_instance( @property def delete_instance( self, - ) -> Callable[[appengine.DeleteInstanceRequest], operations.Operation]: + ) -> Callable[[appengine.DeleteInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the delete instance method over gRPC. Stops a running instance. @@ -331,14 +331,14 @@ def delete_instance( self._stubs["delete_instance"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Instances/DeleteInstance", request_serializer=appengine.DeleteInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_instance"] @property def debug_instance( self, - ) -> Callable[[appengine.DebugInstanceRequest], operations.Operation]: + ) -> Callable[[appengine.DebugInstanceRequest], operations_pb2.Operation]: r"""Return a callable for the debug instance method over gRPC. Enables debugging on a VM instance. This allows you @@ -366,7 +366,7 @@ def debug_instance( self._stubs["debug_instance"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Instances/DebugInstance", request_serializer=appengine.DebugInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["debug_instance"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py index bb55f69a3d8c..5c50a4153c54 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import InstancesTransport, DEFAULT_CLIENT_INFO from .grpc import InstancesGrpcTransport @@ -56,7 +53,7 @@ class InstancesGrpcAsyncIOTransport(InstancesTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -306,7 +305,9 @@ def get_instance( @property def delete_instance( self, - ) -> Callable[[appengine.DeleteInstanceRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.DeleteInstanceRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete instance method over gRPC. Stops a running instance. @@ -339,14 +340,16 @@ def delete_instance( self._stubs["delete_instance"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Instances/DeleteInstance", request_serializer=appengine.DeleteInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_instance"] @property def debug_instance( self, - ) -> Callable[[appengine.DebugInstanceRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.DebugInstanceRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the debug instance method over gRPC. Enables debugging on a VM instance. This allows you @@ -374,7 +377,7 @@ def debug_instance( self._stubs["debug_instance"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Instances/DebugInstance", request_serializer=appengine.DebugInstanceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["debug_instance"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/__init__.py index 5b3c6b076d88..b902b99fec12 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ServicesClient from .async_client import ServicesAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/async_client.py index 2e804af6b475..56ef3f99ff43 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation as gac_operation # type: ignore @@ -35,8 +33,7 @@ from google.cloud.appengine_admin_v1.types import network_settings from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.cloud.appengine_admin_v1.types import service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport from .client import ServicesClient @@ -56,24 +53,21 @@ class ServicesAsyncClient: parse_common_billing_account_path = staticmethod( ServicesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ServicesClient.common_folder_path) parse_common_folder_path = staticmethod(ServicesClient.parse_common_folder_path) - common_organization_path = staticmethod(ServicesClient.common_organization_path) parse_common_organization_path = staticmethod( ServicesClient.parse_common_organization_path ) - common_project_path = staticmethod(ServicesClient.common_project_path) parse_common_project_path = staticmethod(ServicesClient.parse_common_project_path) - common_location_path = staticmethod(ServicesClient.common_location_path) parse_common_location_path = staticmethod(ServicesClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -88,7 +82,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -105,7 +99,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ServicesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ServicesTransport: The transport used by the client instance. @@ -119,12 +113,12 @@ def transport(self) -> ServicesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ServicesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the services client. + """Instantiates the services client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -156,7 +150,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ServicesClient( credentials=credentials, transport=transport, @@ -178,7 +171,6 @@ async def list_services( request (:class:`google.cloud.appengine_admin_v1.types.ListServicesRequest`): The request object. Request message for `Services.ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -194,7 +186,6 @@ async def list_services( """ # Create or coerce a protobuf request object. - request = appengine.ListServicesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -238,7 +229,6 @@ async def get_service( request (:class:`google.cloud.appengine_admin_v1.types.GetServiceRequest`): The request object. Request message for `Services.GetService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -262,7 +252,6 @@ async def get_service( """ # Create or coerce a protobuf request object. - request = appengine.GetServiceRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -299,7 +288,6 @@ async def update_service( request (:class:`google.cloud.appengine_admin_v1.types.UpdateServiceRequest`): The request object. Request message for `Services.UpdateService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -322,7 +310,6 @@ async def update_service( """ # Create or coerce a protobuf request object. - request = appengine.UpdateServiceRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -368,7 +355,6 @@ async def delete_service( request (:class:`google.cloud.appengine_admin_v1.types.DeleteServiceRequest`): The request object. Request message for `Services.DeleteService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -395,7 +381,6 @@ async def delete_service( """ # Create or coerce a protobuf request object. - request = appengine.DeleteServiceRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -419,7 +404,7 @@ async def delete_service( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py index 5623ace16504..7f20d3177293 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -39,8 +37,7 @@ from google.cloud.appengine_admin_v1.types import network_settings from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.cloud.appengine_admin_v1.types import service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ServicesGrpcTransport from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class ServicesClientMeta(type): _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ServicesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class ServicesClient(metaclass=ServicesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,16 +151,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ServicesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ServicesTransport: The transport used by the client instance. + ServicesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -174,7 +174,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -185,7 +185,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -196,7 +196,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -207,7 +207,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,12 +221,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ServicesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the services client. + """Instantiates the services client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -281,9 +281,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -295,12 +296,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -315,8 +318,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -345,7 +348,6 @@ def list_services( request (google.cloud.appengine_admin_v1.types.ListServicesRequest): The request object. Request message for `Services.ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -361,7 +363,6 @@ def list_services( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListServicesRequest. # There's no risk of modifying the input as we've already verified @@ -406,7 +407,6 @@ def get_service( request (google.cloud.appengine_admin_v1.types.GetServiceRequest): The request object. Request message for `Services.GetService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -430,7 +430,6 @@ def get_service( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetServiceRequest. # There's no risk of modifying the input as we've already verified @@ -468,7 +467,6 @@ def update_service( request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): The request object. Request message for `Services.UpdateService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -491,7 +489,6 @@ def update_service( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateServiceRequest. # There's no risk of modifying the input as we've already verified @@ -538,7 +535,6 @@ def delete_service( request (google.cloud.appengine_admin_v1.types.DeleteServiceRequest): The request object. Request message for `Services.DeleteService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -565,7 +561,6 @@ def delete_service( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteServiceRequest. # There's no risk of modifying the input as we've already verified @@ -590,7 +585,7 @@ def delete_service( response = gac_operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/pagers.py index 78e8351640e9..8d17befe4f79 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/__init__.py index 2e08960ff823..6e8aa5c53e98 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/base.py index 2b247bfc1bfe..d38384cdcb10 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ServicesTransport(abc.ABC): """Abstract transport class for Services.""" @@ -50,21 +60,24 @@ class ServicesTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -135,11 +195,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_services( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListServicesRequest], - typing.Union[ - appengine.ListServicesResponse, - typing.Awaitable[appengine.ListServicesResponse], + Union[ + appengine.ListServicesResponse, Awaitable[appengine.ListServicesResponse] ], ]: raise NotImplementedError() @@ -147,27 +206,27 @@ def list_services( @property def get_service( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetServiceRequest], - typing.Union[service.Service, typing.Awaitable[service.Service]], + Union[service.Service, Awaitable[service.Service]], ]: raise NotImplementedError() @property def update_service( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateServiceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_service( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteServiceRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc.py index 4a8b13924452..d31349aff833 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import ServicesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -293,7 +293,7 @@ def get_service(self) -> Callable[[appengine.GetServiceRequest], service.Service @property def update_service( self, - ) -> Callable[[appengine.UpdateServiceRequest], operations.Operation]: + ) -> Callable[[appengine.UpdateServiceRequest], operations_pb2.Operation]: r"""Return a callable for the update service method over gRPC. Updates the configuration of the specified service. @@ -312,14 +312,14 @@ def update_service( self._stubs["update_service"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Services/UpdateService", request_serializer=appengine.UpdateServiceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_service"] @property def delete_service( self, - ) -> Callable[[appengine.DeleteServiceRequest], operations.Operation]: + ) -> Callable[[appengine.DeleteServiceRequest], operations_pb2.Operation]: r"""Return a callable for the delete service method over gRPC. Deletes the specified service and all enclosed @@ -339,7 +339,7 @@ def delete_service( self._stubs["delete_service"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Services/DeleteService", request_serializer=appengine.DeleteServiceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_service"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py index 143b085d7aab..2f107bbff6c5 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import ServicesTransport, DEFAULT_CLIENT_INFO from .grpc import ServicesGrpcTransport @@ -56,7 +53,7 @@ class ServicesGrpcAsyncIOTransport(ServicesTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -303,7 +302,9 @@ def get_service( @property def update_service( self, - ) -> Callable[[appengine.UpdateServiceRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.UpdateServiceRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the update service method over gRPC. Updates the configuration of the specified service. @@ -322,14 +323,16 @@ def update_service( self._stubs["update_service"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Services/UpdateService", request_serializer=appengine.UpdateServiceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_service"] @property def delete_service( self, - ) -> Callable[[appengine.DeleteServiceRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.DeleteServiceRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete service method over gRPC. Deletes the specified service and all enclosed @@ -349,7 +352,7 @@ def delete_service( self._stubs["delete_service"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Services/DeleteService", request_serializer=appengine.DeleteServiceRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_service"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/__init__.py index 93418cefc8b7..586be1818c01 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import VersionsClient from .async_client import VersionsAsyncClient diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/async_client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/async_client.py index dc6828021bea..3d1a81e995e0 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/async_client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation as gac_operation # type: ignore @@ -36,10 +34,9 @@ from google.cloud.appengine_admin_v1.types import deploy from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.cloud.appengine_admin_v1.types import version -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport from .client import VersionsClient @@ -59,24 +56,21 @@ class VersionsAsyncClient: parse_common_billing_account_path = staticmethod( VersionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(VersionsClient.common_folder_path) parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(VersionsClient.common_organization_path) parse_common_organization_path = staticmethod( VersionsClient.parse_common_organization_path ) - common_project_path = staticmethod(VersionsClient.common_project_path) parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) - common_location_path = staticmethod(VersionsClient.common_location_path) parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +85,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: VersionsTransport: The transport used by the client instance. @@ -122,12 +116,12 @@ def transport(self) -> VersionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, VersionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = VersionsClient( credentials=credentials, transport=transport, @@ -181,7 +174,6 @@ async def list_versions( request (:class:`google.cloud.appengine_admin_v1.types.ListVersionsRequest`): The request object. Request message for `Versions.ListVersions`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -197,7 +189,6 @@ async def list_versions( """ # Create or coerce a protobuf request object. - request = appengine.ListVersionsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -242,7 +233,6 @@ async def get_version( request (:class:`google.cloud.appengine_admin_v1.types.GetVersionRequest`): The request object. Request message for `Versions.GetVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -257,7 +247,6 @@ async def get_version( """ # Create or coerce a protobuf request object. - request = appengine.GetVersionRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -294,7 +283,6 @@ async def create_version( request (:class:`google.cloud.appengine_admin_v1.types.CreateVersionRequest`): The request object. Request message for `Versions.CreateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -310,7 +298,6 @@ async def create_version( """ # Create or coerce a protobuf request object. - request = appengine.CreateVersionRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -390,7 +377,6 @@ async def update_version( request (:class:`google.cloud.appengine_admin_v1.types.UpdateVersionRequest`): The request object. Request message for `Versions.UpdateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -406,7 +392,6 @@ async def update_version( """ # Create or coerce a protobuf request object. - request = appengine.UpdateVersionRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -451,7 +436,6 @@ async def delete_version( request (:class:`google.cloud.appengine_admin_v1.types.DeleteVersionRequest`): The request object. Request message for `Versions.DeleteVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -478,7 +462,6 @@ async def delete_version( """ # Create or coerce a protobuf request object. - request = appengine.DeleteVersionRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -502,7 +485,7 @@ async def delete_version( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py index 51a4d06681d8..ed1e0867e259 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -40,10 +38,9 @@ from google.cloud.appengine_admin_v1.types import deploy from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.cloud.appengine_admin_v1.types import version -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import VersionsGrpcTransport from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class VersionsClientMeta(type): _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +82,8 @@ class VersionsClient(metaclass=VersionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -119,7 +117,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +135,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,16 +154,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - VersionsTransport: The transport used by the client instance. + VersionsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -177,7 +177,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -188,7 +188,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -199,7 +199,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -210,7 +210,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -224,12 +224,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, VersionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -284,9 +284,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -298,12 +299,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -318,8 +321,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -348,7 +351,6 @@ def list_versions( request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): The request object. Request message for `Versions.ListVersions`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -364,7 +366,6 @@ def list_versions( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.ListVersionsRequest. # There's no risk of modifying the input as we've already verified @@ -410,7 +411,6 @@ def get_version( request (google.cloud.appengine_admin_v1.types.GetVersionRequest): The request object. Request message for `Versions.GetVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -425,7 +425,6 @@ def get_version( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.GetVersionRequest. # There's no risk of modifying the input as we've already verified @@ -463,7 +462,6 @@ def create_version( request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): The request object. Request message for `Versions.CreateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,7 +477,6 @@ def create_version( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.CreateVersionRequest. # There's no risk of modifying the input as we've already verified @@ -560,7 +557,6 @@ def update_version( request (google.cloud.appengine_admin_v1.types.UpdateVersionRequest): The request object. Request message for `Versions.UpdateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -576,7 +572,6 @@ def update_version( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.UpdateVersionRequest. # There's no risk of modifying the input as we've already verified @@ -622,7 +617,6 @@ def delete_version( request (google.cloud.appengine_admin_v1.types.DeleteVersionRequest): The request object. Request message for `Versions.DeleteVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -649,7 +643,6 @@ def delete_version( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a appengine.DeleteVersionRequest. # There's no risk of modifying the input as we've already verified @@ -674,7 +667,7 @@ def delete_version( response = gac_operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=ga_operation.OperationMetadataV1, ) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/pagers.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/pagers.py index e2be7655bf41..41cfb4671eb9 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/pagers.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py index aa4c96b0dca3..c5a42a0e8fea 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/base.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/base.py index 2c3b32b84bd6..d1f014efd5b1 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/base.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" @@ -50,21 +60,24 @@ class VersionsTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-platform.read-only", ) + DEFAULT_HOST: str = "appengine.googleapis.com" + def __init__( self, *, - host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,7 +86,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -87,29 +100,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -138,11 +198,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_versions( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.ListVersionsRequest], - typing.Union[ - appengine.ListVersionsResponse, - typing.Awaitable[appengine.ListVersionsResponse], + Union[ + appengine.ListVersionsResponse, Awaitable[appengine.ListVersionsResponse] ], ]: raise NotImplementedError() @@ -150,36 +209,36 @@ def list_versions( @property def get_version( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.GetVersionRequest], - typing.Union[version.Version, typing.Awaitable[version.Version]], + Union[version.Version, Awaitable[version.Version]], ]: raise NotImplementedError() @property def create_version( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.CreateVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_version( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.UpdateVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_version( self, - ) -> typing.Callable[ + ) -> Callable[ [appengine.DeleteVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py index f6a34efe2329..36bfeee618a9 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -294,7 +294,7 @@ def get_version(self) -> Callable[[appengine.GetVersionRequest], version.Version @property def create_version( self, - ) -> Callable[[appengine.CreateVersionRequest], operations.Operation]: + ) -> Callable[[appengine.CreateVersionRequest], operations_pb2.Operation]: r"""Return a callable for the create version method over gRPC. Deploys code and resource files to a new version. @@ -313,14 +313,14 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/CreateVersion", request_serializer=appengine.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @property def update_version( self, - ) -> Callable[[appengine.UpdateVersionRequest], operations.Operation]: + ) -> Callable[[appengine.UpdateVersionRequest], operations_pb2.Operation]: r"""Return a callable for the update version method over gRPC. Updates the specified Version resource. You can specify the @@ -374,14 +374,14 @@ def update_version( self._stubs["update_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/UpdateVersion", request_serializer=appengine.UpdateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_version"] @property def delete_version( self, - ) -> Callable[[appengine.DeleteVersionRequest], operations.Operation]: + ) -> Callable[[appengine.DeleteVersionRequest], operations_pb2.Operation]: r"""Return a callable for the delete version method over gRPC. Deletes an existing Version resource. @@ -400,7 +400,7 @@ def delete_version( self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/DeleteVersion", request_serializer=appengine.DeleteVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_version"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py index 2a23e5ab287d..20c53e8e18e4 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO from .grpc import VersionsGrpcTransport @@ -56,7 +53,7 @@ class VersionsGrpcAsyncIOTransport(VersionsTransport): def create_channel( cls, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "appengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -304,7 +303,9 @@ def get_version( @property def create_version( self, - ) -> Callable[[appengine.CreateVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.CreateVersionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create version method over gRPC. Deploys code and resource files to a new version. @@ -323,14 +324,16 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/CreateVersion", request_serializer=appengine.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @property def update_version( self, - ) -> Callable[[appengine.UpdateVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.UpdateVersionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the update version method over gRPC. Updates the specified Version resource. You can specify the @@ -384,14 +387,16 @@ def update_version( self._stubs["update_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/UpdateVersion", request_serializer=appengine.UpdateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_version"] @property def delete_version( self, - ) -> Callable[[appengine.DeleteVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [appengine.DeleteVersionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete version method over gRPC. Deletes an existing Version resource. @@ -410,7 +415,7 @@ def delete_version( self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.appengine.v1.Versions/DeleteVersion", request_serializer=appengine.DeleteVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_version"] diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/__init__.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/__init__.py index c0c28ec581bb..dfe79d645ecc 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/__init__.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .app_yaml import ( ApiConfigHandler, ApiEndpointHandler, diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/app_yaml.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/app_yaml.py index a9fc8d2bb264..9c7f879d5393 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/app_yaml.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/app_yaml.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -88,19 +85,14 @@ class ApiConfigHandler(proto.Message): """ auth_fail_action = proto.Field(proto.ENUM, number=1, enum="AuthFailAction",) - login = proto.Field(proto.ENUM, number=2, enum="LoginRequirement",) - - script = proto.Field(proto.STRING, number=3) - + script = proto.Field(proto.STRING, number=3,) security_level = proto.Field(proto.ENUM, number=4, enum="SecurityLevel",) - - url = proto.Field(proto.STRING, number=5) + url = proto.Field(proto.STRING, number=5,) class ErrorHandler(proto.Message): r"""Custom static error page to be served when an error occurs. - Attributes: error_code (google.cloud.appengine_admin_v1.types.ErrorHandler.ErrorCode): Error condition this handler applies to. @@ -121,10 +113,8 @@ class ErrorCode(proto.Enum): ERROR_CODE_TIMEOUT = 3 error_code = proto.Field(proto.ENUM, number=1, enum=ErrorCode,) - - static_file = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) + static_file = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) class UrlMap(proto.Message): @@ -173,26 +163,19 @@ class RedirectHttpResponseCode(proto.Enum): REDIRECT_HTTP_RESPONSE_CODE_303 = 3 REDIRECT_HTTP_RESPONSE_CODE_307 = 4 - url_regex = proto.Field(proto.STRING, number=1) - + url_regex = proto.Field(proto.STRING, number=1,) static_files = proto.Field( proto.MESSAGE, number=2, oneof="handler_type", message="StaticFilesHandler", ) - script = proto.Field( proto.MESSAGE, number=3, oneof="handler_type", message="ScriptHandler", ) - api_endpoint = proto.Field( proto.MESSAGE, number=4, oneof="handler_type", message="ApiEndpointHandler", ) - security_level = proto.Field(proto.ENUM, number=5, enum="SecurityLevel",) - login = proto.Field(proto.ENUM, number=6, enum="LoginRequirement",) - auth_fail_action = proto.Field(proto.ENUM, number=7, enum="AuthFailAction",) - redirect_http_response_code = proto.Field( proto.ENUM, number=8, enum=RedirectHttpResponseCode, ) @@ -239,19 +222,13 @@ class StaticFilesHandler(proto.Message): resource quotas. """ - path = proto.Field(proto.STRING, number=1) - - upload_path_regex = proto.Field(proto.STRING, number=2) - - http_headers = proto.MapField(proto.STRING, proto.STRING, number=3) - - mime_type = proto.Field(proto.STRING, number=4) - - expiration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - require_matching_file = proto.Field(proto.BOOL, number=6) - - application_readable = proto.Field(proto.BOOL, number=7) + path = proto.Field(proto.STRING, number=1,) + upload_path_regex = proto.Field(proto.STRING, number=2,) + http_headers = proto.MapField(proto.STRING, proto.STRING, number=3,) + mime_type = proto.Field(proto.STRING, number=4,) + expiration = proto.Field(proto.MESSAGE, number=5, message=duration_pb2.Duration,) + require_matching_file = proto.Field(proto.BOOL, number=6,) + application_readable = proto.Field(proto.BOOL, number=7,) class ScriptHandler(proto.Message): @@ -264,19 +241,18 @@ class ScriptHandler(proto.Message): directory. """ - script_path = proto.Field(proto.STRING, number=1) + script_path = proto.Field(proto.STRING, number=1,) class ApiEndpointHandler(proto.Message): r"""Uses Google Cloud Endpoints to handle requests. - Attributes: script_path (str): Path to the script from the application root directory. """ - script_path = proto.Field(proto.STRING, number=1) + script_path = proto.Field(proto.STRING, number=1,) class HealthCheck(proto.Message): @@ -307,19 +283,15 @@ class HealthCheck(proto.Message): failed. """ - disable_health_check = proto.Field(proto.BOOL, number=1) - - host = proto.Field(proto.STRING, number=2) - - healthy_threshold = proto.Field(proto.UINT32, number=3) - - unhealthy_threshold = proto.Field(proto.UINT32, number=4) - - restart_threshold = proto.Field(proto.UINT32, number=5) - - check_interval = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - timeout = proto.Field(proto.MESSAGE, number=7, message=duration.Duration,) + disable_health_check = proto.Field(proto.BOOL, number=1,) + host = proto.Field(proto.STRING, number=2,) + healthy_threshold = proto.Field(proto.UINT32, number=3,) + unhealthy_threshold = proto.Field(proto.UINT32, number=4,) + restart_threshold = proto.Field(proto.UINT32, number=5,) + check_interval = proto.Field( + proto.MESSAGE, number=6, message=duration_pb2.Duration, + ) + timeout = proto.Field(proto.MESSAGE, number=7, message=duration_pb2.Duration,) class ReadinessCheck(proto.Message): @@ -349,19 +321,17 @@ class ReadinessCheck(proto.Message): healthcheck until it is ready to serve traffic. """ - path = proto.Field(proto.STRING, number=1) - - host = proto.Field(proto.STRING, number=2) - - failure_threshold = proto.Field(proto.UINT32, number=3) - - success_threshold = proto.Field(proto.UINT32, number=4) - - check_interval = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - timeout = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - app_start_timeout = proto.Field(proto.MESSAGE, number=7, message=duration.Duration,) + path = proto.Field(proto.STRING, number=1,) + host = proto.Field(proto.STRING, number=2,) + failure_threshold = proto.Field(proto.UINT32, number=3,) + success_threshold = proto.Field(proto.UINT32, number=4,) + check_interval = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + timeout = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration,) + app_start_timeout = proto.Field( + proto.MESSAGE, number=7, message=duration_pb2.Duration, + ) class LivenessCheck(proto.Message): @@ -389,19 +359,15 @@ class LivenessCheck(proto.Message): the checks. """ - path = proto.Field(proto.STRING, number=1) - - host = proto.Field(proto.STRING, number=2) - - failure_threshold = proto.Field(proto.UINT32, number=3) - - success_threshold = proto.Field(proto.UINT32, number=4) - - check_interval = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - timeout = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - initial_delay = proto.Field(proto.MESSAGE, number=7, message=duration.Duration,) + path = proto.Field(proto.STRING, number=1,) + host = proto.Field(proto.STRING, number=2,) + failure_threshold = proto.Field(proto.UINT32, number=3,) + success_threshold = proto.Field(proto.UINT32, number=4,) + check_interval = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + timeout = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration,) + initial_delay = proto.Field(proto.MESSAGE, number=7, message=duration_pb2.Duration,) class Library(proto.Message): @@ -416,9 +382,8 @@ class Library(proto.Message): "latest". """ - name = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/appengine.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/appengine.py index 4f154e1af611..e50ef770a186 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/appengine.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/appengine.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.appengine_admin_v1.types import application as ga_application from google.cloud.appengine_admin_v1.types import certificate as ga_certificate from google.cloud.appengine_admin_v1.types import domain @@ -26,7 +23,7 @@ from google.cloud.appengine_admin_v1.types import instance from google.cloud.appengine_admin_v1.types import service as ga_service from google.cloud.appengine_admin_v1.types import version as ga_version -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -106,19 +103,17 @@ class DomainOverrideStrategy(proto.Enum): class GetApplicationRequest(proto.Message): r"""Request message for ``Applications.GetApplication``. - Attributes: name (str): Name of the Application resource to get. Example: ``apps/myapp``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateApplicationRequest(proto.Message): r"""Request message for ``Applications.CreateApplication``. - Attributes: application (google.cloud.appengine_admin_v1.types.Application): Application configuration. @@ -131,7 +126,6 @@ class CreateApplicationRequest(proto.Message): class UpdateApplicationRequest(proto.Message): r"""Request message for ``Applications.UpdateApplication``. - Attributes: name (str): Name of the Application resource to update. Example: @@ -144,29 +138,27 @@ class UpdateApplicationRequest(proto.Message): be updated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) application = proto.Field( proto.MESSAGE, number=2, message=ga_application.Application, ) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class RepairApplicationRequest(proto.Message): r"""Request message for 'Applications.RepairApplication'. - Attributes: name (str): Name of the application to repair. Example: ``apps/myapp`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListServicesRequest(proto.Message): r"""Request message for ``Services.ListServices``. - Attributes: parent (str): Name of the parent Application resource. Example: @@ -178,16 +170,13 @@ class ListServicesRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListServicesResponse(proto.Message): r"""Response message for ``Services.ListServices``. - Attributes: services (Sequence[google.cloud.appengine_admin_v1.types.Service]): The services belonging to the requested @@ -202,25 +191,22 @@ def raw_page(self): return self services = proto.RepeatedField(proto.MESSAGE, number=1, message=ga_service.Service,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetServiceRequest(proto.Message): r"""Request message for ``Services.GetService``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/services/default``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateServiceRequest(proto.Message): r"""Request message for ``Services.UpdateService``. - Attributes: name (str): Name of the resource to update. Example: @@ -249,30 +235,27 @@ class UpdateServiceRequest(proto.Message): Traffic `__. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) service = proto.Field(proto.MESSAGE, number=2, message=ga_service.Service,) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) - - migrate_traffic = proto.Field(proto.BOOL, number=4) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) + migrate_traffic = proto.Field(proto.BOOL, number=4,) class DeleteServiceRequest(proto.Message): r"""Request message for ``Services.DeleteService``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/services/default``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListVersionsRequest(proto.Message): r"""Request message for ``Versions.ListVersions``. - Attributes: parent (str): Name of the parent Service resource. Example: @@ -287,18 +270,14 @@ class ListVersionsRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) view = proto.Field(proto.ENUM, number=2, enum="VersionView",) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListVersionsResponse(proto.Message): r"""Response message for ``Versions.ListVersions``. - Attributes: versions (Sequence[google.cloud.appengine_admin_v1.types.Version]): The versions belonging to the requested @@ -313,13 +292,11 @@ def raw_page(self): return self versions = proto.RepeatedField(proto.MESSAGE, number=1, message=ga_version.Version,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetVersionRequest(proto.Message): r"""Request message for ``Versions.GetVersion``. - Attributes: name (str): Name of the resource requested. Example: @@ -328,14 +305,12 @@ class GetVersionRequest(proto.Message): Controls the set of fields returned in the ``Get`` response. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) view = proto.Field(proto.ENUM, number=2, enum="VersionView",) class CreateVersionRequest(proto.Message): r"""Request message for ``Versions.CreateVersion``. - Attributes: parent (str): Name of the parent resource to create this version under. @@ -344,14 +319,12 @@ class CreateVersionRequest(proto.Message): Application deployment configuration. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) version = proto.Field(proto.MESSAGE, number=2, message=ga_version.Version,) class UpdateVersionRequest(proto.Message): r"""Request message for ``Versions.UpdateVersion``. - Attributes: name (str): Name of the resource to update. Example: @@ -365,28 +338,26 @@ class UpdateVersionRequest(proto.Message): be updated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) version = proto.Field(proto.MESSAGE, number=2, message=ga_version.Version,) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteVersionRequest(proto.Message): r"""Request message for ``Versions.DeleteVersion``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/services/default/versions/v1``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListInstancesRequest(proto.Message): r"""Request message for ``Instances.ListInstances``. - Attributes: parent (str): Name of the parent Version resource. Example: @@ -398,16 +369,13 @@ class ListInstancesRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListInstancesResponse(proto.Message): r"""Response message for ``Instances.ListInstances``. - Attributes: instances (Sequence[google.cloud.appengine_admin_v1.types.Instance]): The instances belonging to the requested @@ -422,37 +390,33 @@ def raw_page(self): return self instances = proto.RepeatedField(proto.MESSAGE, number=1, message=instance.Instance,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetInstanceRequest(proto.Message): r"""Request message for ``Instances.GetInstance``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/services/default/versions/v1/instances/instance-1``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteInstanceRequest(proto.Message): r"""Request message for ``Instances.DeleteInstance``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/services/default/versions/v1/instances/instance-1``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DebugInstanceRequest(proto.Message): r"""Request message for ``Instances.DebugInstance``. - Attributes: name (str): Name of the resource requested. Example: @@ -467,14 +431,12 @@ class DebugInstanceRequest(proto.Message): Keys `__. """ - name = proto.Field(proto.STRING, number=1) - - ssh_key = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + ssh_key = proto.Field(proto.STRING, number=2,) class ListIngressRulesRequest(proto.Message): r"""Request message for ``Firewall.ListIngressRules``. - Attributes: parent (str): Name of the Firewall collection to retrieve. Example: @@ -491,18 +453,14 @@ class ListIngressRulesRequest(proto.Message): on requests from this IP. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - matching_address = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + matching_address = proto.Field(proto.STRING, number=4,) class ListIngressRulesResponse(proto.Message): r"""Response message for ``Firewall.ListIngressRules``. - Attributes: ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): The ingress FirewallRules for this @@ -519,13 +477,11 @@ def raw_page(self): ingress_rules = proto.RepeatedField( proto.MESSAGE, number=1, message=firewall.FirewallRule, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class BatchUpdateIngressRulesRequest(proto.Message): r"""Request message for ``Firewall.BatchUpdateIngressRules``. - Attributes: name (str): Name of the Firewall collection to set. Example: @@ -535,8 +491,7 @@ class BatchUpdateIngressRulesRequest(proto.Message): existing set. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) ingress_rules = proto.RepeatedField( proto.MESSAGE, number=2, message=firewall.FirewallRule, ) @@ -544,7 +499,6 @@ class BatchUpdateIngressRulesRequest(proto.Message): class BatchUpdateIngressRulesResponse(proto.Message): r"""Response message for ``Firewall.UpdateAllIngressRules``. - Attributes: ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): The full list of ingress FirewallRules for @@ -558,7 +512,6 @@ class BatchUpdateIngressRulesResponse(proto.Message): class CreateIngressRuleRequest(proto.Message): r"""Request message for ``Firewall.CreateIngressRule``. - Attributes: parent (str): Name of the parent Firewall collection in which to create a @@ -578,26 +531,23 @@ class CreateIngressRuleRequest(proto.Message): or deny-all rule. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) rule = proto.Field(proto.MESSAGE, number=2, message=firewall.FirewallRule,) class GetIngressRuleRequest(proto.Message): r"""Request message for ``Firewall.GetIngressRule``. - Attributes: name (str): Name of the Firewall resource to retrieve. Example: ``apps/myapp/firewall/ingressRules/100``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateIngressRuleRequest(proto.Message): r"""Request message for ``Firewall.UpdateIngressRule``. - Attributes: name (str): Name of the Firewall resource to update. Example: @@ -610,28 +560,26 @@ class UpdateIngressRuleRequest(proto.Message): be updated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) rule = proto.Field(proto.MESSAGE, number=2, message=firewall.FirewallRule,) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteIngressRuleRequest(proto.Message): r"""Request message for ``Firewall.DeleteIngressRule``. - Attributes: name (str): Name of the Firewall resource to delete. Example: ``apps/myapp/firewall/ingressRules/100``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListAuthorizedDomainsRequest(proto.Message): r"""Request message for ``AuthorizedDomains.ListAuthorizedDomains``. - Attributes: parent (str): Name of the parent Application resource. Example: @@ -643,16 +591,13 @@ class ListAuthorizedDomainsRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListAuthorizedDomainsResponse(proto.Message): r"""Response message for ``AuthorizedDomains.ListAuthorizedDomains``. - Attributes: domains (Sequence[google.cloud.appengine_admin_v1.types.AuthorizedDomain]): The authorized domains belonging to the user. @@ -668,8 +613,7 @@ def raw_page(self): domains = proto.RepeatedField( proto.MESSAGE, number=1, message=domain.AuthorizedDomain, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListAuthorizedCertificatesRequest(proto.Message): @@ -690,13 +634,10 @@ class ListAuthorizedCertificatesRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) view = proto.Field(proto.ENUM, number=4, enum="AuthorizedCertificateView",) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListAuthorizedCertificatesResponse(proto.Message): @@ -719,8 +660,7 @@ def raw_page(self): certificates = proto.RepeatedField( proto.MESSAGE, number=1, message=ga_certificate.AuthorizedCertificate, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetAuthorizedCertificateRequest(proto.Message): @@ -735,8 +675,7 @@ class GetAuthorizedCertificateRequest(proto.Message): Controls the set of fields returned in the ``GET`` response. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) view = proto.Field(proto.ENUM, number=2, enum="AuthorizedCertificateView",) @@ -752,8 +691,7 @@ class CreateAuthorizedCertificateRequest(proto.Message): SSL certificate data. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) certificate = proto.Field( proto.MESSAGE, number=2, message=ga_certificate.AuthorizedCertificate, ) @@ -776,13 +714,13 @@ class UpdateAuthorizedCertificateRequest(proto.Message): and ``display_name`` fields. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) certificate = proto.Field( proto.MESSAGE, number=2, message=ga_certificate.AuthorizedCertificate, ) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteAuthorizedCertificateRequest(proto.Message): @@ -795,12 +733,11 @@ class DeleteAuthorizedCertificateRequest(proto.Message): ``apps/myapp/authorizedCertificates/12345``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListDomainMappingsRequest(proto.Message): r"""Request message for ``DomainMappings.ListDomainMappings``. - Attributes: parent (str): Name of the parent Application resource. Example: @@ -812,16 +749,13 @@ class ListDomainMappingsRequest(proto.Message): of results. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListDomainMappingsResponse(proto.Message): r"""Response message for ``DomainMappings.ListDomainMappings``. - Attributes: domain_mappings (Sequence[google.cloud.appengine_admin_v1.types.DomainMapping]): The domain mappings for the application. @@ -837,25 +771,22 @@ def raw_page(self): domain_mappings = proto.RepeatedField( proto.MESSAGE, number=1, message=ga_domain_mapping.DomainMapping, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetDomainMappingRequest(proto.Message): r"""Request message for ``DomainMappings.GetDomainMapping``. - Attributes: name (str): Name of the resource requested. Example: ``apps/myapp/domainMappings/example.com``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateDomainMappingRequest(proto.Message): r"""Request message for ``DomainMappings.CreateDomainMapping``. - Attributes: parent (str): Name of the parent Application resource. Example: @@ -868,12 +799,10 @@ class CreateDomainMappingRequest(proto.Message): default, overrides are rejected. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) domain_mapping = proto.Field( proto.MESSAGE, number=2, message=ga_domain_mapping.DomainMapping, ) - override_strategy = proto.Field( proto.ENUM, number=4, enum="DomainOverrideStrategy", ) @@ -881,7 +810,6 @@ class CreateDomainMappingRequest(proto.Message): class UpdateDomainMappingRequest(proto.Message): r"""Request message for ``DomainMappings.UpdateDomainMapping``. - Attributes: name (str): Name of the resource to update. Example: @@ -895,25 +823,24 @@ class UpdateDomainMappingRequest(proto.Message): be updated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) domain_mapping = proto.Field( proto.MESSAGE, number=2, message=ga_domain_mapping.DomainMapping, ) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteDomainMappingRequest(proto.Message): r"""Request message for ``DomainMappings.DeleteDomainMapping``. - Attributes: name (str): Name of the resource to delete. Example: ``apps/myapp/domainMappings/example.com``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/application.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/application.py index 99939c2c543d..89ee5590bd1c 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/application.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/application.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -113,7 +110,6 @@ class DatabaseType(proto.Enum): class IdentityAwareProxy(proto.Message): r"""Identity-Aware Proxy - Attributes: enabled (bool): Whether the serving infrastructure will authenticate and @@ -138,13 +134,10 @@ class IdentityAwareProxy(proto.Message): @OutputOnly """ - enabled = proto.Field(proto.BOOL, number=1) - - oauth2_client_id = proto.Field(proto.STRING, number=2) - - oauth2_client_secret = proto.Field(proto.STRING, number=3) - - oauth2_client_secret_sha256 = proto.Field(proto.STRING, number=4) + enabled = proto.Field(proto.BOOL, number=1,) + oauth2_client_id = proto.Field(proto.STRING, number=2,) + oauth2_client_secret = proto.Field(proto.STRING, number=3,) + oauth2_client_secret_sha256 = proto.Field(proto.STRING, number=4,) class FeatureSettings(proto.Message): r"""The feature specific settings to be used in the application. @@ -164,40 +157,26 @@ class FeatureSettings(proto.Message): base image for VMs, rather than a base Debian image. """ - split_health_checks = proto.Field(proto.BOOL, number=1) - - use_container_optimized_os = proto.Field(proto.BOOL, number=2) - - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) + split_health_checks = proto.Field(proto.BOOL, number=1,) + use_container_optimized_os = proto.Field(proto.BOOL, number=2,) + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) dispatch_rules = proto.RepeatedField( proto.MESSAGE, number=3, message="UrlDispatchRule", ) - - auth_domain = proto.Field(proto.STRING, number=6) - - location_id = proto.Field(proto.STRING, number=7) - - code_bucket = proto.Field(proto.STRING, number=8) - + auth_domain = proto.Field(proto.STRING, number=6,) + location_id = proto.Field(proto.STRING, number=7,) + code_bucket = proto.Field(proto.STRING, number=8,) default_cookie_expiration = proto.Field( - proto.MESSAGE, number=9, message=duration.Duration, + proto.MESSAGE, number=9, message=duration_pb2.Duration, ) - serving_status = proto.Field(proto.ENUM, number=10, enum=ServingStatus,) - - default_hostname = proto.Field(proto.STRING, number=11) - - default_bucket = proto.Field(proto.STRING, number=12) - + default_hostname = proto.Field(proto.STRING, number=11,) + default_bucket = proto.Field(proto.STRING, number=12,) iap = proto.Field(proto.MESSAGE, number=14, message=IdentityAwareProxy,) - - gcr_domain = proto.Field(proto.STRING, number=16) - + gcr_domain = proto.Field(proto.STRING, number=16,) database_type = proto.Field(proto.ENUM, number=17, enum=DatabaseType,) - feature_settings = proto.Field(proto.MESSAGE, number=18, message=FeatureSettings,) @@ -223,11 +202,9 @@ class UrlDispatchRule(proto.Message): Example: ``default``. """ - domain = proto.Field(proto.STRING, number=1) - - path = proto.Field(proto.STRING, number=2) - - service = proto.Field(proto.STRING, number=3) + domain = proto.Field(proto.STRING, number=1,) + path = proto.Field(proto.STRING, number=2,) + service = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/audit_data.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/audit_data.py index ddc4261e1784..c99e43ad97d6 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/audit_data.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/audit_data.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.appengine_admin_v1.types import appengine @@ -29,7 +26,6 @@ class AuditData(proto.Message): r"""App Engine admin service audit log. - Attributes: update_service (google.cloud.appengine_admin_v1.types.UpdateServiceMethod): Detailed information about UpdateService @@ -42,7 +38,6 @@ class AuditData(proto.Message): update_service = proto.Field( proto.MESSAGE, number=1, oneof="method", message="UpdateServiceMethod", ) - create_version = proto.Field( proto.MESSAGE, number=2, oneof="method", message="CreateVersionMethod", ) @@ -50,7 +45,6 @@ class AuditData(proto.Message): class UpdateServiceMethod(proto.Message): r"""Detailed information about UpdateService call. - Attributes: request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): Update service request. @@ -63,7 +57,6 @@ class UpdateServiceMethod(proto.Message): class CreateVersionMethod(proto.Message): r"""Detailed information about CreateVersion call. - Attributes: request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): Create version request. diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/certificate.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/certificate.py index 0a9e070e690c..4d2803952733 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/certificate.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/certificate.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -117,32 +114,23 @@ class AuthorizedCertificate(proto.Message): @OutputOnly """ - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - domain_names = proto.RepeatedField(proto.STRING, number=4) - - expire_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + domain_names = proto.RepeatedField(proto.STRING, number=4,) + expire_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) certificate_raw_data = proto.Field( proto.MESSAGE, number=6, message="CertificateRawData", ) - managed_certificate = proto.Field( proto.MESSAGE, number=7, message="ManagedCertificate", ) - - visible_domain_mappings = proto.RepeatedField(proto.STRING, number=8) - - domain_mappings_count = proto.Field(proto.INT32, number=9) + visible_domain_mappings = proto.RepeatedField(proto.STRING, number=8,) + domain_mappings_count = proto.Field(proto.INT32, number=9,) class CertificateRawData(proto.Message): r"""An SSL certificate obtained from a certificate authority. - Attributes: public_certificate (str): PEM encoded x.509 public key certificate. This field is set @@ -173,14 +161,12 @@ class CertificateRawData(proto.Message): @InputOnly """ - public_certificate = proto.Field(proto.STRING, number=1) - - private_key = proto.Field(proto.STRING, number=2) + public_certificate = proto.Field(proto.STRING, number=1,) + private_key = proto.Field(proto.STRING, number=2,) class ManagedCertificate(proto.Message): r"""A certificate managed by App Engine. - Attributes: last_renewal_time (google.protobuf.timestamp_pb2.Timestamp): Time at which the certificate was last renewed. The renewal @@ -197,9 +183,8 @@ class ManagedCertificate(proto.Message): """ last_renewal_time = proto.Field( - proto.MESSAGE, number=1, message=timestamp.Timestamp, + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) - status = proto.Field(proto.ENUM, number=2, enum="ManagementStatus",) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deploy.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deploy.py index c3680629bc6d..6345d8fba175 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deploy.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deploy.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -60,11 +57,8 @@ class Deployment(proto.Message): """ files = proto.MapField(proto.STRING, proto.MESSAGE, number=1, message="FileInfo",) - container = proto.Field(proto.MESSAGE, number=2, message="ContainerInfo",) - zip_ = proto.Field(proto.MESSAGE, number=3, message="ZipInfo",) - cloud_build_options = proto.Field( proto.MESSAGE, number=6, message="CloudBuildOptions", ) @@ -88,11 +82,9 @@ class FileInfo(proto.Message): Defaults to the value from Google Cloud Storage. """ - source_url = proto.Field(proto.STRING, number=1) - - sha1_sum = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) + source_url = proto.Field(proto.STRING, number=1,) + sha1_sum = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) class ContainerInfo(proto.Message): @@ -109,7 +101,7 @@ class ContainerInfo(proto.Message): project/image@digest". """ - image = proto.Field(proto.STRING, number=1) + image = proto.Field(proto.STRING, number=1,) class CloudBuildOptions(proto.Message): @@ -132,16 +124,14 @@ class CloudBuildOptions(proto.Message): Defaults to 10 minutes. """ - app_yaml_path = proto.Field(proto.STRING, number=1) - + app_yaml_path = proto.Field(proto.STRING, number=1,) cloud_build_timeout = proto.Field( - proto.MESSAGE, number=2, message=duration.Duration, + proto.MESSAGE, number=2, message=duration_pb2.Duration, ) class ZipInfo(proto.Message): r"""The zip file information for a zip deployment. - Attributes: source_url (str): URL of the zip file to deploy from. Must be a @@ -156,9 +146,8 @@ class ZipInfo(proto.Message): provided, deployment may be slow. """ - source_url = proto.Field(proto.STRING, number=3) - - files_count = proto.Field(proto.INT32, number=4) + source_url = proto.Field(proto.STRING, number=3,) + files_count = proto.Field(proto.INT32, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deployed_files.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deployed_files.py index 1f17c4b4c0cb..3b05140546a3 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deployed_files.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/deployed_files.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain.py index 024bb6ab6b7e..ea6c8f440ca6 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -39,9 +37,8 @@ class AuthorizedDomain(proto.Message): use. Example: ``example.com``. """ - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain_mapping.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain_mapping.py index c08953bfe8ee..bfa48da1c172 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain_mapping.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/domain_mapping.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class DomainMapping(proto.Message): r"""A domain serving an App Engine application. - Attributes: name (str): Full path to the ``DomainMapping`` resource in the API. @@ -48,12 +45,9 @@ class DomainMapping(proto.Message): @OutputOnly """ - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) ssl_settings = proto.Field(proto.MESSAGE, number=3, message="SslSettings",) - resource_records = proto.RepeatedField( proto.MESSAGE, number=4, message="ResourceRecord", ) @@ -61,7 +55,6 @@ class DomainMapping(proto.Message): class SslSettings(proto.Message): r"""SSL configuration for a ``DomainMapping`` resource. - Attributes: certificate_id (str): ID of the ``AuthorizedCertificate`` resource configuring SSL @@ -100,16 +93,13 @@ class SslManagementType(proto.Enum): AUTOMATIC = 1 MANUAL = 2 - certificate_id = proto.Field(proto.STRING, number=1) - + certificate_id = proto.Field(proto.STRING, number=1,) ssl_management_type = proto.Field(proto.ENUM, number=3, enum=SslManagementType,) - - pending_managed_certificate_id = proto.Field(proto.STRING, number=4) + pending_managed_certificate_id = proto.Field(proto.STRING, number=4,) class ResourceRecord(proto.Message): r"""A DNS resource record. - Attributes: name (str): Relative name of the object affected by this record. Only @@ -129,10 +119,8 @@ class RecordType(proto.Enum): AAAA = 2 CNAME = 3 - name = proto.Field(proto.STRING, number=1) - - rrdata = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + rrdata = proto.Field(proto.STRING, number=2,) type_ = proto.Field(proto.ENUM, number=3, enum=RecordType,) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/firewall.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/firewall.py index e3b179bb1935..175346e38e5a 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/firewall.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/firewall.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -62,13 +60,10 @@ class Action(proto.Enum): ALLOW = 1 DENY = 2 - priority = proto.Field(proto.INT32, number=1) - + priority = proto.Field(proto.INT32, number=1,) action = proto.Field(proto.ENUM, number=2, enum=Action,) - - source_range = proto.Field(proto.STRING, number=3) - - description = proto.Field(proto.STRING, number=4) + source_range = proto.Field(proto.STRING, number=3,) + description = proto.Field(proto.STRING, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/instance.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/instance.py index 72422cf6c017..2311bb923baa 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/instance.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/instance.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module(package="google.appengine.v1", manifest={"Instance",},) @@ -96,7 +93,7 @@ class Availability(proto.Enum): DYNAMIC = 2 class Liveness(proto.Message): - r"""Wrapper for LivenessState enum.""" + r"""Wrapper for LivenessState enum. """ class LivenessState(proto.Enum): r"""Liveness health check status for Flex instances.""" @@ -107,38 +104,22 @@ class LivenessState(proto.Enum): DRAINING = 4 TIMEOUT = 5 - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) - - app_engine_release = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) + app_engine_release = proto.Field(proto.STRING, number=3,) availability = proto.Field(proto.ENUM, number=4, enum=Availability,) - - vm_name = proto.Field(proto.STRING, number=5) - - vm_zone_name = proto.Field(proto.STRING, number=6) - - vm_id = proto.Field(proto.STRING, number=7) - - start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) - - requests = proto.Field(proto.INT32, number=9) - - errors = proto.Field(proto.INT32, number=10) - - qps = proto.Field(proto.FLOAT, number=11) - - average_latency = proto.Field(proto.INT32, number=12) - - memory_usage = proto.Field(proto.INT64, number=13) - - vm_status = proto.Field(proto.STRING, number=14) - - vm_debug_enabled = proto.Field(proto.BOOL, number=15) - - vm_ip = proto.Field(proto.STRING, number=16) - + vm_name = proto.Field(proto.STRING, number=5,) + vm_zone_name = proto.Field(proto.STRING, number=6,) + vm_id = proto.Field(proto.STRING, number=7,) + start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) + requests = proto.Field(proto.INT32, number=9,) + errors = proto.Field(proto.INT32, number=10,) + qps = proto.Field(proto.FLOAT, number=11,) + average_latency = proto.Field(proto.INT32, number=12,) + memory_usage = proto.Field(proto.INT64, number=13,) + vm_status = proto.Field(proto.STRING, number=14,) + vm_debug_enabled = proto.Field(proto.BOOL, number=15,) + vm_ip = proto.Field(proto.STRING, number=16,) vm_liveness = proto.Field(proto.ENUM, number=17, enum=Liveness.LivenessState,) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/location.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/location.py index a9a3e3e333dc..28543e7609bc 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/location.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/location.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -42,11 +40,9 @@ class LocationMetadata(proto.Message): is available in the given location. """ - standard_environment_available = proto.Field(proto.BOOL, number=2) - - flexible_environment_available = proto.Field(proto.BOOL, number=4) - - search_api_available = proto.Field(proto.BOOL, number=6) + standard_environment_available = proto.Field(proto.BOOL, number=2,) + flexible_environment_available = proto.Field(proto.BOOL, number=4,) + search_api_available = proto.Field(proto.BOOL, number=6,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/network_settings.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/network_settings.py index 81e51dc2a437..09f22895469d 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/network_settings.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/network_settings.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/operation.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/operation.py index 79619d4251b5..4c0c35a02c94 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/operation.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/operation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -61,20 +58,13 @@ class OperationMetadataV1(proto.Message): """ - method = proto.Field(proto.STRING, number=1) - - insert_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - user = proto.Field(proto.STRING, number=4) - - target = proto.Field(proto.STRING, number=5) - - ephemeral_message = proto.Field(proto.STRING, number=6) - - warning = proto.RepeatedField(proto.STRING, number=7) - + method = proto.Field(proto.STRING, number=1,) + insert_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + user = proto.Field(proto.STRING, number=4,) + target = proto.Field(proto.STRING, number=5,) + ephemeral_message = proto.Field(proto.STRING, number=6,) + warning = proto.RepeatedField(proto.STRING, number=7,) create_version_metadata = proto.Field( proto.MESSAGE, number=8, @@ -95,7 +85,7 @@ class CreateVersionMetadataV1(proto.Message): of the version create. @OutputOnly """ - cloud_build_id = proto.Field(proto.STRING, number=1) + cloud_build_id = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/service.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/service.py index c44eac55773e..318f1957575a 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/service.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.appengine_admin_v1.types import ( network_settings as ga_network_settings, ) @@ -58,12 +55,9 @@ class Service(proto.Message): to all versions. """ - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) split = proto.Field(proto.MESSAGE, number=3, message="TrafficSplit",) - network_settings = proto.Field( proto.MESSAGE, number=6, message=ga_network_settings.NetworkSettings, ) @@ -100,8 +94,7 @@ class ShardBy(proto.Enum): RANDOM = 3 shard_by = proto.Field(proto.ENUM, number=1, enum=ShardBy,) - - allocations = proto.MapField(proto.STRING, proto.DOUBLE, number=2) + allocations = proto.MapField(proto.STRING, proto.DOUBLE, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/version.py b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/version.py index ac2bfac019b0..c47506382047 100644 --- a/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/version.py +++ b/packages/google-cloud-appengine-admin/google/cloud/appengine_admin_v1/types/version.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.appengine_admin_v1.types import app_yaml from google.cloud.appengine_admin_v1.types import deploy -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -256,104 +253,68 @@ class Version(proto.Message): Enables VPC connectivity for standard apps. """ - name = proto.Field(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=2,) automatic_scaling = proto.Field( proto.MESSAGE, number=3, oneof="scaling", message="AutomaticScaling", ) - basic_scaling = proto.Field( proto.MESSAGE, number=4, oneof="scaling", message="BasicScaling", ) - manual_scaling = proto.Field( proto.MESSAGE, number=5, oneof="scaling", message="ManualScaling", ) - inbound_services = proto.RepeatedField( proto.ENUM, number=6, enum="InboundServiceType", ) - - instance_class = proto.Field(proto.STRING, number=7) - + instance_class = proto.Field(proto.STRING, number=7,) network = proto.Field(proto.MESSAGE, number=8, message="Network",) - - zones = proto.RepeatedField(proto.STRING, number=118) - + zones = proto.RepeatedField(proto.STRING, number=118,) resources = proto.Field(proto.MESSAGE, number=9, message="Resources",) - - runtime = proto.Field(proto.STRING, number=10) - - runtime_channel = proto.Field(proto.STRING, number=117) - - threadsafe = proto.Field(proto.BOOL, number=11) - - vm = proto.Field(proto.BOOL, number=12) - - beta_settings = proto.MapField(proto.STRING, proto.STRING, number=13) - - env = proto.Field(proto.STRING, number=14) - + runtime = proto.Field(proto.STRING, number=10,) + runtime_channel = proto.Field(proto.STRING, number=117,) + threadsafe = proto.Field(proto.BOOL, number=11,) + vm = proto.Field(proto.BOOL, number=12,) + beta_settings = proto.MapField(proto.STRING, proto.STRING, number=13,) + env = proto.Field(proto.STRING, number=14,) serving_status = proto.Field(proto.ENUM, number=15, enum="ServingStatus",) - - created_by = proto.Field(proto.STRING, number=16) - - create_time = proto.Field(proto.MESSAGE, number=17, message=timestamp.Timestamp,) - - disk_usage_bytes = proto.Field(proto.INT64, number=18) - - runtime_api_version = proto.Field(proto.STRING, number=21) - - runtime_main_executable_path = proto.Field(proto.STRING, number=22) - - service_account = proto.Field(proto.STRING, number=127) - + created_by = proto.Field(proto.STRING, number=16,) + create_time = proto.Field( + proto.MESSAGE, number=17, message=timestamp_pb2.Timestamp, + ) + disk_usage_bytes = proto.Field(proto.INT64, number=18,) + runtime_api_version = proto.Field(proto.STRING, number=21,) + runtime_main_executable_path = proto.Field(proto.STRING, number=22,) + service_account = proto.Field(proto.STRING, number=127,) handlers = proto.RepeatedField(proto.MESSAGE, number=100, message=app_yaml.UrlMap,) - error_handlers = proto.RepeatedField( proto.MESSAGE, number=101, message=app_yaml.ErrorHandler, ) - libraries = proto.RepeatedField( proto.MESSAGE, number=102, message=app_yaml.Library, ) - api_config = proto.Field( proto.MESSAGE, number=103, message=app_yaml.ApiConfigHandler, ) - - env_variables = proto.MapField(proto.STRING, proto.STRING, number=104) - - build_env_variables = proto.MapField(proto.STRING, proto.STRING, number=125) - + env_variables = proto.MapField(proto.STRING, proto.STRING, number=104,) + build_env_variables = proto.MapField(proto.STRING, proto.STRING, number=125,) default_expiration = proto.Field( - proto.MESSAGE, number=105, message=duration.Duration, + proto.MESSAGE, number=105, message=duration_pb2.Duration, ) - health_check = proto.Field(proto.MESSAGE, number=106, message=app_yaml.HealthCheck,) - readiness_check = proto.Field( proto.MESSAGE, number=112, message=app_yaml.ReadinessCheck, ) - liveness_check = proto.Field( proto.MESSAGE, number=113, message=app_yaml.LivenessCheck, ) - - nobuild_files_regex = proto.Field(proto.STRING, number=107) - + nobuild_files_regex = proto.Field(proto.STRING, number=107,) deployment = proto.Field(proto.MESSAGE, number=108, message=deploy.Deployment,) - - version_url = proto.Field(proto.STRING, number=109) - + version_url = proto.Field(proto.STRING, number=109,) endpoints_api_service = proto.Field( proto.MESSAGE, number=110, message="EndpointsApiService", ) - entrypoint = proto.Field(proto.MESSAGE, number=122, message="Entrypoint",) - vpc_access_connector = proto.Field( proto.MESSAGE, number=121, message="VpcAccessConnector", ) @@ -405,13 +366,10 @@ class RolloutStrategy(proto.Enum): FIXED = 1 MANAGED = 2 - name = proto.Field(proto.STRING, number=1) - - config_id = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + config_id = proto.Field(proto.STRING, number=2,) rollout_strategy = proto.Field(proto.ENUM, number=3, enum=RolloutStrategy,) - - disable_trace_sampling = proto.Field(proto.BOOL, number=4) + disable_trace_sampling = proto.Field(proto.BOOL, number=4,) class AutomaticScaling(proto.Message): @@ -465,38 +423,28 @@ class AutomaticScaling(proto.Message): Scheduler settings for standard environment. """ - cool_down_period = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - + cool_down_period = proto.Field( + proto.MESSAGE, number=1, message=duration_pb2.Duration, + ) cpu_utilization = proto.Field(proto.MESSAGE, number=2, message="CpuUtilization",) - - max_concurrent_requests = proto.Field(proto.INT32, number=3) - - max_idle_instances = proto.Field(proto.INT32, number=4) - - max_total_instances = proto.Field(proto.INT32, number=5) - + max_concurrent_requests = proto.Field(proto.INT32, number=3,) + max_idle_instances = proto.Field(proto.INT32, number=4,) + max_total_instances = proto.Field(proto.INT32, number=5,) max_pending_latency = proto.Field( - proto.MESSAGE, number=6, message=duration.Duration, + proto.MESSAGE, number=6, message=duration_pb2.Duration, ) - - min_idle_instances = proto.Field(proto.INT32, number=7) - - min_total_instances = proto.Field(proto.INT32, number=8) - + min_idle_instances = proto.Field(proto.INT32, number=7,) + min_total_instances = proto.Field(proto.INT32, number=8,) min_pending_latency = proto.Field( - proto.MESSAGE, number=9, message=duration.Duration, + proto.MESSAGE, number=9, message=duration_pb2.Duration, ) - request_utilization = proto.Field( proto.MESSAGE, number=10, message="RequestUtilization", ) - disk_utilization = proto.Field(proto.MESSAGE, number=11, message="DiskUtilization",) - network_utilization = proto.Field( proto.MESSAGE, number=12, message="NetworkUtilization", ) - standard_scheduler_settings = proto.Field( proto.MESSAGE, number=20, message="StandardSchedulerSettings", ) @@ -518,9 +466,8 @@ class BasicScaling(proto.Message): this version. """ - idle_timeout = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - max_instances = proto.Field(proto.INT32, number=2) + idle_timeout = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + max_instances = proto.Field(proto.INT32, number=2,) class ManualScaling(proto.Message): @@ -536,12 +483,11 @@ class ManualScaling(proto.Message): ``set_num_instances()`` function. """ - instances = proto.Field(proto.INT32, number=1) + instances = proto.Field(proto.INT32, number=1,) class CpuUtilization(proto.Message): r"""Target scaling by CPU usage. - Attributes: aggregation_window_length (google.protobuf.duration_pb2.Duration): Period of time over which CPU utilization is @@ -552,10 +498,9 @@ class CpuUtilization(proto.Message): """ aggregation_window_length = proto.Field( - proto.MESSAGE, number=1, message=duration.Duration, + proto.MESSAGE, number=1, message=duration_pb2.Duration, ) - - target_utilization = proto.Field(proto.DOUBLE, number=2) + target_utilization = proto.Field(proto.DOUBLE, number=2,) class RequestUtilization(proto.Message): @@ -569,9 +514,8 @@ class RequestUtilization(proto.Message): Target number of concurrent requests. """ - target_request_count_per_second = proto.Field(proto.INT32, number=1) - - target_concurrent_requests = proto.Field(proto.INT32, number=2) + target_request_count_per_second = proto.Field(proto.INT32, number=1,) + target_concurrent_requests = proto.Field(proto.INT32, number=2,) class DiskUtilization(proto.Message): @@ -589,13 +533,10 @@ class DiskUtilization(proto.Message): Target ops read per seconds. """ - target_write_bytes_per_second = proto.Field(proto.INT32, number=14) - - target_write_ops_per_second = proto.Field(proto.INT32, number=15) - - target_read_bytes_per_second = proto.Field(proto.INT32, number=16) - - target_read_ops_per_second = proto.Field(proto.INT32, number=17) + target_write_bytes_per_second = proto.Field(proto.INT32, number=14,) + target_write_ops_per_second = proto.Field(proto.INT32, number=15,) + target_read_bytes_per_second = proto.Field(proto.INT32, number=16,) + target_read_ops_per_second = proto.Field(proto.INT32, number=17,) class NetworkUtilization(proto.Message): @@ -613,18 +554,14 @@ class NetworkUtilization(proto.Message): Target packets received per second. """ - target_sent_bytes_per_second = proto.Field(proto.INT32, number=1) - - target_sent_packets_per_second = proto.Field(proto.INT32, number=11) - - target_received_bytes_per_second = proto.Field(proto.INT32, number=12) - - target_received_packets_per_second = proto.Field(proto.INT32, number=13) + target_sent_bytes_per_second = proto.Field(proto.INT32, number=1,) + target_sent_packets_per_second = proto.Field(proto.INT32, number=11,) + target_received_bytes_per_second = proto.Field(proto.INT32, number=12,) + target_received_packets_per_second = proto.Field(proto.INT32, number=13,) class StandardSchedulerSettings(proto.Message): r"""Scheduler settings for standard environment. - Attributes: target_cpu_utilization (float): Target CPU utilization ratio to maintain when @@ -640,13 +577,10 @@ class StandardSchedulerSettings(proto.Message): zero to disable ``max_instances`` configuration. """ - target_cpu_utilization = proto.Field(proto.DOUBLE, number=1) - - target_throughput_utilization = proto.Field(proto.DOUBLE, number=2) - - min_instances = proto.Field(proto.INT32, number=3) - - max_instances = proto.Field(proto.INT32, number=4) + target_cpu_utilization = proto.Field(proto.DOUBLE, number=1,) + target_throughput_utilization = proto.Field(proto.DOUBLE, number=2,) + min_instances = proto.Field(proto.INT32, number=3,) + max_instances = proto.Field(proto.INT32, number=4,) class Network(proto.Message): @@ -696,15 +630,11 @@ class Network(proto.Message): environment. """ - forwarded_ports = proto.RepeatedField(proto.STRING, number=1) - - instance_tag = proto.Field(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=3) - - subnetwork_name = proto.Field(proto.STRING, number=4) - - session_affinity = proto.Field(proto.BOOL, number=5) + forwarded_ports = proto.RepeatedField(proto.STRING, number=1,) + instance_tag = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=3,) + subnetwork_name = proto.Field(proto.STRING, number=4,) + session_affinity = proto.Field(proto.BOOL, number=5,) class Volume(proto.Message): @@ -720,16 +650,13 @@ class Volume(proto.Message): Volume size in gigabytes. """ - name = proto.Field(proto.STRING, number=1) - - volume_type = proto.Field(proto.STRING, number=2) - - size_gb = proto.Field(proto.DOUBLE, number=3) + name = proto.Field(proto.STRING, number=1,) + volume_type = proto.Field(proto.STRING, number=2,) + size_gb = proto.Field(proto.DOUBLE, number=3,) class Resources(proto.Message): r"""Machine resources for a version. - Attributes: cpu (float): Number of CPU cores needed. @@ -745,20 +672,15 @@ class Resources(proto.Message): Cloud Composer to encrypt the vm disk """ - cpu = proto.Field(proto.DOUBLE, number=1) - - disk_gb = proto.Field(proto.DOUBLE, number=2) - - memory_gb = proto.Field(proto.DOUBLE, number=3) - + cpu = proto.Field(proto.DOUBLE, number=1,) + disk_gb = proto.Field(proto.DOUBLE, number=2,) + memory_gb = proto.Field(proto.DOUBLE, number=3,) volumes = proto.RepeatedField(proto.MESSAGE, number=4, message="Volume",) - - kms_key_reference = proto.Field(proto.STRING, number=5) + kms_key_reference = proto.Field(proto.STRING, number=5,) class VpcAccessConnector(proto.Message): r"""VPC access connector specification. - Attributes: name (str): Full Serverless VPC Access Connector name @@ -766,19 +688,18 @@ class VpcAccessConnector(proto.Message): central1/connectors/c1. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class Entrypoint(proto.Message): r"""The entrypoint for the application. - Attributes: shell (str): The format should be a shell command that can be fed to ``bash -c``. """ - shell = proto.Field(proto.STRING, number=1, oneof="command") + shell = proto.Field(proto.STRING, number=1, oneof="command",) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-appengine-admin/scripts/fixup_appengine_admin_v1_keywords.py b/packages/google-cloud-appengine-admin/scripts/fixup_appengine_admin_v1_keywords.py index 5c6224afb157..977426fc88b3 100644 --- a/packages/google-cloud-appengine-admin/scripts/fixup_appengine_admin_v1_keywords.py +++ b/packages/google-cloud-appengine-admin/scripts/fixup_appengine_admin_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,41 +39,40 @@ def partition( class appengine_adminCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_update_ingress_rules': ('name', 'ingress_rules', ), - 'create_application': ('application', ), - 'create_authorized_certificate': ('parent', 'certificate', ), - 'create_domain_mapping': ('parent', 'domain_mapping', 'override_strategy', ), - 'create_ingress_rule': ('parent', 'rule', ), - 'create_version': ('parent', 'version', ), - 'debug_instance': ('name', 'ssh_key', ), - 'delete_authorized_certificate': ('name', ), - 'delete_domain_mapping': ('name', ), - 'delete_ingress_rule': ('name', ), - 'delete_instance': ('name', ), - 'delete_service': ('name', ), - 'delete_version': ('name', ), - 'get_application': ('name', ), - 'get_authorized_certificate': ('name', 'view', ), - 'get_domain_mapping': ('name', ), - 'get_ingress_rule': ('name', ), - 'get_instance': ('name', ), - 'get_service': ('name', ), - 'get_version': ('name', 'view', ), - 'list_authorized_certificates': ('parent', 'view', 'page_size', 'page_token', ), - 'list_authorized_domains': ('parent', 'page_size', 'page_token', ), - 'list_domain_mappings': ('parent', 'page_size', 'page_token', ), - 'list_ingress_rules': ('parent', 'page_size', 'page_token', 'matching_address', ), - 'list_instances': ('parent', 'page_size', 'page_token', ), - 'list_services': ('parent', 'page_size', 'page_token', ), - 'list_versions': ('parent', 'view', 'page_size', 'page_token', ), - 'repair_application': ('name', ), - 'update_application': ('name', 'application', 'update_mask', ), - 'update_authorized_certificate': ('name', 'certificate', 'update_mask', ), - 'update_domain_mapping': ('name', 'domain_mapping', 'update_mask', ), - 'update_ingress_rule': ('name', 'rule', 'update_mask', ), - 'update_service': ('name', 'service', 'update_mask', 'migrate_traffic', ), - 'update_version': ('name', 'version', 'update_mask', ), - + 'batch_update_ingress_rules': ('name', 'ingress_rules', ), + 'create_application': ('application', ), + 'create_authorized_certificate': ('parent', 'certificate', ), + 'create_domain_mapping': ('parent', 'domain_mapping', 'override_strategy', ), + 'create_ingress_rule': ('parent', 'rule', ), + 'create_version': ('parent', 'version', ), + 'debug_instance': ('name', 'ssh_key', ), + 'delete_authorized_certificate': ('name', ), + 'delete_domain_mapping': ('name', ), + 'delete_ingress_rule': ('name', ), + 'delete_instance': ('name', ), + 'delete_service': ('name', ), + 'delete_version': ('name', ), + 'get_application': ('name', ), + 'get_authorized_certificate': ('name', 'view', ), + 'get_domain_mapping': ('name', ), + 'get_ingress_rule': ('name', ), + 'get_instance': ('name', ), + 'get_service': ('name', ), + 'get_version': ('name', 'view', ), + 'list_authorized_certificates': ('parent', 'view', 'page_size', 'page_token', ), + 'list_authorized_domains': ('parent', 'page_size', 'page_token', ), + 'list_domain_mappings': ('parent', 'page_size', 'page_token', ), + 'list_ingress_rules': ('parent', 'page_size', 'page_token', 'matching_address', ), + 'list_instances': ('parent', 'page_size', 'page_token', ), + 'list_services': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'view', 'page_size', 'page_token', ), + 'repair_application': ('name', ), + 'update_application': ('name', 'application', 'update_mask', ), + 'update_authorized_certificate': ('name', 'certificate', 'update_mask', ), + 'update_domain_mapping': ('name', 'domain_mapping', 'update_mask', ), + 'update_ingress_rule': ('name', 'rule', 'update_mask', ), + 'update_service': ('name', 'service', 'update_mask', 'migrate_traffic', ), + 'update_version': ('name', 'version', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -106,7 +103,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/packages/google-cloud-appengine-admin/tests/__init__.py b/packages/google-cloud-appengine-admin/tests/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-appengine-admin/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-appengine-admin/tests/unit/__init__.py b/packages/google-cloud-appengine-admin/tests/unit/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-appengine-admin/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/__init__.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..4de65971c238 --- /dev/null +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/__init__.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/__init__.py index 42ffdf2bc43d..4de65971c238 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/__init__.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py index 32be11ebc402..c168ab646d1b 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_applications.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.applications import ( ApplicationsAsyncClient, ) from google.cloud.appengine_admin_v1.services.applications import ApplicationsClient from google.cloud.appengine_admin_v1.services.applications import transports +from google.cloud.appengine_admin_v1.services.applications.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.applications.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import application from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,]) def test_applications_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_applications_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,]) def test_applications_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -158,7 +187,7 @@ def test_applications_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ApplicationsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -442,7 +471,7 @@ def test_get_application( transport: str = "grpc", request_type=appengine.GetApplicationRequest ): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -464,37 +493,24 @@ def test_get_application( gcr_domain="gcr_domain_value", database_type=application.Application.DatabaseType.CLOUD_DATASTORE, ) - response = client.get_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, application.Application) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.auth_domain == "auth_domain_value" - assert response.location_id == "location_id_value" - assert response.code_bucket == "code_bucket_value" - assert response.serving_status == application.Application.ServingStatus.SERVING - assert response.default_hostname == "default_hostname_value" - assert response.default_bucket == "default_bucket_value" - assert response.gcr_domain == "gcr_domain_value" - assert ( response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE ) @@ -508,7 +524,7 @@ def test_get_application_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -516,7 +532,6 @@ def test_get_application_empty_call(): client.get_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() @@ -525,7 +540,7 @@ async def test_get_application_async( transport: str = "grpc_asyncio", request_type=appengine.GetApplicationRequest ): client = ApplicationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -549,36 +564,24 @@ async def test_get_application_async( database_type=application.Application.DatabaseType.CLOUD_DATASTORE, ) ) - response = await client.get_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() # Establish that the response is the type that we expect. assert isinstance(response, application.Application) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.auth_domain == "auth_domain_value" - assert response.location_id == "location_id_value" - assert response.code_bucket == "code_bucket_value" - assert response.serving_status == application.Application.ServingStatus.SERVING - assert response.default_hostname == "default_hostname_value" - assert response.default_bucket == "default_bucket_value" - assert response.gcr_domain == "gcr_domain_value" - assert ( response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE ) @@ -590,17 +593,17 @@ async def test_get_application_async_from_dict(): def test_get_application_field_headers(): - client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_application), "__call__") as call: call.return_value = application.Application() - client.get_application(request) # Establish that the underlying gRPC stub method was called. @@ -615,11 +618,12 @@ def test_get_application_field_headers(): @pytest.mark.asyncio async def test_get_application_field_headers_async(): - client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -627,7 +631,6 @@ async def test_get_application_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( application.Application() ) - await client.get_application(request) # Establish that the underlying gRPC stub method was called. @@ -644,7 +647,7 @@ def test_create_application( transport: str = "grpc", request_type=appengine.CreateApplicationRequest ): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -657,13 +660,11 @@ def test_create_application( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() # Establish that the response is the type that we expect. @@ -678,7 +679,7 @@ def test_create_application_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -688,7 +689,6 @@ def test_create_application_empty_call(): client.create_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() @@ -697,7 +697,7 @@ async def test_create_application_async( transport: str = "grpc_asyncio", request_type=appengine.CreateApplicationRequest ): client = ApplicationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -712,13 +712,11 @@ async def test_create_application_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() # Establish that the response is the type that we expect. @@ -734,7 +732,7 @@ def test_update_application( transport: str = "grpc", request_type=appengine.UpdateApplicationRequest ): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -747,13 +745,11 @@ def test_update_application( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() # Establish that the response is the type that we expect. @@ -768,7 +764,7 @@ def test_update_application_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -778,7 +774,6 @@ def test_update_application_empty_call(): client.update_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() @@ -787,7 +782,7 @@ async def test_update_application_async( transport: str = "grpc_asyncio", request_type=appengine.UpdateApplicationRequest ): client = ApplicationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,13 +797,11 @@ async def test_update_application_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() # Establish that the response is the type that we expect. @@ -821,11 +814,12 @@ async def test_update_application_async_from_dict(): def test_update_application_field_headers(): - client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -833,7 +827,6 @@ def test_update_application_field_headers(): type(client.transport.update_application), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_application(request) # Establish that the underlying gRPC stub method was called. @@ -848,11 +841,12 @@ def test_update_application_field_headers(): @pytest.mark.asyncio async def test_update_application_field_headers_async(): - client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -862,7 +856,6 @@ async def test_update_application_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_application(request) # Establish that the underlying gRPC stub method was called. @@ -879,7 +872,7 @@ def test_repair_application( transport: str = "grpc", request_type=appengine.RepairApplicationRequest ): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -892,13 +885,11 @@ def test_repair_application( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.repair_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() # Establish that the response is the type that we expect. @@ -913,7 +904,7 @@ def test_repair_application_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -923,7 +914,6 @@ def test_repair_application_empty_call(): client.repair_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() @@ -932,7 +922,7 @@ async def test_repair_application_async( transport: str = "grpc_asyncio", request_type=appengine.RepairApplicationRequest ): client = ApplicationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -947,13 +937,11 @@ async def test_repair_application_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.repair_application(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() # Establish that the response is the type that we expect. @@ -966,11 +954,12 @@ async def test_repair_application_async_from_dict(): def test_repair_application_field_headers(): - client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.RepairApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -978,7 +967,6 @@ def test_repair_application_field_headers(): type(client.transport.repair_application), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.repair_application(request) # Establish that the underlying gRPC stub method was called. @@ -993,11 +981,12 @@ def test_repair_application_field_headers(): @pytest.mark.asyncio async def test_repair_application_field_headers_async(): - client = ApplicationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.RepairApplicationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1007,7 +996,6 @@ async def test_repair_application_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.repair_application(request) # Establish that the underlying gRPC stub method was called. @@ -1023,16 +1011,16 @@ async def test_repair_application_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ApplicationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ApplicationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ApplicationsClient( @@ -1042,7 +1030,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ApplicationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ApplicationsClient( @@ -1053,7 +1041,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ApplicationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ApplicationsClient(transport=transport) assert client.transport is transport @@ -1062,13 +1050,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ApplicationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ApplicationsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1083,23 +1071,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ApplicationsClient(credentials=credentials.AnonymousCredentials(),) + client = ApplicationsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ApplicationsGrpcTransport,) def test_applications_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ApplicationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1111,7 +1099,7 @@ def test_applications_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ApplicationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1132,15 +1120,41 @@ def test_applications_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_applications_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ApplicationsTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_applications_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ApplicationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1157,19 +1171,37 @@ def test_applications_base_transport_with_credentials_file(): def test_applications_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ApplicationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_applications_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ApplicationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_applications_auth_adc_old_google_auth(): + # 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) ApplicationsClient() adc.assert_called_once_with( scopes=( @@ -1181,14 +1213,45 @@ def test_applications_auth_adc(): ) -def test_applications_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApplicationsGrpcTransport, + transports.ApplicationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_applications_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ApplicationsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApplicationsGrpcTransport, + transports.ApplicationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_applications_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1199,12 +1262,129 @@ def test_applications_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationsGrpcTransport, grpc_helpers), + (transports.ApplicationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_applications_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationsGrpcTransport, grpc_helpers), + (transports.ApplicationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_applications_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationsGrpcTransport, grpc_helpers), + (transports.ApplicationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_applications_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport], ) def test_applications_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1247,7 +1427,7 @@ def test_applications_grpc_transport_client_cert_source_for_mtls(transport_class def test_applications_host_no_port(): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1257,7 +1437,7 @@ def test_applications_host_no_port(): def test_applications_host_with_port(): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1308,9 +1488,9 @@ def test_applications_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1391,7 +1571,7 @@ def test_applications_transport_channel_mtls_with_adc(transport_class): def test_applications_grpc_lro_client(): client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1404,7 +1584,7 @@ def test_applications_grpc_lro_client(): def test_applications_grpc_lro_async_client(): client = ApplicationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1417,7 +1597,6 @@ def test_applications_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1438,7 +1617,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ApplicationsClient.common_folder_path(folder) assert expected == actual @@ -1457,7 +1635,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ApplicationsClient.common_organization_path(organization) assert expected == actual @@ -1476,7 +1653,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ApplicationsClient.common_project_path(project) assert expected == actual @@ -1496,7 +1672,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1523,7 +1698,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ApplicationsTransport, "_prep_wrapped_messages" ) as prep: client = ApplicationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1532,6 +1707,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ApplicationsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py index f93792b6cd1a..590e4063e80a 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.authorized_certificates import ( AuthorizedCertificatesAsyncClient, @@ -40,11 +39,41 @@ ) from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers from google.cloud.appengine_admin_v1.services.authorized_certificates import transports +from google.cloud.appengine_admin_v1.services.authorized_certificates.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.authorized_certificates.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import certificate from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,] ) def test_authorized_certificates_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -113,7 +142,7 @@ def test_authorized_certificates_client_from_service_account_info(client_class): "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,] ) def test_authorized_certificates_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -170,7 +199,7 @@ def test_authorized_certificates_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AuthorizedCertificatesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -476,7 +505,7 @@ def test_list_authorized_certificates( transport: str = "grpc", request_type=appengine.ListAuthorizedCertificatesRequest ): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -491,19 +520,15 @@ def test_list_authorized_certificates( call.return_value = appengine.ListAuthorizedCertificatesResponse( next_page_token="next_page_token_value", ) - response = client.list_authorized_certificates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedCertificatesPager) - assert response.next_page_token == "next_page_token_value" @@ -515,7 +540,7 @@ def test_list_authorized_certificates_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -525,7 +550,6 @@ def test_list_authorized_certificates_empty_call(): client.list_authorized_certificates() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() @@ -535,7 +559,7 @@ async def test_list_authorized_certificates_async( request_type=appengine.ListAuthorizedCertificatesRequest, ): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -552,18 +576,15 @@ async def test_list_authorized_certificates_async( next_page_token="next_page_token_value", ) ) - response = await client.list_authorized_certificates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAuthorizedCertificatesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -574,12 +595,13 @@ async def test_list_authorized_certificates_async_from_dict(): def test_list_authorized_certificates_field_headers(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListAuthorizedCertificatesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -587,7 +609,6 @@ def test_list_authorized_certificates_field_headers(): type(client.transport.list_authorized_certificates), "__call__" ) as call: call.return_value = appengine.ListAuthorizedCertificatesResponse() - client.list_authorized_certificates(request) # Establish that the underlying gRPC stub method was called. @@ -603,12 +624,13 @@ def test_list_authorized_certificates_field_headers(): @pytest.mark.asyncio async def test_list_authorized_certificates_field_headers_async(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListAuthorizedCertificatesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -618,7 +640,6 @@ async def test_list_authorized_certificates_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListAuthorizedCertificatesResponse() ) - await client.list_authorized_certificates(request) # Establish that the underlying gRPC stub method was called. @@ -632,7 +653,9 @@ async def test_list_authorized_certificates_field_headers_async(): def test_list_authorized_certificates_pager(): - client = AuthorizedCertificatesClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -678,7 +701,9 @@ def test_list_authorized_certificates_pager(): def test_list_authorized_certificates_pages(): - client = AuthorizedCertificatesClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -717,7 +742,7 @@ def test_list_authorized_certificates_pages(): @pytest.mark.asyncio async def test_list_authorized_certificates_async_pager(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -764,7 +789,7 @@ async def test_list_authorized_certificates_async_pager(): @pytest.mark.asyncio async def test_list_authorized_certificates_async_pages(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -811,7 +836,7 @@ def test_get_authorized_certificate( transport: str = "grpc", request_type=appengine.GetAuthorizedCertificateRequest ): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -831,29 +856,20 @@ def test_get_authorized_certificate( visible_domain_mappings=["visible_domain_mappings_value"], domain_mappings_count=2238, ) - response = client.get_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -865,7 +881,7 @@ def test_get_authorized_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -875,7 +891,6 @@ def test_get_authorized_certificate_empty_call(): client.get_authorized_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() @@ -885,7 +900,7 @@ async def test_get_authorized_certificate_async( request_type=appengine.GetAuthorizedCertificateRequest, ): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -907,28 +922,20 @@ async def test_get_authorized_certificate_async( domain_mappings_count=2238, ) ) - response = await client.get_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() # Establish that the response is the type that we expect. assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -939,12 +946,13 @@ async def test_get_authorized_certificate_async_from_dict(): def test_get_authorized_certificate_field_headers(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -952,7 +960,6 @@ def test_get_authorized_certificate_field_headers(): type(client.transport.get_authorized_certificate), "__call__" ) as call: call.return_value = certificate.AuthorizedCertificate() - client.get_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -968,12 +975,13 @@ def test_get_authorized_certificate_field_headers(): @pytest.mark.asyncio async def test_get_authorized_certificate_field_headers_async(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -983,7 +991,6 @@ async def test_get_authorized_certificate_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( certificate.AuthorizedCertificate() ) - await client.get_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1000,7 +1007,7 @@ def test_create_authorized_certificate( transport: str = "grpc", request_type=appengine.CreateAuthorizedCertificateRequest ): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1020,29 +1027,20 @@ def test_create_authorized_certificate( visible_domain_mappings=["visible_domain_mappings_value"], domain_mappings_count=2238, ) - response = client.create_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -1054,7 +1052,7 @@ def test_create_authorized_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1062,6 @@ def test_create_authorized_certificate_empty_call(): client.create_authorized_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() @@ -1074,7 +1071,7 @@ async def test_create_authorized_certificate_async( request_type=appengine.CreateAuthorizedCertificateRequest, ): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1096,28 +1093,20 @@ async def test_create_authorized_certificate_async( domain_mappings_count=2238, ) ) - response = await client.create_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() # Establish that the response is the type that we expect. assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -1128,12 +1117,13 @@ async def test_create_authorized_certificate_async_from_dict(): def test_create_authorized_certificate_field_headers(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateAuthorizedCertificateRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1141,7 +1131,6 @@ def test_create_authorized_certificate_field_headers(): type(client.transport.create_authorized_certificate), "__call__" ) as call: call.return_value = certificate.AuthorizedCertificate() - client.create_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1157,12 +1146,13 @@ def test_create_authorized_certificate_field_headers(): @pytest.mark.asyncio async def test_create_authorized_certificate_field_headers_async(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateAuthorizedCertificateRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1172,7 +1162,6 @@ async def test_create_authorized_certificate_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( certificate.AuthorizedCertificate() ) - await client.create_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1189,7 +1178,7 @@ def test_update_authorized_certificate( transport: str = "grpc", request_type=appengine.UpdateAuthorizedCertificateRequest ): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1209,29 +1198,20 @@ def test_update_authorized_certificate( visible_domain_mappings=["visible_domain_mappings_value"], domain_mappings_count=2238, ) - response = client.update_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -1243,7 +1223,7 @@ def test_update_authorized_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1253,7 +1233,6 @@ def test_update_authorized_certificate_empty_call(): client.update_authorized_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() @@ -1263,7 +1242,7 @@ async def test_update_authorized_certificate_async( request_type=appengine.UpdateAuthorizedCertificateRequest, ): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1285,28 +1264,20 @@ async def test_update_authorized_certificate_async( domain_mappings_count=2238, ) ) - response = await client.update_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() # Establish that the response is the type that we expect. assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.display_name == "display_name_value" - assert response.domain_names == ["domain_names_value"] - assert response.visible_domain_mappings == ["visible_domain_mappings_value"] - assert response.domain_mappings_count == 2238 @@ -1317,12 +1288,13 @@ async def test_update_authorized_certificate_async_from_dict(): def test_update_authorized_certificate_field_headers(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1330,7 +1302,6 @@ def test_update_authorized_certificate_field_headers(): type(client.transport.update_authorized_certificate), "__call__" ) as call: call.return_value = certificate.AuthorizedCertificate() - client.update_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1346,12 +1317,13 @@ def test_update_authorized_certificate_field_headers(): @pytest.mark.asyncio async def test_update_authorized_certificate_field_headers_async(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1361,7 +1333,6 @@ async def test_update_authorized_certificate_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( certificate.AuthorizedCertificate() ) - await client.update_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1378,7 +1349,7 @@ def test_delete_authorized_certificate( transport: str = "grpc", request_type=appengine.DeleteAuthorizedCertificateRequest ): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1391,13 +1362,11 @@ def test_delete_authorized_certificate( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() # Establish that the response is the type that we expect. @@ -1412,7 +1381,7 @@ def test_delete_authorized_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1422,7 +1391,6 @@ def test_delete_authorized_certificate_empty_call(): client.delete_authorized_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() @@ -1432,7 +1400,7 @@ async def test_delete_authorized_certificate_async( request_type=appengine.DeleteAuthorizedCertificateRequest, ): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1445,13 +1413,11 @@ async def test_delete_authorized_certificate_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() # Establish that the response is the type that we expect. @@ -1465,12 +1431,13 @@ async def test_delete_authorized_certificate_async_from_dict(): def test_delete_authorized_certificate_field_headers(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1478,7 +1445,6 @@ def test_delete_authorized_certificate_field_headers(): type(client.transport.delete_authorized_certificate), "__call__" ) as call: call.return_value = None - client.delete_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1494,12 +1460,13 @@ def test_delete_authorized_certificate_field_headers(): @pytest.mark.asyncio async def test_delete_authorized_certificate_field_headers_async(): client = AuthorizedCertificatesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteAuthorizedCertificateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1507,7 +1474,6 @@ async def test_delete_authorized_certificate_field_headers_async(): type(client.transport.delete_authorized_certificate), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_authorized_certificate(request) # Establish that the underlying gRPC stub method was called. @@ -1523,16 +1489,16 @@ async def test_delete_authorized_certificate_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedCertificatesClient( @@ -1542,7 +1508,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedCertificatesClient( @@ -1553,7 +1519,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AuthorizedCertificatesClient(transport=transport) assert client.transport is transport @@ -1562,13 +1528,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1583,8 +1549,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -1592,16 +1558,16 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance(client.transport, transports.AuthorizedCertificatesGrpcTransport,) def test_authorized_certificates_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AuthorizedCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1613,7 +1579,7 @@ def test_authorized_certificates_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AuthorizedCertificatesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1630,15 +1596,41 @@ def test_authorized_certificates_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_authorized_certificates_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedCertificatesTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AuthorizedCertificatesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1655,19 +1647,37 @@ def test_authorized_certificates_base_transport_with_credentials_file(): def test_authorized_certificates_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AuthorizedCertificatesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_authorized_certificates_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedCertificatesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_auth_adc_old_google_auth(): + # 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) AuthorizedCertificatesClient() adc.assert_called_once_with( scopes=( @@ -1679,14 +1689,45 @@ def test_authorized_certificates_auth_adc(): ) -def test_authorized_certificates_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedCertificatesGrpcTransport, + transports.AuthorizedCertificatesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_authorized_certificates_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AuthorizedCertificatesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedCertificatesGrpcTransport, + transports.AuthorizedCertificatesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1697,6 +1738,125 @@ def test_authorized_certificates_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedCertificatesGrpcTransport, grpc_helpers), + (transports.AuthorizedCertificatesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_authorized_certificates_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedCertificatesGrpcTransport, grpc_helpers), + (transports.AuthorizedCertificatesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_authorized_certificates_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedCertificatesGrpcTransport, grpc_helpers), + (transports.AuthorizedCertificatesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_authorized_certificates_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1707,7 +1867,7 @@ def test_authorized_certificates_transport_auth_adc(): def test_authorized_certificates_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1750,7 +1910,7 @@ def test_authorized_certificates_grpc_transport_client_cert_source_for_mtls( def test_authorized_certificates_host_no_port(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1760,7 +1920,7 @@ def test_authorized_certificates_host_no_port(): def test_authorized_certificates_host_with_port(): client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1816,9 +1976,9 @@ def test_authorized_certificates_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1902,7 +2062,6 @@ def test_authorized_certificates_transport_channel_mtls_with_adc(transport_class def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1923,7 +2082,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AuthorizedCertificatesClient.common_folder_path(folder) assert expected == actual @@ -1942,7 +2100,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AuthorizedCertificatesClient.common_organization_path(organization) assert expected == actual @@ -1961,7 +2118,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AuthorizedCertificatesClient.common_project_path(project) assert expected == actual @@ -1981,7 +2137,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2008,7 +2163,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AuthorizedCertificatesTransport, "_prep_wrapped_messages" ) as prep: client = AuthorizedCertificatesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2017,6 +2172,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AuthorizedCertificatesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py index b40fd88449a4..65e843f3a60d 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.authorized_domains import ( AuthorizedDomainsAsyncClient, @@ -40,9 +39,39 @@ ) from google.cloud.appengine_admin_v1.services.authorized_domains import pagers from google.cloud.appengine_admin_v1.services.authorized_domains import transports +from google.cloud.appengine_admin_v1.services.authorized_domains.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.authorized_domains.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,] ) def test_authorized_domains_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_authorized_domains_client_from_service_account_info(client_class): "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,] ) def test_authorized_domains_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -164,7 +193,7 @@ def test_authorized_domains_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AuthorizedDomainsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -462,7 +491,7 @@ def test_list_authorized_domains( transport: str = "grpc", request_type=appengine.ListAuthorizedDomainsRequest ): client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -477,19 +506,15 @@ def test_list_authorized_domains( call.return_value = appengine.ListAuthorizedDomainsResponse( next_page_token="next_page_token_value", ) - response = client.list_authorized_domains(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedDomainsPager) - assert response.next_page_token == "next_page_token_value" @@ -501,7 +526,7 @@ def test_list_authorized_domains_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -511,7 +536,6 @@ def test_list_authorized_domains_empty_call(): client.list_authorized_domains() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() @@ -520,7 +544,7 @@ async def test_list_authorized_domains_async( transport: str = "grpc_asyncio", request_type=appengine.ListAuthorizedDomainsRequest ): client = AuthorizedDomainsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -537,18 +561,15 @@ async def test_list_authorized_domains_async( next_page_token="next_page_token_value", ) ) - response = await client.list_authorized_domains(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAuthorizedDomainsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -558,11 +579,12 @@ async def test_list_authorized_domains_async_from_dict(): def test_list_authorized_domains_field_headers(): - client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials(),) + client = AuthorizedDomainsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListAuthorizedDomainsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -570,7 +592,6 @@ def test_list_authorized_domains_field_headers(): type(client.transport.list_authorized_domains), "__call__" ) as call: call.return_value = appengine.ListAuthorizedDomainsResponse() - client.list_authorized_domains(request) # Establish that the underlying gRPC stub method was called. @@ -586,12 +607,13 @@ def test_list_authorized_domains_field_headers(): @pytest.mark.asyncio async def test_list_authorized_domains_field_headers_async(): client = AuthorizedDomainsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListAuthorizedDomainsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -601,7 +623,6 @@ async def test_list_authorized_domains_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListAuthorizedDomainsResponse() ) - await client.list_authorized_domains(request) # Establish that the underlying gRPC stub method was called. @@ -615,7 +636,7 @@ async def test_list_authorized_domains_field_headers_async(): def test_list_authorized_domains_pager(): - client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedDomainsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -655,7 +676,7 @@ def test_list_authorized_domains_pager(): def test_list_authorized_domains_pages(): - client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedDomainsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -687,7 +708,9 @@ def test_list_authorized_domains_pages(): @pytest.mark.asyncio async def test_list_authorized_domains_async_pager(): - client = AuthorizedDomainsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedDomainsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -726,7 +749,9 @@ async def test_list_authorized_domains_async_pager(): @pytest.mark.asyncio async def test_list_authorized_domains_async_pages(): - client = AuthorizedDomainsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AuthorizedDomainsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -763,16 +788,16 @@ async def test_list_authorized_domains_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AuthorizedDomainsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AuthorizedDomainsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedDomainsClient( @@ -782,7 +807,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AuthorizedDomainsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AuthorizedDomainsClient( @@ -793,7 +818,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AuthorizedDomainsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AuthorizedDomainsClient(transport=transport) assert client.transport is transport @@ -802,13 +827,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AuthorizedDomainsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AuthorizedDomainsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -823,23 +848,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AuthorizedDomainsClient(credentials=credentials.AnonymousCredentials(),) + client = AuthorizedDomainsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AuthorizedDomainsGrpcTransport,) def test_authorized_domains_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AuthorizedDomainsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -851,7 +876,7 @@ def test_authorized_domains_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AuthorizedDomainsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -862,15 +887,41 @@ def test_authorized_domains_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_authorized_domains_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedDomainsTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AuthorizedDomainsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -887,19 +938,37 @@ def test_authorized_domains_base_transport_with_credentials_file(): def test_authorized_domains_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AuthorizedDomainsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_authorized_domains_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedDomainsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_auth_adc_old_google_auth(): + # 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) AuthorizedDomainsClient() adc.assert_called_once_with( scopes=( @@ -911,14 +980,45 @@ def test_authorized_domains_auth_adc(): ) -def test_authorized_domains_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedDomainsGrpcTransport, + transports.AuthorizedDomainsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_authorized_domains_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AuthorizedDomainsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedDomainsGrpcTransport, + transports.AuthorizedDomainsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -929,6 +1029,123 @@ def test_authorized_domains_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedDomainsGrpcTransport, grpc_helpers), + (transports.AuthorizedDomainsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_authorized_domains_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedDomainsGrpcTransport, grpc_helpers), + (transports.AuthorizedDomainsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_authorized_domains_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedDomainsGrpcTransport, grpc_helpers), + (transports.AuthorizedDomainsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_authorized_domains_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -937,7 +1154,7 @@ def test_authorized_domains_transport_auth_adc(): ], ) def test_authorized_domains_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -980,7 +1197,7 @@ def test_authorized_domains_grpc_transport_client_cert_source_for_mtls(transport def test_authorized_domains_host_no_port(): client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -990,7 +1207,7 @@ def test_authorized_domains_host_no_port(): def test_authorized_domains_host_with_port(): client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1046,9 +1263,9 @@ def test_authorized_domains_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1132,7 +1349,6 @@ def test_authorized_domains_transport_channel_mtls_with_adc(transport_class): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1153,7 +1369,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AuthorizedDomainsClient.common_folder_path(folder) assert expected == actual @@ -1172,7 +1387,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AuthorizedDomainsClient.common_organization_path(organization) assert expected == actual @@ -1191,7 +1405,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AuthorizedDomainsClient.common_project_path(project) assert expected == actual @@ -1211,7 +1424,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1238,7 +1450,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AuthorizedDomainsTransport, "_prep_wrapped_messages" ) as prep: client = AuthorizedDomainsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1247,6 +1459,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AuthorizedDomainsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py index 1a995d8ac7af..05d9d6bfcfcb 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.domain_mappings import ( DomainMappingsAsyncClient, @@ -43,12 +42,42 @@ ) from google.cloud.appengine_admin_v1.services.domain_mappings import pagers from google.cloud.appengine_admin_v1.services.domain_mappings import transports +from google.cloud.appengine_admin_v1.services.domain_mappings.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.domain_mappings.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import domain_mapping from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,] ) def test_domain_mappings_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -116,7 +145,7 @@ def test_domain_mappings_client_from_service_account_info(client_class): "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,] ) def test_domain_mappings_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -169,7 +198,7 @@ def test_domain_mappings_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(DomainMappingsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -457,7 +486,7 @@ def test_list_domain_mappings( transport: str = "grpc", request_type=appengine.ListDomainMappingsRequest ): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -472,19 +501,15 @@ def test_list_domain_mappings( call.return_value = appengine.ListDomainMappingsResponse( next_page_token="next_page_token_value", ) - response = client.list_domain_mappings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDomainMappingsPager) - assert response.next_page_token == "next_page_token_value" @@ -496,7 +521,7 @@ def test_list_domain_mappings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -506,7 +531,6 @@ def test_list_domain_mappings_empty_call(): client.list_domain_mappings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() @@ -515,7 +539,7 @@ async def test_list_domain_mappings_async( transport: str = "grpc_asyncio", request_type=appengine.ListDomainMappingsRequest ): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -532,18 +556,15 @@ async def test_list_domain_mappings_async( next_page_token="next_page_token_value", ) ) - response = await client.list_domain_mappings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDomainMappingsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -553,11 +574,12 @@ async def test_list_domain_mappings_async_from_dict(): def test_list_domain_mappings_field_headers(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListDomainMappingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -565,7 +587,6 @@ def test_list_domain_mappings_field_headers(): type(client.transport.list_domain_mappings), "__call__" ) as call: call.return_value = appengine.ListDomainMappingsResponse() - client.list_domain_mappings(request) # Establish that the underlying gRPC stub method was called. @@ -580,11 +601,14 @@ def test_list_domain_mappings_field_headers(): @pytest.mark.asyncio async def test_list_domain_mappings_field_headers_async(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListDomainMappingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -594,7 +618,6 @@ async def test_list_domain_mappings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListDomainMappingsResponse() ) - await client.list_domain_mappings(request) # Establish that the underlying gRPC stub method was called. @@ -608,7 +631,7 @@ async def test_list_domain_mappings_field_headers_async(): def test_list_domain_mappings_pager(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials,) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -654,7 +677,7 @@ def test_list_domain_mappings_pager(): def test_list_domain_mappings_pages(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials,) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -692,7 +715,7 @@ def test_list_domain_mappings_pages(): @pytest.mark.asyncio async def test_list_domain_mappings_async_pager(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DomainMappingsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -737,7 +760,7 @@ async def test_list_domain_mappings_async_pager(): @pytest.mark.asyncio async def test_list_domain_mappings_async_pages(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DomainMappingsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -781,7 +804,7 @@ def test_get_domain_mapping( transport: str = "grpc", request_type=appengine.GetDomainMappingRequest ): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -796,21 +819,16 @@ def test_get_domain_mapping( call.return_value = domain_mapping.DomainMapping( name="name_value", id="id_value", ) - response = client.get_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, domain_mapping.DomainMapping) - assert response.name == "name_value" - assert response.id == "id_value" @@ -822,7 +840,7 @@ def test_get_domain_mapping_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +850,6 @@ def test_get_domain_mapping_empty_call(): client.get_domain_mapping() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() @@ -841,7 +858,7 @@ async def test_get_domain_mapping_async( transport: str = "grpc_asyncio", request_type=appengine.GetDomainMappingRequest ): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -856,20 +873,16 @@ async def test_get_domain_mapping_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( domain_mapping.DomainMapping(name="name_value", id="id_value",) ) - response = await client.get_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() # Establish that the response is the type that we expect. assert isinstance(response, domain_mapping.DomainMapping) - assert response.name == "name_value" - assert response.id == "id_value" @@ -879,11 +892,12 @@ async def test_get_domain_mapping_async_from_dict(): def test_get_domain_mapping_field_headers(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -891,7 +905,6 @@ def test_get_domain_mapping_field_headers(): type(client.transport.get_domain_mapping), "__call__" ) as call: call.return_value = domain_mapping.DomainMapping() - client.get_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -906,11 +919,14 @@ def test_get_domain_mapping_field_headers(): @pytest.mark.asyncio async def test_get_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -920,7 +936,6 @@ async def test_get_domain_mapping_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( domain_mapping.DomainMapping() ) - await client.get_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -937,7 +952,7 @@ def test_create_domain_mapping( transport: str = "grpc", request_type=appengine.CreateDomainMappingRequest ): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -950,13 +965,11 @@ def test_create_domain_mapping( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() # Establish that the response is the type that we expect. @@ -971,7 +984,7 @@ def test_create_domain_mapping_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -981,7 +994,6 @@ def test_create_domain_mapping_empty_call(): client.create_domain_mapping() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() @@ -990,7 +1002,7 @@ async def test_create_domain_mapping_async( transport: str = "grpc_asyncio", request_type=appengine.CreateDomainMappingRequest ): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1005,13 +1017,11 @@ async def test_create_domain_mapping_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() # Establish that the response is the type that we expect. @@ -1024,11 +1034,12 @@ async def test_create_domain_mapping_async_from_dict(): def test_create_domain_mapping_field_headers(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateDomainMappingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1036,7 +1047,6 @@ def test_create_domain_mapping_field_headers(): type(client.transport.create_domain_mapping), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1051,11 +1061,14 @@ def test_create_domain_mapping_field_headers(): @pytest.mark.asyncio async def test_create_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateDomainMappingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1065,7 +1078,6 @@ async def test_create_domain_mapping_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1082,7 +1094,7 @@ def test_update_domain_mapping( transport: str = "grpc", request_type=appengine.UpdateDomainMappingRequest ): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1095,13 +1107,11 @@ def test_update_domain_mapping( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() # Establish that the response is the type that we expect. @@ -1116,7 +1126,7 @@ def test_update_domain_mapping_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1126,7 +1136,6 @@ def test_update_domain_mapping_empty_call(): client.update_domain_mapping() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() @@ -1135,7 +1144,7 @@ async def test_update_domain_mapping_async( transport: str = "grpc_asyncio", request_type=appengine.UpdateDomainMappingRequest ): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1150,13 +1159,11 @@ async def test_update_domain_mapping_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() # Establish that the response is the type that we expect. @@ -1169,11 +1176,12 @@ async def test_update_domain_mapping_async_from_dict(): def test_update_domain_mapping_field_headers(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1181,7 +1189,6 @@ def test_update_domain_mapping_field_headers(): type(client.transport.update_domain_mapping), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1196,11 +1203,14 @@ def test_update_domain_mapping_field_headers(): @pytest.mark.asyncio async def test_update_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1210,7 +1220,6 @@ async def test_update_domain_mapping_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1227,7 +1236,7 @@ def test_delete_domain_mapping( transport: str = "grpc", request_type=appengine.DeleteDomainMappingRequest ): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1240,13 +1249,11 @@ def test_delete_domain_mapping( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() # Establish that the response is the type that we expect. @@ -1261,7 +1268,7 @@ def test_delete_domain_mapping_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1271,7 +1278,6 @@ def test_delete_domain_mapping_empty_call(): client.delete_domain_mapping() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() @@ -1280,7 +1286,7 @@ async def test_delete_domain_mapping_async( transport: str = "grpc_asyncio", request_type=appengine.DeleteDomainMappingRequest ): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1295,13 +1301,11 @@ async def test_delete_domain_mapping_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_domain_mapping(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() # Establish that the response is the type that we expect. @@ -1314,11 +1318,12 @@ async def test_delete_domain_mapping_async_from_dict(): def test_delete_domain_mapping_field_headers(): - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1326,7 +1331,6 @@ def test_delete_domain_mapping_field_headers(): type(client.transport.delete_domain_mapping), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1341,11 +1345,14 @@ def test_delete_domain_mapping_field_headers(): @pytest.mark.asyncio async def test_delete_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteDomainMappingRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1355,7 +1362,6 @@ async def test_delete_domain_mapping_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_domain_mapping(request) # Establish that the underlying gRPC stub method was called. @@ -1371,16 +1377,16 @@ async def test_delete_domain_mapping_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DomainMappingsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.DomainMappingsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DomainMappingsClient( @@ -1390,7 +1396,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DomainMappingsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DomainMappingsClient( @@ -1401,7 +1407,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DomainMappingsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DomainMappingsClient(transport=transport) assert client.transport is transport @@ -1410,13 +1416,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DomainMappingsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DomainMappingsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1431,23 +1437,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = DomainMappingsClient(credentials=credentials.AnonymousCredentials(),) + client = DomainMappingsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DomainMappingsGrpcTransport,) def test_domain_mappings_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DomainMappingsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1459,7 +1465,7 @@ def test_domain_mappings_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DomainMappingsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1481,15 +1487,41 @@ def test_domain_mappings_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_domain_mappings_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainMappingsTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DomainMappingsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1506,19 +1538,37 @@ def test_domain_mappings_base_transport_with_credentials_file(): def test_domain_mappings_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DomainMappingsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_domain_mappings_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DomainMappingsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_auth_adc_old_google_auth(): + # 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) DomainMappingsClient() adc.assert_called_once_with( scopes=( @@ -1530,14 +1580,45 @@ def test_domain_mappings_auth_adc(): ) -def test_domain_mappings_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainMappingsGrpcTransport, + transports.DomainMappingsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_domain_mappings_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.DomainMappingsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainMappingsGrpcTransport, + transports.DomainMappingsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1548,6 +1629,123 @@ def test_domain_mappings_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DomainMappingsGrpcTransport, grpc_helpers), + (transports.DomainMappingsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_domain_mappings_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DomainMappingsGrpcTransport, grpc_helpers), + (transports.DomainMappingsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_domain_mappings_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DomainMappingsGrpcTransport, grpc_helpers), + (transports.DomainMappingsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_domain_mappings_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1556,7 +1754,7 @@ def test_domain_mappings_transport_auth_adc(): ], ) def test_domain_mappings_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1599,7 +1797,7 @@ def test_domain_mappings_grpc_transport_client_cert_source_for_mtls(transport_cl def test_domain_mappings_host_no_port(): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1609,7 +1807,7 @@ def test_domain_mappings_host_no_port(): def test_domain_mappings_host_with_port(): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1665,9 +1863,9 @@ def test_domain_mappings_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1751,7 +1949,7 @@ def test_domain_mappings_transport_channel_mtls_with_adc(transport_class): def test_domain_mappings_grpc_lro_client(): client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1764,7 +1962,7 @@ def test_domain_mappings_grpc_lro_client(): def test_domain_mappings_grpc_lro_async_client(): client = DomainMappingsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1777,7 +1975,6 @@ def test_domain_mappings_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1798,7 +1995,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = DomainMappingsClient.common_folder_path(folder) assert expected == actual @@ -1817,7 +2013,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = DomainMappingsClient.common_organization_path(organization) assert expected == actual @@ -1836,7 +2031,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = DomainMappingsClient.common_project_path(project) assert expected == actual @@ -1856,7 +2050,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1883,7 +2076,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DomainMappingsTransport, "_prep_wrapped_messages" ) as prep: client = DomainMappingsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1892,6 +2085,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DomainMappingsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py index 945a7c365bd0..303a69ac8c0f 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_firewall.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.firewall import FirewallAsyncClient from google.cloud.appengine_admin_v1.services.firewall import FirewallClient from google.cloud.appengine_admin_v1.services.firewall import pagers from google.cloud.appengine_admin_v1.services.firewall import transports +from google.cloud.appengine_admin_v1.services.firewall.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.firewall.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import firewall from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -83,7 +112,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,]) def test_firewall_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +127,7 @@ def test_firewall_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,]) def test_firewall_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_firewall_client_get_transport_class(): def test_firewall_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(FirewallClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -419,7 +448,7 @@ def test_list_ingress_rules( transport: str = "grpc", request_type=appengine.ListIngressRulesRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -434,19 +463,15 @@ def test_list_ingress_rules( call.return_value = appengine.ListIngressRulesResponse( next_page_token="next_page_token_value", ) - response = client.list_ingress_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIngressRulesPager) - assert response.next_page_token == "next_page_token_value" @@ -458,7 +483,7 @@ def test_list_ingress_rules_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -468,7 +493,6 @@ def test_list_ingress_rules_empty_call(): client.list_ingress_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() @@ -477,7 +501,7 @@ async def test_list_ingress_rules_async( transport: str = "grpc_asyncio", request_type=appengine.ListIngressRulesRequest ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -492,18 +516,15 @@ async def test_list_ingress_rules_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListIngressRulesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_ingress_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListIngressRulesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -513,11 +534,12 @@ async def test_list_ingress_rules_async_from_dict(): def test_list_ingress_rules_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListIngressRulesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -525,7 +547,6 @@ def test_list_ingress_rules_field_headers(): type(client.transport.list_ingress_rules), "__call__" ) as call: call.return_value = appengine.ListIngressRulesResponse() - client.list_ingress_rules(request) # Establish that the underlying gRPC stub method was called. @@ -540,11 +561,12 @@ def test_list_ingress_rules_field_headers(): @pytest.mark.asyncio async def test_list_ingress_rules_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListIngressRulesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -554,7 +576,6 @@ async def test_list_ingress_rules_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListIngressRulesResponse() ) - await client.list_ingress_rules(request) # Establish that the underlying gRPC stub method was called. @@ -568,7 +589,7 @@ async def test_list_ingress_rules_field_headers_async(): def test_list_ingress_rules_pager(): - client = FirewallClient(credentials=credentials.AnonymousCredentials,) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -610,7 +631,7 @@ def test_list_ingress_rules_pager(): def test_list_ingress_rules_pages(): - client = FirewallClient(credentials=credentials.AnonymousCredentials,) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -644,7 +665,7 @@ def test_list_ingress_rules_pages(): @pytest.mark.asyncio async def test_list_ingress_rules_async_pager(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -685,7 +706,7 @@ async def test_list_ingress_rules_async_pager(): @pytest.mark.asyncio async def test_list_ingress_rules_async_pages(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -725,7 +746,7 @@ def test_batch_update_ingress_rules( transport: str = "grpc", request_type=appengine.BatchUpdateIngressRulesRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -738,17 +759,14 @@ def test_batch_update_ingress_rules( ) as call: # Designate an appropriate return value for the call. call.return_value = appengine.BatchUpdateIngressRulesResponse() - response = client.batch_update_ingress_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, appengine.BatchUpdateIngressRulesResponse) @@ -760,7 +778,7 @@ def test_batch_update_ingress_rules_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -770,7 +788,6 @@ def test_batch_update_ingress_rules_empty_call(): client.batch_update_ingress_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() @@ -780,7 +797,7 @@ async def test_batch_update_ingress_rules_async( request_type=appengine.BatchUpdateIngressRulesRequest, ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -795,13 +812,11 @@ async def test_batch_update_ingress_rules_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.BatchUpdateIngressRulesResponse() ) - response = await client.batch_update_ingress_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() # Establish that the response is the type that we expect. @@ -814,11 +829,12 @@ async def test_batch_update_ingress_rules_async_from_dict(): def test_batch_update_ingress_rules_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.BatchUpdateIngressRulesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -826,7 +842,6 @@ def test_batch_update_ingress_rules_field_headers(): type(client.transport.batch_update_ingress_rules), "__call__" ) as call: call.return_value = appengine.BatchUpdateIngressRulesResponse() - client.batch_update_ingress_rules(request) # Establish that the underlying gRPC stub method was called. @@ -841,11 +856,12 @@ def test_batch_update_ingress_rules_field_headers(): @pytest.mark.asyncio async def test_batch_update_ingress_rules_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.BatchUpdateIngressRulesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -855,7 +871,6 @@ async def test_batch_update_ingress_rules_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.BatchUpdateIngressRulesResponse() ) - await client.batch_update_ingress_rules(request) # Establish that the underlying gRPC stub method was called. @@ -872,7 +887,7 @@ def test_create_ingress_rule( transport: str = "grpc", request_type=appengine.CreateIngressRuleRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -890,25 +905,18 @@ def test_create_ingress_rule( source_range="source_range_value", description="description_value", ) - response = client.create_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -920,7 +928,7 @@ def test_create_ingress_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -930,7 +938,6 @@ def test_create_ingress_rule_empty_call(): client.create_ingress_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() @@ -939,7 +946,7 @@ async def test_create_ingress_rule_async( transport: str = "grpc_asyncio", request_type=appengine.CreateIngressRuleRequest ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -959,24 +966,18 @@ async def test_create_ingress_rule_async( description="description_value", ) ) - response = await client.create_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() # Establish that the response is the type that we expect. assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -986,11 +987,12 @@ async def test_create_ingress_rule_async_from_dict(): def test_create_ingress_rule_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateIngressRuleRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -998,7 +1000,6 @@ def test_create_ingress_rule_field_headers(): type(client.transport.create_ingress_rule), "__call__" ) as call: call.return_value = firewall.FirewallRule() - client.create_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1013,11 +1014,12 @@ def test_create_ingress_rule_field_headers(): @pytest.mark.asyncio async def test_create_ingress_rule_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateIngressRuleRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1027,7 +1029,6 @@ async def test_create_ingress_rule_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( firewall.FirewallRule() ) - await client.create_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1044,7 +1045,7 @@ def test_get_ingress_rule( transport: str = "grpc", request_type=appengine.GetIngressRuleRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1060,25 +1061,18 @@ def test_get_ingress_rule( source_range="source_range_value", description="description_value", ) - response = client.get_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -1090,7 +1084,7 @@ def test_get_ingress_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1098,7 +1092,6 @@ def test_get_ingress_rule_empty_call(): client.get_ingress_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() @@ -1107,7 +1100,7 @@ async def test_get_ingress_rule_async( transport: str = "grpc_asyncio", request_type=appengine.GetIngressRuleRequest ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1125,24 +1118,18 @@ async def test_get_ingress_rule_async( description="description_value", ) ) - response = await client.get_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() # Establish that the response is the type that we expect. assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -1152,17 +1139,17 @@ async def test_get_ingress_rule_async_from_dict(): def test_get_ingress_rule_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_ingress_rule), "__call__") as call: call.return_value = firewall.FirewallRule() - client.get_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1177,11 +1164,12 @@ def test_get_ingress_rule_field_headers(): @pytest.mark.asyncio async def test_get_ingress_rule_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1189,7 +1177,6 @@ async def test_get_ingress_rule_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( firewall.FirewallRule() ) - await client.get_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1206,7 +1193,7 @@ def test_update_ingress_rule( transport: str = "grpc", request_type=appengine.UpdateIngressRuleRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1224,25 +1211,18 @@ def test_update_ingress_rule( source_range="source_range_value", description="description_value", ) - response = client.update_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -1254,7 +1234,7 @@ def test_update_ingress_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1264,7 +1244,6 @@ def test_update_ingress_rule_empty_call(): client.update_ingress_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() @@ -1273,7 +1252,7 @@ async def test_update_ingress_rule_async( transport: str = "grpc_asyncio", request_type=appengine.UpdateIngressRuleRequest ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1293,24 +1272,18 @@ async def test_update_ingress_rule_async( description="description_value", ) ) - response = await client.update_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() # Establish that the response is the type that we expect. assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == "source_range_value" - assert response.description == "description_value" @@ -1320,11 +1293,12 @@ async def test_update_ingress_rule_async_from_dict(): def test_update_ingress_rule_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1332,7 +1306,6 @@ def test_update_ingress_rule_field_headers(): type(client.transport.update_ingress_rule), "__call__" ) as call: call.return_value = firewall.FirewallRule() - client.update_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1347,11 +1320,12 @@ def test_update_ingress_rule_field_headers(): @pytest.mark.asyncio async def test_update_ingress_rule_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1361,7 +1335,6 @@ async def test_update_ingress_rule_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( firewall.FirewallRule() ) - await client.update_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1378,7 +1351,7 @@ def test_delete_ingress_rule( transport: str = "grpc", request_type=appengine.DeleteIngressRuleRequest ): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1391,13 +1364,11 @@ def test_delete_ingress_rule( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() # Establish that the response is the type that we expect. @@ -1412,7 +1383,7 @@ def test_delete_ingress_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1422,7 +1393,6 @@ def test_delete_ingress_rule_empty_call(): client.delete_ingress_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() @@ -1431,7 +1401,7 @@ async def test_delete_ingress_rule_async( transport: str = "grpc_asyncio", request_type=appengine.DeleteIngressRuleRequest ): client = FirewallAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1444,13 +1414,11 @@ async def test_delete_ingress_rule_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_ingress_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() # Establish that the response is the type that we expect. @@ -1463,11 +1431,12 @@ async def test_delete_ingress_rule_async_from_dict(): def test_delete_ingress_rule_field_headers(): - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1475,7 +1444,6 @@ def test_delete_ingress_rule_field_headers(): type(client.transport.delete_ingress_rule), "__call__" ) as call: call.return_value = None - client.delete_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1490,11 +1458,12 @@ def test_delete_ingress_rule_field_headers(): @pytest.mark.asyncio async def test_delete_ingress_rule_field_headers_async(): - client = FirewallAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteIngressRuleRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1502,7 +1471,6 @@ async def test_delete_ingress_rule_field_headers_async(): type(client.transport.delete_ingress_rule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_ingress_rule(request) # Establish that the underlying gRPC stub method was called. @@ -1518,16 +1486,16 @@ async def test_delete_ingress_rule_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.FirewallGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.FirewallGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallClient( @@ -1537,7 +1505,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.FirewallGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FirewallClient( @@ -1548,7 +1516,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.FirewallGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = FirewallClient(transport=transport) assert client.transport is transport @@ -1557,13 +1525,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.FirewallGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.FirewallGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1575,23 +1543,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = FirewallClient(credentials=credentials.AnonymousCredentials(),) + client = FirewallClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.FirewallGrpcTransport,) def test_firewall_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.FirewallTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1603,7 +1571,7 @@ def test_firewall_base_transport(): ) as Transport: Transport.return_value = None transport = transports.FirewallTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1621,15 +1589,41 @@ def test_firewall_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_firewall_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FirewallTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1646,19 +1640,37 @@ def test_firewall_base_transport_with_credentials_file(): def test_firewall_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FirewallTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_firewall_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FirewallClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_auth_adc_old_google_auth(): + # 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) FirewallClient() adc.assert_called_once_with( scopes=( @@ -1670,14 +1682,39 @@ def test_firewall_auth_adc(): ) -def test_firewall_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_firewall_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.FirewallGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_firewall_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1688,12 +1725,125 @@ def test_firewall_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FirewallGrpcTransport, grpc_helpers), + (transports.FirewallGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_firewall_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FirewallGrpcTransport, grpc_helpers), + (transports.FirewallGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_firewall_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FirewallGrpcTransport, grpc_helpers), + (transports.FirewallGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_firewall_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport], ) def test_firewall_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1736,7 +1886,7 @@ def test_firewall_grpc_transport_client_cert_source_for_mtls(transport_class): def test_firewall_host_no_port(): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1746,7 +1896,7 @@ def test_firewall_host_no_port(): def test_firewall_host_with_port(): client = FirewallClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1797,9 +1947,9 @@ def test_firewall_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1880,7 +2030,6 @@ def test_firewall_transport_channel_mtls_with_adc(transport_class): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1901,7 +2050,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = FirewallClient.common_folder_path(folder) assert expected == actual @@ -1920,7 +2068,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = FirewallClient.common_organization_path(organization) assert expected == actual @@ -1939,7 +2086,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = FirewallClient.common_project_path(project) assert expected == actual @@ -1959,7 +2105,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1986,7 +2131,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.FirewallTransport, "_prep_wrapped_messages" ) as prep: client = FirewallClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1995,6 +2140,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = FirewallClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py index 9b18ecc96308..3d5d5a95f8a5 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_instances.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,27 +23,57 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.instances import InstancesAsyncClient from google.cloud.appengine_admin_v1.services.instances import InstancesClient from google.cloud.appengine_admin_v1.services.instances import pagers from google.cloud.appengine_admin_v1.services.instances import transports +from google.cloud.appengine_admin_v1.services.instances.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.instances.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import instance from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,]) def test_instances_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_instances_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,]) def test_instances_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_instances_client_get_transport_class(): def test_instances_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(InstancesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -436,7 +465,7 @@ def test_list_instances( transport: str = "grpc", request_type=appengine.ListInstancesRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -449,19 +478,15 @@ def test_list_instances( call.return_value = appengine.ListInstancesResponse( next_page_token="next_page_token_value", ) - response = client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" @@ -473,7 +498,7 @@ def test_list_instances_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -481,7 +506,6 @@ def test_list_instances_empty_call(): client.list_instances() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() @@ -490,7 +514,7 @@ async def test_list_instances_async( transport: str = "grpc_asyncio", request_type=appengine.ListInstancesRequest ): client = InstancesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -503,18 +527,15 @@ async def test_list_instances_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListInstancesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListInstancesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -524,17 +545,17 @@ async def test_list_instances_async_from_dict(): def test_list_instances_field_headers(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListInstancesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: call.return_value = appengine.ListInstancesResponse() - client.list_instances(request) # Establish that the underlying gRPC stub method was called. @@ -549,11 +570,12 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio async def test_list_instances_field_headers_async(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListInstancesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -561,7 +583,6 @@ async def test_list_instances_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListInstancesResponse() ) - await client.list_instances(request) # Establish that the underlying gRPC stub method was called. @@ -575,7 +596,7 @@ async def test_list_instances_field_headers_async(): def test_list_instances_pager(): - client = InstancesClient(credentials=credentials.AnonymousCredentials,) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: @@ -613,7 +634,7 @@ def test_list_instances_pager(): def test_list_instances_pages(): - client = InstancesClient(credentials=credentials.AnonymousCredentials,) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: @@ -643,7 +664,7 @@ def test_list_instances_pages(): @pytest.mark.asyncio async def test_list_instances_async_pager(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -680,7 +701,7 @@ async def test_list_instances_async_pager(): @pytest.mark.asyncio async def test_list_instances_async_pages(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -716,7 +737,7 @@ def test_get_instance( transport: str = "grpc", request_type=appengine.GetInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -744,49 +765,30 @@ def test_get_instance( vm_ip="vm_ip_value", vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, ) - response = client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.app_engine_release == "app_engine_release_value" - assert response.availability == instance.Instance.Availability.RESIDENT - assert response.vm_name == "vm_name_value" - assert response.vm_zone_name == "vm_zone_name_value" - assert response.vm_id == "vm_id_value" - assert response.requests == 892 - assert response.errors == 669 - assert math.isclose(response.qps, 0.340, rel_tol=1e-6) - assert response.average_latency == 1578 - assert response.memory_usage == 1293 - assert response.vm_status == "vm_status_value" - assert response.vm_debug_enabled is True - assert response.vm_ip == "vm_ip_value" - assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN @@ -798,7 +800,7 @@ def test_get_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -806,7 +808,6 @@ def test_get_instance_empty_call(): client.get_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() @@ -815,7 +816,7 @@ async def test_get_instance_async( transport: str = "grpc_asyncio", request_type=appengine.GetInstanceRequest ): client = InstancesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -845,48 +846,30 @@ async def test_get_instance_async( vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, ) ) - response = await client.get_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() # Establish that the response is the type that we expect. assert isinstance(response, instance.Instance) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.app_engine_release == "app_engine_release_value" - assert response.availability == instance.Instance.Availability.RESIDENT - assert response.vm_name == "vm_name_value" - assert response.vm_zone_name == "vm_zone_name_value" - assert response.vm_id == "vm_id_value" - assert response.requests == 892 - assert response.errors == 669 - assert math.isclose(response.qps, 0.340, rel_tol=1e-6) - assert response.average_latency == 1578 - assert response.memory_usage == 1293 - assert response.vm_status == "vm_status_value" - assert response.vm_debug_enabled is True - assert response.vm_ip == "vm_ip_value" - assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN @@ -896,17 +879,17 @@ async def test_get_instance_async_from_dict(): def test_get_instance_field_headers(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_instance), "__call__") as call: call.return_value = instance.Instance() - client.get_instance(request) # Establish that the underlying gRPC stub method was called. @@ -921,17 +904,17 @@ def test_get_instance_field_headers(): @pytest.mark.asyncio async def test_get_instance_field_headers_async(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_instance), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance()) - await client.get_instance(request) # Establish that the underlying gRPC stub method was called. @@ -948,7 +931,7 @@ def test_delete_instance( transport: str = "grpc", request_type=appengine.DeleteInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -959,13 +942,11 @@ def test_delete_instance( with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() # Establish that the response is the type that we expect. @@ -980,7 +961,7 @@ def test_delete_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -988,7 +969,6 @@ def test_delete_instance_empty_call(): client.delete_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() @@ -997,7 +977,7 @@ async def test_delete_instance_async( transport: str = "grpc_asyncio", request_type=appengine.DeleteInstanceRequest ): client = InstancesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1010,13 +990,11 @@ async def test_delete_instance_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() # Establish that the response is the type that we expect. @@ -1029,17 +1007,17 @@ async def test_delete_instance_async_from_dict(): def test_delete_instance_field_headers(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1054,11 +1032,12 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio async def test_delete_instance_field_headers_async(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1066,7 +1045,6 @@ async def test_delete_instance_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1083,7 +1061,7 @@ def test_debug_instance( transport: str = "grpc", request_type=appengine.DebugInstanceRequest ): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1094,13 +1072,11 @@ def test_debug_instance( with mock.patch.object(type(client.transport.debug_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.debug_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() # Establish that the response is the type that we expect. @@ -1115,7 +1091,7 @@ def test_debug_instance_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1123,7 +1099,6 @@ def test_debug_instance_empty_call(): client.debug_instance() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() @@ -1132,7 +1107,7 @@ async def test_debug_instance_async( transport: str = "grpc_asyncio", request_type=appengine.DebugInstanceRequest ): client = InstancesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1145,13 +1120,11 @@ async def test_debug_instance_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.debug_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() # Establish that the response is the type that we expect. @@ -1164,17 +1137,17 @@ async def test_debug_instance_async_from_dict(): def test_debug_instance_field_headers(): - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DebugInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.debug_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.debug_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1189,11 +1162,12 @@ def test_debug_instance_field_headers(): @pytest.mark.asyncio async def test_debug_instance_field_headers_async(): - client = InstancesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DebugInstanceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1201,7 +1175,6 @@ async def test_debug_instance_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.debug_instance(request) # Establish that the underlying gRPC stub method was called. @@ -1217,16 +1190,16 @@ async def test_debug_instance_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.InstancesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.InstancesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( @@ -1236,7 +1209,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.InstancesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = InstancesClient( @@ -1247,7 +1220,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.InstancesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = InstancesClient(transport=transport) assert client.transport is transport @@ -1256,13 +1229,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.InstancesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.InstancesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1274,23 +1247,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = InstancesClient(credentials=credentials.AnonymousCredentials(),) + client = InstancesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.InstancesGrpcTransport,) def test_instances_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.InstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1302,7 +1275,7 @@ def test_instances_base_transport(): ) as Transport: Transport.return_value = None transport = transports.InstancesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1323,15 +1296,41 @@ def test_instances_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_instances_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_instances_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstancesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1348,19 +1347,37 @@ def test_instances_base_transport_with_credentials_file(): def test_instances_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.InstancesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_instances_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstancesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_instances_auth_adc_old_google_auth(): + # 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) InstancesClient() adc.assert_called_once_with( scopes=( @@ -1372,14 +1389,39 @@ def test_instances_auth_adc(): ) -def test_instances_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_instances_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.InstancesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_instances_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1390,12 +1432,125 @@ def test_instances_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstancesGrpcTransport, grpc_helpers), + (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_instances_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstancesGrpcTransport, grpc_helpers), + (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_instances_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstancesGrpcTransport, grpc_helpers), + (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_instances_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport], ) def test_instances_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1438,7 +1593,7 @@ def test_instances_grpc_transport_client_cert_source_for_mtls(transport_class): def test_instances_host_no_port(): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1448,7 +1603,7 @@ def test_instances_host_no_port(): def test_instances_host_with_port(): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1499,9 +1654,9 @@ def test_instances_transport_channel_mtls_with_client_cert_source(transport_clas mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1582,7 +1737,7 @@ def test_instances_transport_channel_mtls_with_adc(transport_class): def test_instances_grpc_lro_client(): client = InstancesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1595,7 +1750,7 @@ def test_instances_grpc_lro_client(): def test_instances_grpc_lro_async_client(): client = InstancesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1611,7 +1766,6 @@ def test_instance_path(): service = "clam" version = "whelk" instance = "octopus" - expected = "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format( app=app, service=service, version=version, instance=instance, ) @@ -1635,7 +1789,6 @@ def test_parse_instance_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1656,7 +1809,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = InstancesClient.common_folder_path(folder) assert expected == actual @@ -1675,7 +1827,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = InstancesClient.common_organization_path(organization) assert expected == actual @@ -1694,7 +1845,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = InstancesClient.common_project_path(project) assert expected == actual @@ -1714,7 +1864,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1741,7 +1890,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.InstancesTransport, "_prep_wrapped_messages" ) as prep: client = InstancesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1750,6 +1899,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = InstancesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py index 69f3818661c6..88ad62148c24 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_services.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.services import ServicesAsyncClient from google.cloud.appengine_admin_v1.services.services import ServicesClient from google.cloud.appengine_admin_v1.services.services import pagers from google.cloud.appengine_admin_v1.services.services import transports +from google.cloud.appengine_admin_v1.services.services.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.services.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import network_settings from google.cloud.appengine_admin_v1.types import operation as ga_operation from google.cloud.appengine_admin_v1.types import service from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -89,7 +118,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,]) def test_services_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -104,7 +133,7 @@ def test_services_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,]) def test_services_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -149,7 +178,7 @@ def test_services_client_get_transport_class(): def test_services_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(ServicesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -425,7 +454,7 @@ def test_list_services( transport: str = "grpc", request_type=appengine.ListServicesRequest ): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -438,19 +467,15 @@ def test_list_services( call.return_value = appengine.ListServicesResponse( next_page_token="next_page_token_value", ) - response = client.list_services(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == "next_page_token_value" @@ -462,7 +487,7 @@ def test_list_services_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -470,7 +495,6 @@ def test_list_services_empty_call(): client.list_services() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() @@ -479,7 +503,7 @@ async def test_list_services_async( transport: str = "grpc_asyncio", request_type=appengine.ListServicesRequest ): client = ServicesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -492,18 +516,15 @@ async def test_list_services_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListServicesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_services(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -513,17 +534,17 @@ async def test_list_services_async_from_dict(): def test_list_services_field_headers(): - client = ServicesClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListServicesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_services), "__call__") as call: call.return_value = appengine.ListServicesResponse() - client.list_services(request) # Establish that the underlying gRPC stub method was called. @@ -538,11 +559,12 @@ def test_list_services_field_headers(): @pytest.mark.asyncio async def test_list_services_field_headers_async(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListServicesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -550,7 +572,6 @@ async def test_list_services_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListServicesResponse() ) - await client.list_services(request) # Establish that the underlying gRPC stub method was called. @@ -564,7 +585,7 @@ async def test_list_services_field_headers_async(): def test_list_services_pager(): - client = ServicesClient(credentials=credentials.AnonymousCredentials,) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_services), "__call__") as call: @@ -598,7 +619,7 @@ def test_list_services_pager(): def test_list_services_pages(): - client = ServicesClient(credentials=credentials.AnonymousCredentials,) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_services), "__call__") as call: @@ -624,7 +645,7 @@ def test_list_services_pages(): @pytest.mark.asyncio async def test_list_services_async_pager(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -657,7 +678,7 @@ async def test_list_services_async_pager(): @pytest.mark.asyncio async def test_list_services_async_pages(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -687,7 +708,7 @@ async def test_list_services_async_pages(): def test_get_service(transport: str = "grpc", request_type=appengine.GetServiceRequest): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -698,21 +719,16 @@ def test_get_service(transport: str = "grpc", request_type=appengine.GetServiceR with mock.patch.object(type(client.transport.get_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.Service(name="name_value", id="id_value",) - response = client.get_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == "name_value" - assert response.id == "id_value" @@ -724,7 +740,7 @@ def test_get_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -732,7 +748,6 @@ def test_get_service_empty_call(): client.get_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() @@ -741,7 +756,7 @@ async def test_get_service_async( transport: str = "grpc_asyncio", request_type=appengine.GetServiceRequest ): client = ServicesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -754,20 +769,16 @@ async def test_get_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.Service(name="name_value", id="id_value",) ) - response = await client.get_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Service) - assert response.name == "name_value" - assert response.id == "id_value" @@ -777,17 +788,17 @@ async def test_get_service_async_from_dict(): def test_get_service_field_headers(): - client = ServicesClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_service), "__call__") as call: call.return_value = service.Service() - client.get_service(request) # Establish that the underlying gRPC stub method was called. @@ -802,17 +813,17 @@ def test_get_service_field_headers(): @pytest.mark.asyncio async def test_get_service_field_headers_async(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_service), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - await client.get_service(request) # Establish that the underlying gRPC stub method was called. @@ -829,7 +840,7 @@ def test_update_service( transport: str = "grpc", request_type=appengine.UpdateServiceRequest ): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -840,13 +851,11 @@ def test_update_service( with mock.patch.object(type(client.transport.update_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() # Establish that the response is the type that we expect. @@ -861,7 +870,7 @@ def test_update_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -869,7 +878,6 @@ def test_update_service_empty_call(): client.update_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() @@ -878,7 +886,7 @@ async def test_update_service_async( transport: str = "grpc_asyncio", request_type=appengine.UpdateServiceRequest ): client = ServicesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -891,13 +899,11 @@ async def test_update_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() # Establish that the response is the type that we expect. @@ -910,17 +916,17 @@ async def test_update_service_async_from_dict(): def test_update_service_field_headers(): - client = ServicesClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_service), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_service(request) # Establish that the underlying gRPC stub method was called. @@ -935,11 +941,12 @@ def test_update_service_field_headers(): @pytest.mark.asyncio async def test_update_service_field_headers_async(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -947,7 +954,6 @@ async def test_update_service_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_service(request) # Establish that the underlying gRPC stub method was called. @@ -964,7 +970,7 @@ def test_delete_service( transport: str = "grpc", request_type=appengine.DeleteServiceRequest ): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -975,13 +981,11 @@ def test_delete_service( with mock.patch.object(type(client.transport.delete_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() # Establish that the response is the type that we expect. @@ -996,7 +1000,7 @@ def test_delete_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1004,7 +1008,6 @@ def test_delete_service_empty_call(): client.delete_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() @@ -1013,7 +1016,7 @@ async def test_delete_service_async( transport: str = "grpc_asyncio", request_type=appengine.DeleteServiceRequest ): client = ServicesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1026,13 +1029,11 @@ async def test_delete_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() # Establish that the response is the type that we expect. @@ -1045,17 +1046,17 @@ async def test_delete_service_async_from_dict(): def test_delete_service_field_headers(): - client = ServicesClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_service), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_service(request) # Establish that the underlying gRPC stub method was called. @@ -1070,11 +1071,12 @@ def test_delete_service_field_headers(): @pytest.mark.asyncio async def test_delete_service_field_headers_async(): - client = ServicesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteServiceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1082,7 +1084,6 @@ async def test_delete_service_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_service(request) # Establish that the underlying gRPC stub method was called. @@ -1098,16 +1099,16 @@ async def test_delete_service_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ServicesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ServicesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServicesClient( @@ -1117,7 +1118,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ServicesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServicesClient( @@ -1128,7 +1129,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ServicesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ServicesClient(transport=transport) assert client.transport is transport @@ -1137,13 +1138,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ServicesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ServicesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1155,23 +1156,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = ServicesClient(credentials=credentials.AnonymousCredentials(),) + client = ServicesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ServicesGrpcTransport,) def test_services_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1183,7 +1184,7 @@ def test_services_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ServicesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1204,15 +1205,41 @@ def test_services_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_services_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_services_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ServicesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1229,19 +1256,37 @@ def test_services_base_transport_with_credentials_file(): def test_services_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ServicesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_services_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ServicesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_services_auth_adc_old_google_auth(): + # 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) ServicesClient() adc.assert_called_once_with( scopes=( @@ -1253,14 +1298,39 @@ def test_services_auth_adc(): ) -def test_services_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_services_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ServicesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_services_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1271,12 +1341,125 @@ def test_services_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServicesGrpcTransport, grpc_helpers), + (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_services_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServicesGrpcTransport, grpc_helpers), + (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_services_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServicesGrpcTransport, grpc_helpers), + (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_services_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport], ) def test_services_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1319,7 +1502,7 @@ def test_services_grpc_transport_client_cert_source_for_mtls(transport_class): def test_services_host_no_port(): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1329,7 +1512,7 @@ def test_services_host_no_port(): def test_services_host_with_port(): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1380,9 +1563,9 @@ def test_services_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1463,7 +1646,7 @@ def test_services_transport_channel_mtls_with_adc(transport_class): def test_services_grpc_lro_client(): client = ServicesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1476,7 +1659,7 @@ def test_services_grpc_lro_client(): def test_services_grpc_lro_async_client(): client = ServicesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1489,7 +1672,6 @@ def test_services_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1510,7 +1692,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ServicesClient.common_folder_path(folder) assert expected == actual @@ -1529,7 +1710,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ServicesClient.common_organization_path(organization) assert expected == actual @@ -1548,7 +1728,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ServicesClient.common_project_path(project) assert expected == actual @@ -1568,7 +1747,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1595,7 +1773,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ServicesTransport, "_prep_wrapped_messages" ) as prep: client = ServicesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1604,6 +1782,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ServicesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py index ef68c8f006d4..6110074b9f34 100644 --- a/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py +++ b/packages/google-cloud-appengine-admin/tests/unit/gapic/appengine_admin_v1/test_versions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,27 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.appengine_admin_v1.services.versions import VersionsAsyncClient from google.cloud.appengine_admin_v1.services.versions import VersionsClient from google.cloud.appengine_admin_v1.services.versions import pagers from google.cloud.appengine_admin_v1.services.versions import transports +from google.cloud.appengine_admin_v1.services.versions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.appengine_admin_v1.services.versions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.appengine_admin_v1.types import app_yaml from google.cloud.appengine_admin_v1.types import appengine from google.cloud.appengine_admin_v1.types import deploy @@ -46,9 +51,33 @@ from google.cloud.appengine_admin_v1.types import version from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_versions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -152,7 +181,7 @@ def test_versions_client_get_transport_class(): def test_versions_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(VersionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -428,7 +457,7 @@ def test_list_versions( transport: str = "grpc", request_type=appengine.ListVersionsRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -441,19 +470,15 @@ def test_list_versions( call.return_value = appengine.ListVersionsResponse( next_page_token="next_page_token_value", ) - response = client.list_versions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == "next_page_token_value" @@ -465,7 +490,7 @@ def test_list_versions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -473,7 +498,6 @@ def test_list_versions_empty_call(): client.list_versions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() @@ -482,7 +506,7 @@ async def test_list_versions_async( transport: str = "grpc_asyncio", request_type=appengine.ListVersionsRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -495,18 +519,15 @@ async def test_list_versions_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListVersionsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_versions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -516,17 +537,17 @@ async def test_list_versions_async_from_dict(): def test_list_versions_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_versions), "__call__") as call: call.return_value = appengine.ListVersionsResponse() - client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -541,11 +562,12 @@ def test_list_versions_field_headers(): @pytest.mark.asyncio async def test_list_versions_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -553,7 +575,6 @@ async def test_list_versions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( appengine.ListVersionsResponse() ) - await client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -567,7 +588,7 @@ async def test_list_versions_field_headers_async(): def test_list_versions_pager(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_versions), "__call__") as call: @@ -601,7 +622,7 @@ def test_list_versions_pager(): def test_list_versions_pages(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_versions), "__call__") as call: @@ -627,7 +648,7 @@ def test_list_versions_pages(): @pytest.mark.asyncio async def test_list_versions_async_pager(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -660,7 +681,7 @@ async def test_list_versions_async_pager(): @pytest.mark.asyncio async def test_list_versions_async_pages(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -690,7 +711,7 @@ async def test_list_versions_async_pages(): def test_get_version(transport: str = "grpc", request_type=appengine.GetVersionRequest): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -720,58 +741,37 @@ def test_get_version(transport: str = "grpc", request_type=appengine.GetVersionR nobuild_files_regex="nobuild_files_regex_value", version_url="version_url_value", automatic_scaling=version.AutomaticScaling( - cool_down_period=duration.Duration(seconds=751) + cool_down_period=duration_pb2.Duration(seconds=751) ), ) - response = client.get_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.inbound_services == [ version.InboundServiceType.INBOUND_SERVICE_MAIL ] - assert response.instance_class == "instance_class_value" - assert response.zones == ["zones_value"] - assert response.runtime == "runtime_value" - assert response.runtime_channel == "runtime_channel_value" - assert response.threadsafe is True - assert response.vm is True - assert response.env == "env_value" - assert response.serving_status == version.ServingStatus.SERVING - assert response.created_by == "created_by_value" - assert response.disk_usage_bytes == 1701 - assert response.runtime_api_version == "runtime_api_version_value" - assert response.runtime_main_executable_path == "runtime_main_executable_path_value" - assert response.service_account == "service_account_value" - assert response.nobuild_files_regex == "nobuild_files_regex_value" - assert response.version_url == "version_url_value" @@ -783,7 +783,7 @@ def test_get_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -791,7 +791,6 @@ def test_get_version_empty_call(): client.get_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() @@ -800,7 +799,7 @@ async def test_get_version_async( transport: str = "grpc_asyncio", request_type=appengine.GetVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -832,54 +831,34 @@ async def test_get_version_async( version_url="version_url_value", ) ) - response = await client.get_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.id == "id_value" - assert response.inbound_services == [ version.InboundServiceType.INBOUND_SERVICE_MAIL ] - assert response.instance_class == "instance_class_value" - assert response.zones == ["zones_value"] - assert response.runtime == "runtime_value" - assert response.runtime_channel == "runtime_channel_value" - assert response.threadsafe is True - assert response.vm is True - assert response.env == "env_value" - assert response.serving_status == version.ServingStatus.SERVING - assert response.created_by == "created_by_value" - assert response.disk_usage_bytes == 1701 - assert response.runtime_api_version == "runtime_api_version_value" - assert response.runtime_main_executable_path == "runtime_main_executable_path_value" - assert response.service_account == "service_account_value" - assert response.nobuild_files_regex == "nobuild_files_regex_value" - assert response.version_url == "version_url_value" @@ -889,17 +868,17 @@ async def test_get_version_async_from_dict(): def test_get_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = version.Version() - client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -914,17 +893,17 @@ def test_get_version_field_headers(): @pytest.mark.asyncio async def test_get_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) - await client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -941,7 +920,7 @@ def test_create_version( transport: str = "grpc", request_type=appengine.CreateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -952,13 +931,11 @@ def test_create_version( with mock.patch.object(type(client.transport.create_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -973,7 +950,7 @@ def test_create_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -981,7 +958,6 @@ def test_create_version_empty_call(): client.create_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() @@ -990,7 +966,7 @@ async def test_create_version_async( transport: str = "grpc_asyncio", request_type=appengine.CreateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1003,13 +979,11 @@ async def test_create_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -1022,17 +996,17 @@ async def test_create_version_async_from_dict(): def test_create_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1047,11 +1021,12 @@ def test_create_version_field_headers(): @pytest.mark.asyncio async def test_create_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1059,7 +1034,6 @@ async def test_create_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1076,7 +1050,7 @@ def test_update_version( transport: str = "grpc", request_type=appengine.UpdateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1087,13 +1061,11 @@ def test_update_version( with mock.patch.object(type(client.transport.update_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() # Establish that the response is the type that we expect. @@ -1108,7 +1080,7 @@ def test_update_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1116,7 +1088,6 @@ def test_update_version_empty_call(): client.update_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() @@ -1125,7 +1096,7 @@ async def test_update_version_async( transport: str = "grpc_asyncio", request_type=appengine.UpdateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1138,13 +1109,11 @@ async def test_update_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() # Establish that the response is the type that we expect. @@ -1157,17 +1126,17 @@ async def test_update_version_async_from_dict(): def test_update_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1182,11 +1151,12 @@ def test_update_version_field_headers(): @pytest.mark.asyncio async def test_update_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.UpdateVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1194,7 +1164,6 @@ async def test_update_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1211,7 +1180,7 @@ def test_delete_version( transport: str = "grpc", request_type=appengine.DeleteVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,13 +1191,11 @@ def test_delete_version( with mock.patch.object(type(client.transport.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1243,7 +1210,7 @@ def test_delete_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1251,7 +1218,6 @@ def test_delete_version_empty_call(): client.delete_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() @@ -1260,7 +1226,7 @@ async def test_delete_version_async( transport: str = "grpc_asyncio", request_type=appengine.DeleteVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1273,13 +1239,11 @@ async def test_delete_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1292,17 +1256,17 @@ async def test_delete_version_async_from_dict(): def test_delete_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1317,11 +1281,12 @@ def test_delete_version_field_headers(): @pytest.mark.asyncio async def test_delete_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = appengine.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1329,7 +1294,6 @@ async def test_delete_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1345,16 +1309,16 @@ async def test_delete_version_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1364,7 +1328,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1375,7 +1339,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = VersionsClient(transport=transport) assert client.transport is transport @@ -1384,13 +1348,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.VersionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1402,23 +1366,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.VersionsGrpcTransport,) def test_versions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1430,7 +1394,7 @@ def test_versions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1452,15 +1416,41 @@ def test_versions_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_versions_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + 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/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # 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.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VersionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1477,19 +1467,37 @@ def test_versions_base_transport_with_credentials_file(): def test_versions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VersionsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_versions_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_auth_adc_old_google_auth(): + # 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) VersionsClient() adc.assert_called_once_with( scopes=( @@ -1501,14 +1509,39 @@ def test_versions_auth_adc(): ) -def test_versions_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.VersionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_versions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/appengine.admin", @@ -1519,12 +1552,125 @@ def test_versions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_versions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/appengine.admin", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], ) def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1567,7 +1713,7 @@ def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_versions_host_no_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com" ), @@ -1577,7 +1723,7 @@ def test_versions_host_no_port(): def test_versions_host_with_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="appengine.googleapis.com:8000" ), @@ -1628,9 +1774,9 @@ def test_versions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1711,7 +1857,7 @@ def test_versions_transport_channel_mtls_with_adc(transport_class): def test_versions_grpc_lro_client(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1724,7 +1870,7 @@ def test_versions_grpc_lro_client(): def test_versions_grpc_lro_async_client(): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1737,7 +1883,6 @@ def test_versions_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1758,7 +1903,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = VersionsClient.common_folder_path(folder) assert expected == actual @@ -1777,7 +1921,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = VersionsClient.common_organization_path(organization) assert expected == actual @@ -1796,7 +1939,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = VersionsClient.common_project_path(project) assert expected == actual @@ -1816,7 +1958,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1843,7 +1984,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.VersionsTransport, "_prep_wrapped_messages" ) as prep: client = VersionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1852,6 +1993,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = VersionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)