diff --git a/docs/monitoring_v3/alert_policy_service.rst b/docs/monitoring_v3/alert_policy_service.rst index 1a413ef2..a11da806 100644 --- a/docs/monitoring_v3/alert_policy_service.rst +++ b/docs/monitoring_v3/alert_policy_service.rst @@ -5,7 +5,6 @@ AlertPolicyService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.alert_policy_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/group_service.rst b/docs/monitoring_v3/group_service.rst index c191656e..74703e5e 100644 --- a/docs/monitoring_v3/group_service.rst +++ b/docs/monitoring_v3/group_service.rst @@ -5,7 +5,6 @@ GroupService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.group_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/metric_service.rst b/docs/monitoring_v3/metric_service.rst index 15e120c3..74a1d3cf 100644 --- a/docs/monitoring_v3/metric_service.rst +++ b/docs/monitoring_v3/metric_service.rst @@ -5,7 +5,6 @@ MetricService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.metric_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/notification_channel_service.rst b/docs/monitoring_v3/notification_channel_service.rst index cdcaaf1f..85e28278 100644 --- a/docs/monitoring_v3/notification_channel_service.rst +++ b/docs/monitoring_v3/notification_channel_service.rst @@ -5,7 +5,6 @@ NotificationChannelService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.notification_channel_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/query_service.rst b/docs/monitoring_v3/query_service.rst index d600d503..b144dc56 100644 --- a/docs/monitoring_v3/query_service.rst +++ b/docs/monitoring_v3/query_service.rst @@ -5,7 +5,6 @@ QueryService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.query_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/service_monitoring_service.rst b/docs/monitoring_v3/service_monitoring_service.rst index b3781db9..f7c35fa6 100644 --- a/docs/monitoring_v3/service_monitoring_service.rst +++ b/docs/monitoring_v3/service_monitoring_service.rst @@ -5,7 +5,6 @@ ServiceMonitoringService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.service_monitoring_service.pagers :members: :inherited-members: diff --git a/docs/monitoring_v3/uptime_check_service.rst b/docs/monitoring_v3/uptime_check_service.rst index a433d1b2..7149a771 100644 --- a/docs/monitoring_v3/uptime_check_service.rst +++ b/docs/monitoring_v3/uptime_check_service.rst @@ -5,7 +5,6 @@ UptimeCheckService :members: :inherited-members: - .. automodule:: google.cloud.monitoring_v3.services.uptime_check_service.pagers :members: :inherited-members: diff --git a/google/cloud/monitoring/__init__.py b/google/cloud/monitoring/__init__.py index 1d6a7622..60f07f2d 100644 --- a/google/cloud/monitoring/__init__.py +++ b/google/cloud/monitoring/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,44 +14,45 @@ # limitations under the License. # -from google.cloud.monitoring_v3.services.alert_policy_service.async_client import ( - AlertPolicyServiceAsyncClient, -) from google.cloud.monitoring_v3.services.alert_policy_service.client import ( AlertPolicyServiceClient, ) -from google.cloud.monitoring_v3.services.group_service.async_client import ( - GroupServiceAsyncClient, +from google.cloud.monitoring_v3.services.alert_policy_service.async_client import ( + AlertPolicyServiceAsyncClient, ) from google.cloud.monitoring_v3.services.group_service.client import GroupServiceClient -from google.cloud.monitoring_v3.services.metric_service.async_client import ( - MetricServiceAsyncClient, +from google.cloud.monitoring_v3.services.group_service.async_client import ( + GroupServiceAsyncClient, ) from google.cloud.monitoring_v3.services.metric_service.client import ( MetricServiceClient, ) -from google.cloud.monitoring_v3.services.notification_channel_service.async_client import ( - NotificationChannelServiceAsyncClient, +from google.cloud.monitoring_v3.services.metric_service.async_client import ( + MetricServiceAsyncClient, ) from google.cloud.monitoring_v3.services.notification_channel_service.client import ( NotificationChannelServiceClient, ) -from google.cloud.monitoring_v3.services.query_service.async_client import ( - QueryServiceAsyncClient, +from google.cloud.monitoring_v3.services.notification_channel_service.async_client import ( + NotificationChannelServiceAsyncClient, ) from google.cloud.monitoring_v3.services.query_service.client import QueryServiceClient -from google.cloud.monitoring_v3.services.service_monitoring_service.async_client import ( - ServiceMonitoringServiceAsyncClient, +from google.cloud.monitoring_v3.services.query_service.async_client import ( + QueryServiceAsyncClient, ) from google.cloud.monitoring_v3.services.service_monitoring_service.client import ( ServiceMonitoringServiceClient, ) -from google.cloud.monitoring_v3.services.uptime_check_service.async_client import ( - UptimeCheckServiceAsyncClient, +from google.cloud.monitoring_v3.services.service_monitoring_service.async_client import ( + ServiceMonitoringServiceAsyncClient, ) from google.cloud.monitoring_v3.services.uptime_check_service.client import ( UptimeCheckServiceClient, ) +from google.cloud.monitoring_v3.services.uptime_check_service.async_client import ( + UptimeCheckServiceAsyncClient, +) + from google.cloud.monitoring_v3.types.alert import AlertPolicy from google.cloud.monitoring_v3.types.alert_service import CreateAlertPolicyRequest from google.cloud.monitoring_v3.types.alert_service import DeleteAlertPolicyRequest @@ -61,10 +61,10 @@ from google.cloud.monitoring_v3.types.alert_service import ListAlertPoliciesResponse from google.cloud.monitoring_v3.types.alert_service import UpdateAlertPolicyRequest from google.cloud.monitoring_v3.types.common import Aggregation -from google.cloud.monitoring_v3.types.common import ComparisonType -from google.cloud.monitoring_v3.types.common import ServiceTier from google.cloud.monitoring_v3.types.common import TimeInterval from google.cloud.monitoring_v3.types.common import TypedValue +from google.cloud.monitoring_v3.types.common import ComparisonType +from google.cloud.monitoring_v3.types.common import ServiceTier from google.cloud.monitoring_v3.types.dropped_labels import DroppedLabels from google.cloud.monitoring_v3.types.group import Group from google.cloud.monitoring_v3.types.group_service import CreateGroupRequest @@ -186,10 +186,10 @@ ) from google.cloud.monitoring_v3.types.service_service import UpdateServiceRequest from google.cloud.monitoring_v3.types.span_context import SpanContext -from google.cloud.monitoring_v3.types.uptime import GroupResourceType from google.cloud.monitoring_v3.types.uptime import InternalChecker from google.cloud.monitoring_v3.types.uptime import UptimeCheckConfig from google.cloud.monitoring_v3.types.uptime import UptimeCheckIp +from google.cloud.monitoring_v3.types.uptime import GroupResourceType from google.cloud.monitoring_v3.types.uptime import UptimeCheckRegion from google.cloud.monitoring_v3.types.uptime_service import ( CreateUptimeCheckConfigRequest, @@ -211,114 +211,114 @@ ) __all__ = ( - "Aggregation", - "AlertPolicy", - "AlertPolicyServiceAsyncClient", "AlertPolicyServiceClient", - "BasicSli", - "ComparisonType", + "AlertPolicyServiceAsyncClient", + "GroupServiceClient", + "GroupServiceAsyncClient", + "MetricServiceClient", + "MetricServiceAsyncClient", + "NotificationChannelServiceClient", + "NotificationChannelServiceAsyncClient", + "QueryServiceClient", + "QueryServiceAsyncClient", + "ServiceMonitoringServiceClient", + "ServiceMonitoringServiceAsyncClient", + "UptimeCheckServiceClient", + "UptimeCheckServiceAsyncClient", + "AlertPolicy", "CreateAlertPolicyRequest", - "CreateGroupRequest", - "CreateMetricDescriptorRequest", - "CreateNotificationChannelRequest", - "CreateServiceLevelObjectiveRequest", - "CreateServiceRequest", - "CreateTimeSeriesError", - "CreateTimeSeriesRequest", - "CreateTimeSeriesSummary", - "CreateUptimeCheckConfigRequest", "DeleteAlertPolicyRequest", - "DeleteGroupRequest", - "DeleteMetricDescriptorRequest", - "DeleteNotificationChannelRequest", - "DeleteServiceLevelObjectiveRequest", - "DeleteServiceRequest", - "DeleteUptimeCheckConfigRequest", - "DistributionCut", - "DroppedLabels", "GetAlertPolicyRequest", - "GetGroupRequest", - "GetMetricDescriptorRequest", - "GetMonitoredResourceDescriptorRequest", - "GetNotificationChannelDescriptorRequest", - "GetNotificationChannelRequest", - "GetNotificationChannelVerificationCodeRequest", - "GetNotificationChannelVerificationCodeResponse", - "GetServiceLevelObjectiveRequest", - "GetServiceRequest", - "GetUptimeCheckConfigRequest", - "Group", - "GroupResourceType", - "GroupServiceAsyncClient", - "GroupServiceClient", - "InternalChecker", - "LabelValue", "ListAlertPoliciesRequest", "ListAlertPoliciesResponse", + "UpdateAlertPolicyRequest", + "Aggregation", + "TimeInterval", + "TypedValue", + "ComparisonType", + "ServiceTier", + "DroppedLabels", + "Group", + "CreateGroupRequest", + "DeleteGroupRequest", + "GetGroupRequest", "ListGroupMembersRequest", "ListGroupMembersResponse", "ListGroupsRequest", "ListGroupsResponse", + "UpdateGroupRequest", + "LabelValue", + "Point", + "QueryError", + "TextLocator", + "TimeSeries", + "TimeSeriesData", + "TimeSeriesDescriptor", + "CreateMetricDescriptorRequest", + "CreateTimeSeriesError", + "CreateTimeSeriesRequest", + "CreateTimeSeriesSummary", + "DeleteMetricDescriptorRequest", + "GetMetricDescriptorRequest", + "GetMonitoredResourceDescriptorRequest", "ListMetricDescriptorsRequest", "ListMetricDescriptorsResponse", "ListMonitoredResourceDescriptorsRequest", "ListMonitoredResourceDescriptorsResponse", - "ListNotificationChannelDescriptorsRequest", - "ListNotificationChannelDescriptorsResponse", - "ListNotificationChannelsRequest", - "ListNotificationChannelsResponse", - "ListServiceLevelObjectivesRequest", - "ListServiceLevelObjectivesResponse", - "ListServicesRequest", - "ListServicesResponse", "ListTimeSeriesRequest", "ListTimeSeriesResponse", - "ListUptimeCheckConfigsRequest", - "ListUptimeCheckConfigsResponse", - "ListUptimeCheckIpsRequest", - "ListUptimeCheckIpsResponse", - "MetricServiceAsyncClient", - "MetricServiceClient", - "MutationRecord", - "NotificationChannel", - "NotificationChannelDescriptor", - "NotificationChannelServiceAsyncClient", - "NotificationChannelServiceClient", - "Point", - "QueryError", "QueryErrorList", - "QueryServiceAsyncClient", - "QueryServiceClient", "QueryTimeSeriesRequest", "QueryTimeSeriesResponse", + "MutationRecord", + "NotificationChannel", + "NotificationChannelDescriptor", + "CreateNotificationChannelRequest", + "DeleteNotificationChannelRequest", + "GetNotificationChannelDescriptorRequest", + "GetNotificationChannelRequest", + "GetNotificationChannelVerificationCodeRequest", + "GetNotificationChannelVerificationCodeResponse", + "ListNotificationChannelDescriptorsRequest", + "ListNotificationChannelDescriptorsResponse", + "ListNotificationChannelsRequest", + "ListNotificationChannelsResponse", + "SendNotificationChannelVerificationCodeRequest", + "UpdateNotificationChannelRequest", + "VerifyNotificationChannelRequest", + "BasicSli", + "DistributionCut", "Range", "RequestBasedSli", - "SendNotificationChannelVerificationCodeRequest", "Service", "ServiceLevelIndicator", "ServiceLevelObjective", - "ServiceMonitoringServiceAsyncClient", - "ServiceMonitoringServiceClient", - "ServiceTier", - "SpanContext", - "TextLocator", - "TimeInterval", - "TimeSeries", - "TimeSeriesData", - "TimeSeriesDescriptor", "TimeSeriesRatio", - "TypedValue", - "UpdateAlertPolicyRequest", - "UpdateGroupRequest", - "UpdateNotificationChannelRequest", + "WindowsBasedSli", + "CreateServiceLevelObjectiveRequest", + "CreateServiceRequest", + "DeleteServiceLevelObjectiveRequest", + "DeleteServiceRequest", + "GetServiceLevelObjectiveRequest", + "GetServiceRequest", + "ListServiceLevelObjectivesRequest", + "ListServiceLevelObjectivesResponse", + "ListServicesRequest", + "ListServicesResponse", "UpdateServiceLevelObjectiveRequest", "UpdateServiceRequest", - "UpdateUptimeCheckConfigRequest", + "SpanContext", + "InternalChecker", "UptimeCheckConfig", "UptimeCheckIp", + "GroupResourceType", "UptimeCheckRegion", - "UptimeCheckServiceAsyncClient", - "UptimeCheckServiceClient", - "VerifyNotificationChannelRequest", - "WindowsBasedSli", + "CreateUptimeCheckConfigRequest", + "DeleteUptimeCheckConfigRequest", + "GetUptimeCheckConfigRequest", + "ListUptimeCheckConfigsRequest", + "ListUptimeCheckConfigsResponse", + "ListUptimeCheckIpsRequest", + "ListUptimeCheckIpsResponse", + "UpdateUptimeCheckConfigRequest", ) diff --git a/google/cloud/monitoring_v3/__init__.py b/google/cloud/monitoring_v3/__init__.py index 8c1103a5..77f1d7b9 100644 --- a/google/cloud/monitoring_v3/__init__.py +++ b/google/cloud/monitoring_v3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,12 +15,20 @@ # from .services.alert_policy_service import AlertPolicyServiceClient +from .services.alert_policy_service import AlertPolicyServiceAsyncClient from .services.group_service import GroupServiceClient +from .services.group_service import GroupServiceAsyncClient from .services.metric_service import MetricServiceClient +from .services.metric_service import MetricServiceAsyncClient from .services.notification_channel_service import NotificationChannelServiceClient +from .services.notification_channel_service import NotificationChannelServiceAsyncClient from .services.query_service import QueryServiceClient +from .services.query_service import QueryServiceAsyncClient from .services.service_monitoring_service import ServiceMonitoringServiceClient +from .services.service_monitoring_service import ServiceMonitoringServiceAsyncClient from .services.uptime_check_service import UptimeCheckServiceClient +from .services.uptime_check_service import UptimeCheckServiceAsyncClient + from .types.alert import AlertPolicy from .types.alert_service import CreateAlertPolicyRequest from .types.alert_service import DeleteAlertPolicyRequest @@ -30,10 +37,10 @@ from .types.alert_service import ListAlertPoliciesResponse from .types.alert_service import UpdateAlertPolicyRequest from .types.common import Aggregation -from .types.common import ComparisonType -from .types.common import ServiceTier from .types.common import TimeInterval from .types.common import TypedValue +from .types.common import ComparisonType +from .types.common import ServiceTier from .types.dropped_labels import DroppedLabels from .types.group import Group from .types.group_service import CreateGroupRequest @@ -105,10 +112,10 @@ from .types.service_service import UpdateServiceLevelObjectiveRequest from .types.service_service import UpdateServiceRequest from .types.span_context import SpanContext -from .types.uptime import GroupResourceType from .types.uptime import InternalChecker from .types.uptime import UptimeCheckConfig from .types.uptime import UptimeCheckIp +from .types.uptime import GroupResourceType from .types.uptime import UptimeCheckRegion from .types.uptime_service import CreateUptimeCheckConfigRequest from .types.uptime_service import DeleteUptimeCheckConfigRequest @@ -119,8 +126,14 @@ from .types.uptime_service import ListUptimeCheckIpsResponse from .types.uptime_service import UpdateUptimeCheckConfigRequest - __all__ = ( + "AlertPolicyServiceAsyncClient", + "GroupServiceAsyncClient", + "MetricServiceAsyncClient", + "NotificationChannelServiceAsyncClient", + "QueryServiceAsyncClient", + "ServiceMonitoringServiceAsyncClient", + "UptimeCheckServiceAsyncClient", "Aggregation", "AlertPolicy", "AlertPolicyServiceClient", @@ -221,7 +234,7 @@ "UptimeCheckConfig", "UptimeCheckIp", "UptimeCheckRegion", + "UptimeCheckServiceClient", "VerifyNotificationChannelRequest", "WindowsBasedSli", - "UptimeCheckServiceClient", ) diff --git a/google/cloud/monitoring_v3/gapic_metadata.json b/google/cloud/monitoring_v3/gapic_metadata.json new file mode 100644 index 00000000..0b3e214a --- /dev/null +++ b/google/cloud/monitoring_v3/gapic_metadata.json @@ -0,0 +1,567 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.monitoring_v3", + "protoPackage": "google.monitoring.v3", + "schema": "1.0", + "services": { + "AlertPolicyService": { + "clients": { + "grpc": { + "libraryClient": "AlertPolicyServiceClient", + "rpcs": { + "CreateAlertPolicy": { + "methods": [ + "create_alert_policy" + ] + }, + "DeleteAlertPolicy": { + "methods": [ + "delete_alert_policy" + ] + }, + "GetAlertPolicy": { + "methods": [ + "get_alert_policy" + ] + }, + "ListAlertPolicies": { + "methods": [ + "list_alert_policies" + ] + }, + "UpdateAlertPolicy": { + "methods": [ + "update_alert_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AlertPolicyServiceAsyncClient", + "rpcs": { + "CreateAlertPolicy": { + "methods": [ + "create_alert_policy" + ] + }, + "DeleteAlertPolicy": { + "methods": [ + "delete_alert_policy" + ] + }, + "GetAlertPolicy": { + "methods": [ + "get_alert_policy" + ] + }, + "ListAlertPolicies": { + "methods": [ + "list_alert_policies" + ] + }, + "UpdateAlertPolicy": { + "methods": [ + "update_alert_policy" + ] + } + } + } + } + }, + "GroupService": { + "clients": { + "grpc": { + "libraryClient": "GroupServiceClient", + "rpcs": { + "CreateGroup": { + "methods": [ + "create_group" + ] + }, + "DeleteGroup": { + "methods": [ + "delete_group" + ] + }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, + "ListGroupMembers": { + "methods": [ + "list_group_members" + ] + }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "UpdateGroup": { + "methods": [ + "update_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GroupServiceAsyncClient", + "rpcs": { + "CreateGroup": { + "methods": [ + "create_group" + ] + }, + "DeleteGroup": { + "methods": [ + "delete_group" + ] + }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, + "ListGroupMembers": { + "methods": [ + "list_group_members" + ] + }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "UpdateGroup": { + "methods": [ + "update_group" + ] + } + } + } + } + }, + "MetricService": { + "clients": { + "grpc": { + "libraryClient": "MetricServiceClient", + "rpcs": { + "CreateMetricDescriptor": { + "methods": [ + "create_metric_descriptor" + ] + }, + "CreateTimeSeries": { + "methods": [ + "create_time_series" + ] + }, + "DeleteMetricDescriptor": { + "methods": [ + "delete_metric_descriptor" + ] + }, + "GetMetricDescriptor": { + "methods": [ + "get_metric_descriptor" + ] + }, + "GetMonitoredResourceDescriptor": { + "methods": [ + "get_monitored_resource_descriptor" + ] + }, + "ListMetricDescriptors": { + "methods": [ + "list_metric_descriptors" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "ListTimeSeries": { + "methods": [ + "list_time_series" + ] + } + } + }, + "grpc-async": { + "libraryClient": "MetricServiceAsyncClient", + "rpcs": { + "CreateMetricDescriptor": { + "methods": [ + "create_metric_descriptor" + ] + }, + "CreateTimeSeries": { + "methods": [ + "create_time_series" + ] + }, + "DeleteMetricDescriptor": { + "methods": [ + "delete_metric_descriptor" + ] + }, + "GetMetricDescriptor": { + "methods": [ + "get_metric_descriptor" + ] + }, + "GetMonitoredResourceDescriptor": { + "methods": [ + "get_monitored_resource_descriptor" + ] + }, + "ListMetricDescriptors": { + "methods": [ + "list_metric_descriptors" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "list_monitored_resource_descriptors" + ] + }, + "ListTimeSeries": { + "methods": [ + "list_time_series" + ] + } + } + } + } + }, + "NotificationChannelService": { + "clients": { + "grpc": { + "libraryClient": "NotificationChannelServiceClient", + "rpcs": { + "CreateNotificationChannel": { + "methods": [ + "create_notification_channel" + ] + }, + "DeleteNotificationChannel": { + "methods": [ + "delete_notification_channel" + ] + }, + "GetNotificationChannel": { + "methods": [ + "get_notification_channel" + ] + }, + "GetNotificationChannelDescriptor": { + "methods": [ + "get_notification_channel_descriptor" + ] + }, + "GetNotificationChannelVerificationCode": { + "methods": [ + "get_notification_channel_verification_code" + ] + }, + "ListNotificationChannelDescriptors": { + "methods": [ + "list_notification_channel_descriptors" + ] + }, + "ListNotificationChannels": { + "methods": [ + "list_notification_channels" + ] + }, + "SendNotificationChannelVerificationCode": { + "methods": [ + "send_notification_channel_verification_code" + ] + }, + "UpdateNotificationChannel": { + "methods": [ + "update_notification_channel" + ] + }, + "VerifyNotificationChannel": { + "methods": [ + "verify_notification_channel" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NotificationChannelServiceAsyncClient", + "rpcs": { + "CreateNotificationChannel": { + "methods": [ + "create_notification_channel" + ] + }, + "DeleteNotificationChannel": { + "methods": [ + "delete_notification_channel" + ] + }, + "GetNotificationChannel": { + "methods": [ + "get_notification_channel" + ] + }, + "GetNotificationChannelDescriptor": { + "methods": [ + "get_notification_channel_descriptor" + ] + }, + "GetNotificationChannelVerificationCode": { + "methods": [ + "get_notification_channel_verification_code" + ] + }, + "ListNotificationChannelDescriptors": { + "methods": [ + "list_notification_channel_descriptors" + ] + }, + "ListNotificationChannels": { + "methods": [ + "list_notification_channels" + ] + }, + "SendNotificationChannelVerificationCode": { + "methods": [ + "send_notification_channel_verification_code" + ] + }, + "UpdateNotificationChannel": { + "methods": [ + "update_notification_channel" + ] + }, + "VerifyNotificationChannel": { + "methods": [ + "verify_notification_channel" + ] + } + } + } + } + }, + "QueryService": { + "clients": { + "grpc": { + "libraryClient": "QueryServiceClient", + "rpcs": { + "QueryTimeSeries": { + "methods": [ + "query_time_series" + ] + } + } + }, + "grpc-async": { + "libraryClient": "QueryServiceAsyncClient", + "rpcs": { + "QueryTimeSeries": { + "methods": [ + "query_time_series" + ] + } + } + } + } + }, + "ServiceMonitoringService": { + "clients": { + "grpc": { + "libraryClient": "ServiceMonitoringServiceClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "CreateServiceLevelObjective": { + "methods": [ + "create_service_level_objective" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "DeleteServiceLevelObjective": { + "methods": [ + "delete_service_level_objective" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "GetServiceLevelObjective": { + "methods": [ + "get_service_level_objective" + ] + }, + "ListServiceLevelObjectives": { + "methods": [ + "list_service_level_objectives" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + }, + "UpdateServiceLevelObjective": { + "methods": [ + "update_service_level_objective" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServiceMonitoringServiceAsyncClient", + "rpcs": { + "CreateService": { + "methods": [ + "create_service" + ] + }, + "CreateServiceLevelObjective": { + "methods": [ + "create_service_level_objective" + ] + }, + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "DeleteServiceLevelObjective": { + "methods": [ + "delete_service_level_objective" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "GetServiceLevelObjective": { + "methods": [ + "get_service_level_objective" + ] + }, + "ListServiceLevelObjectives": { + "methods": [ + "list_service_level_objectives" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + }, + "UpdateServiceLevelObjective": { + "methods": [ + "update_service_level_objective" + ] + } + } + } + } + }, + "UptimeCheckService": { + "clients": { + "grpc": { + "libraryClient": "UptimeCheckServiceClient", + "rpcs": { + "CreateUptimeCheckConfig": { + "methods": [ + "create_uptime_check_config" + ] + }, + "DeleteUptimeCheckConfig": { + "methods": [ + "delete_uptime_check_config" + ] + }, + "GetUptimeCheckConfig": { + "methods": [ + "get_uptime_check_config" + ] + }, + "ListUptimeCheckConfigs": { + "methods": [ + "list_uptime_check_configs" + ] + }, + "ListUptimeCheckIps": { + "methods": [ + "list_uptime_check_ips" + ] + }, + "UpdateUptimeCheckConfig": { + "methods": [ + "update_uptime_check_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UptimeCheckServiceAsyncClient", + "rpcs": { + "CreateUptimeCheckConfig": { + "methods": [ + "create_uptime_check_config" + ] + }, + "DeleteUptimeCheckConfig": { + "methods": [ + "delete_uptime_check_config" + ] + }, + "GetUptimeCheckConfig": { + "methods": [ + "get_uptime_check_config" + ] + }, + "ListUptimeCheckConfigs": { + "methods": [ + "list_uptime_check_configs" + ] + }, + "ListUptimeCheckIps": { + "methods": [ + "list_uptime_check_ips" + ] + }, + "UpdateUptimeCheckConfig": { + "methods": [ + "update_uptime_check_config" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/monitoring_v3/services/__init__.py b/google/cloud/monitoring_v3/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/monitoring_v3/services/__init__.py +++ b/google/cloud/monitoring_v3/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/google/cloud/monitoring_v3/services/alert_policy_service/__init__.py b/google/cloud/monitoring_v3/services/alert_policy_service/__init__.py index b5aed67b..0f831e51 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/__init__.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/__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 AlertPolicyServiceClient from .async_client import AlertPolicyServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/alert_policy_service/async_client.py b/google/cloud/monitoring_v3/services/alert_policy_service/async_client.py index 841cedd0..04b2608e 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/async_client.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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,20 +20,19 @@ 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.monitoring_v3.services.alert_policy_service import pagers from google.cloud.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service from google.cloud.monitoring_v3.types import mutation_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import AlertPolicyServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AlertPolicyServiceGrpcAsyncIOTransport from .client import AlertPolicyServiceClient @@ -68,31 +65,26 @@ class AlertPolicyServiceAsyncClient: parse_alert_policy_condition_path = staticmethod( AlertPolicyServiceClient.parse_alert_policy_condition_path ) - common_billing_account_path = staticmethod( AlertPolicyServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AlertPolicyServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AlertPolicyServiceClient.common_folder_path) parse_common_folder_path = staticmethod( AlertPolicyServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( AlertPolicyServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( AlertPolicyServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(AlertPolicyServiceClient.common_project_path) parse_common_project_path = staticmethod( AlertPolicyServiceClient.parse_common_project_path ) - common_location_path = staticmethod(AlertPolicyServiceClient.common_location_path) parse_common_location_path = staticmethod( AlertPolicyServiceClient.parse_common_location_path @@ -100,7 +92,8 @@ class AlertPolicyServiceAsyncClient: @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. @@ -115,7 +108,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 @@ -132,7 +125,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AlertPolicyServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AlertPolicyServiceTransport: The transport used by the client instance. @@ -147,12 +140,12 @@ def transport(self) -> AlertPolicyServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AlertPolicyServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the alert policy service client. + """Instantiates the alert policy service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -184,7 +177,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AlertPolicyServiceClient( credentials=credentials, transport=transport, @@ -225,7 +217,6 @@ async def list_alert_policies( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -254,7 +245,6 @@ async def list_alert_policies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -267,7 +257,8 @@ async def list_alert_policies( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -319,7 +310,6 @@ async def get_alert_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -349,7 +339,6 @@ async def get_alert_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -362,7 +351,8 @@ async def get_alert_policy( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -428,7 +418,6 @@ async def create_alert_policy( This corresponds to the ``alert_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -458,7 +447,6 @@ async def create_alert_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if alert_policy is not None: @@ -512,7 +500,6 @@ async def delete_alert_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -533,7 +520,6 @@ async def delete_alert_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -546,7 +532,8 @@ async def delete_alert_policy( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -569,7 +556,7 @@ async def update_alert_policy( self, request: alert_service.UpdateAlertPolicyRequest = None, *, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, alert_policy: alert.AlertPolicy = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -626,7 +613,6 @@ async def update_alert_policy( This corresponds to the ``alert_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -656,7 +642,6 @@ async def update_alert_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if update_mask is not None: request.update_mask = update_mask if alert_policy is not None: diff --git a/google/cloud/monitoring_v3/services/alert_policy_service/client.py b/google/cloud/monitoring_v3/services/alert_policy_service/client.py index 5f32a4a8..1f03f5d5 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/client.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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 @@ -36,10 +34,9 @@ from google.cloud.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service from google.cloud.monitoring_v3.types import mutation_record -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import AlertPolicyServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AlertPolicyServiceGrpcTransport from .transports.grpc_asyncio import AlertPolicyServiceGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class AlertPolicyServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[AlertPolicyServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -94,7 +91,8 @@ class AlertPolicyServiceClient(metaclass=AlertPolicyServiceClientMeta): @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: @@ -128,7 +126,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. @@ -145,7 +144,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 @@ -164,23 +163,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AlertPolicyServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AlertPolicyServiceTransport: The transport used by the client instance. + AlertPolicyServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def alert_policy_path(project: str, alert_policy: str,) -> str: - """Return a fully-qualified alert_policy string.""" + """Returns a fully-qualified alert_policy string.""" return "projects/{project}/alertPolicies/{alert_policy}".format( project=project, alert_policy=alert_policy, ) @staticmethod def parse_alert_policy_path(path: str) -> Dict[str, str]: - """Parse a alert_policy path into its component segments.""" + """Parses a alert_policy path into its component segments.""" m = re.match( r"^projects/(?P.+?)/alertPolicies/(?P.+?)$", path ) @@ -190,14 +190,14 @@ def parse_alert_policy_path(path: str) -> Dict[str, str]: def alert_policy_condition_path( project: str, alert_policy: str, condition: str, ) -> str: - """Return a fully-qualified alert_policy_condition string.""" + """Returns a fully-qualified alert_policy_condition string.""" return "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}".format( project=project, alert_policy=alert_policy, condition=condition, ) @staticmethod def parse_alert_policy_condition_path(path: str) -> Dict[str, str]: - """Parse a alert_policy_condition path into its component segments.""" + """Parses a alert_policy_condition path into its component segments.""" m = re.match( r"^projects/(?P.+?)/alertPolicies/(?P.+?)/conditions/(?P.+?)$", path, @@ -206,7 +206,7 @@ def parse_alert_policy_condition_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, ) @@ -219,7 +219,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 @@ -230,7 +230,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 @@ -241,7 +241,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 @@ -252,7 +252,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, ) @@ -266,12 +266,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, AlertPolicyServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the alert policy service client. + """Instantiates the alert policy service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -326,9 +326,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: @@ -340,12 +341,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. @@ -360,8 +363,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: @@ -409,7 +412,6 @@ def list_alert_policies( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -440,10 +442,8 @@ def list_alert_policies( # there are no flattened fields. if not isinstance(request, alert_service.ListAlertPoliciesRequest): request = alert_service.ListAlertPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -495,7 +495,6 @@ def get_alert_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -527,10 +526,8 @@ def get_alert_policy( # there are no flattened fields. if not isinstance(request, alert_service.GetAlertPolicyRequest): request = alert_service.GetAlertPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -596,7 +593,6 @@ def create_alert_policy( This corresponds to the ``alert_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -628,10 +624,8 @@ def create_alert_policy( # there are no flattened fields. if not isinstance(request, alert_service.CreateAlertPolicyRequest): request = alert_service.CreateAlertPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if alert_policy is not None: @@ -681,7 +675,6 @@ def delete_alert_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -704,10 +697,8 @@ def delete_alert_policy( # there are no flattened fields. if not isinstance(request, alert_service.DeleteAlertPolicyRequest): request = alert_service.DeleteAlertPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -730,7 +721,7 @@ def update_alert_policy( self, request: alert_service.UpdateAlertPolicyRequest = None, *, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, alert_policy: alert.AlertPolicy = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -787,7 +778,6 @@ def update_alert_policy( This corresponds to the ``alert_policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -819,10 +809,8 @@ def update_alert_policy( # there are no flattened fields. if not isinstance(request, alert_service.UpdateAlertPolicyRequest): request = alert_service.UpdateAlertPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if update_mask is not None: request.update_mask = update_mask if alert_policy is not None: diff --git a/google/cloud/monitoring_v3/services/alert_policy_service/pagers.py b/google/cloud/monitoring_v3/services/alert_policy_service/pagers.py index 4a5e61c2..11381e37 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/pagers.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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/google/cloud/monitoring_v3/services/alert_policy_service/transports/__init__.py b/google/cloud/monitoring_v3/services/alert_policy_service/transports/__init__.py index 64244d17..d42bb124 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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/google/cloud/monitoring_v3/services/alert_policy_service/transports/base.py b/google/cloud/monitoring_v3/services/alert_policy_service/transports/base.py index 4da7980d..a74fbdfe 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service -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 AlertPolicyServiceTransport(abc.ABC): """Abstract transport class for AlertPolicyService.""" @@ -49,21 +59,24 @@ class AlertPolicyServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -119,7 +179,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -133,7 +194,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -150,7 +212,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -165,11 +228,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_alert_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [alert_service.ListAlertPoliciesRequest], - typing.Union[ + Union[ alert_service.ListAlertPoliciesResponse, - typing.Awaitable[alert_service.ListAlertPoliciesResponse], + Awaitable[alert_service.ListAlertPoliciesResponse], ], ]: raise NotImplementedError() @@ -177,36 +240,36 @@ def list_alert_policies( @property def get_alert_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [alert_service.GetAlertPolicyRequest], - typing.Union[alert.AlertPolicy, typing.Awaitable[alert.AlertPolicy]], + Union[alert.AlertPolicy, Awaitable[alert.AlertPolicy]], ]: raise NotImplementedError() @property def create_alert_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [alert_service.CreateAlertPolicyRequest], - typing.Union[alert.AlertPolicy, typing.Awaitable[alert.AlertPolicy]], + Union[alert.AlertPolicy, Awaitable[alert.AlertPolicy]], ]: raise NotImplementedError() @property def delete_alert_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [alert_service.DeleteAlertPolicyRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def update_alert_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [alert_service.UpdateAlertPolicyRequest], - typing.Union[alert.AlertPolicy, typing.Awaitable[alert.AlertPolicy]], + Union[alert.AlertPolicy, Awaitable[alert.AlertPolicy]], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc.py b/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc.py index 2de02cda..4c41102e 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AlertPolicyServiceTransport, DEFAULT_CLIENT_INFO @@ -60,7 +57,7 @@ def __init__( self, *, host: str = "monitoring.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -74,7 +71,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 @@ -184,7 +182,7 @@ def __init__( def create_channel( cls, host: str = "monitoring.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, @@ -215,13 +213,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, ) @@ -316,7 +316,7 @@ def create_alert_policy( @property def delete_alert_policy( self, - ) -> Callable[[alert_service.DeleteAlertPolicyRequest], empty.Empty]: + ) -> Callable[[alert_service.DeleteAlertPolicyRequest], empty_pb2.Empty]: r"""Return a callable for the delete alert policy method over gRPC. Deletes an alerting policy. @@ -335,7 +335,7 @@ def delete_alert_policy( self._stubs["delete_alert_policy"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.AlertPolicyService/DeleteAlertPolicy", request_serializer=alert_service.DeleteAlertPolicyRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_alert_policy"] diff --git a/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc_asyncio.py index 11b5c4d7..a07bde32 100644 --- a/google/cloud/monitoring_v3/services/alert_policy_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/alert_policy_service/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.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AlertPolicyServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AlertPolicyServiceGrpcTransport @@ -63,7 +60,7 @@ class AlertPolicyServiceGrpcAsyncIOTransport(AlertPolicyServiceTransport): def create_channel( cls, host: str = "monitoring.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, @@ -90,13 +87,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, ) @@ -104,7 +103,7 @@ def __init__( self, *, host: str = "monitoring.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, @@ -118,7 +117,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 +176,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 @@ -322,7 +321,7 @@ def create_alert_policy( @property def delete_alert_policy( self, - ) -> Callable[[alert_service.DeleteAlertPolicyRequest], Awaitable[empty.Empty]]: + ) -> Callable[[alert_service.DeleteAlertPolicyRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete alert policy method over gRPC. Deletes an alerting policy. @@ -341,7 +340,7 @@ def delete_alert_policy( self._stubs["delete_alert_policy"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.AlertPolicyService/DeleteAlertPolicy", request_serializer=alert_service.DeleteAlertPolicyRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_alert_policy"] diff --git a/google/cloud/monitoring_v3/services/group_service/__init__.py b/google/cloud/monitoring_v3/services/group_service/__init__.py index 8486d514..18611a8a 100644 --- a/google/cloud/monitoring_v3/services/group_service/__init__.py +++ b/google/cloud/monitoring_v3/services/group_service/__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 GroupServiceClient from .async_client import GroupServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/group_service/async_client.py b/google/cloud/monitoring_v3/services/group_service/async_client.py index 433e9371..ae215e68 100644 --- a/google/cloud/monitoring_v3/services/group_service/async_client.py +++ b/google/cloud/monitoring_v3/services/group_service/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,18 +20,17 @@ 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 import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.group_service import pagers from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service - from .transports.base import GroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import GroupServiceGrpcAsyncIOTransport from .client import GroupServiceClient @@ -61,27 +58,22 @@ class GroupServiceAsyncClient: group_path = staticmethod(GroupServiceClient.group_path) parse_group_path = staticmethod(GroupServiceClient.parse_group_path) - common_billing_account_path = staticmethod( GroupServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( GroupServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(GroupServiceClient.common_folder_path) parse_common_folder_path = staticmethod(GroupServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(GroupServiceClient.common_organization_path) parse_common_organization_path = staticmethod( GroupServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(GroupServiceClient.common_project_path) parse_common_project_path = staticmethod( GroupServiceClient.parse_common_project_path ) - common_location_path = staticmethod(GroupServiceClient.common_location_path) parse_common_location_path = staticmethod( GroupServiceClient.parse_common_location_path @@ -89,7 +81,8 @@ class GroupServiceAsyncClient: @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. @@ -104,7 +97,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 @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GroupServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: GroupServiceTransport: The transport used by the client instance. @@ -135,12 +128,12 @@ def transport(self) -> GroupServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, GroupServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the group service client. + """Instantiates the group service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -172,7 +165,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = GroupServiceClient( credentials=credentials, transport=transport, @@ -205,7 +197,6 @@ async def list_groups( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -234,7 +225,6 @@ async def list_groups( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -247,7 +237,8 @@ async def list_groups( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -297,7 +288,6 @@ async def get_group( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -355,7 +345,6 @@ async def get_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -368,7 +357,8 @@ async def get_group( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -421,7 +411,6 @@ async def create_group( This corresponds to the ``group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,7 +468,6 @@ async def create_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if group is not None: @@ -528,7 +516,6 @@ async def update_group( This corresponds to the ``group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -586,7 +573,6 @@ async def update_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if group is not None: request.group = group @@ -599,7 +585,8 @@ async def update_group( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -647,7 +634,6 @@ async def delete_group( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -668,7 +654,6 @@ async def delete_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -681,7 +666,8 @@ async def delete_group( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -726,7 +712,6 @@ async def list_group_members( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -755,7 +740,6 @@ async def list_group_members( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -768,7 +752,8 @@ async def list_group_members( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), diff --git a/google/cloud/monitoring_v3/services/group_service/client.py b/google/cloud/monitoring_v3/services/group_service/client.py index 813bc0a7..75db40f0 100644 --- a/google/cloud/monitoring_v3/services/group_service/client.py +++ b/google/cloud/monitoring_v3/services/group_service/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,21 +21,20 @@ 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 from google.oauth2 import service_account # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.group_service import pagers from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service - from .transports.base import GroupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import GroupServiceGrpcTransport from .transports.grpc_asyncio import GroupServiceGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class GroupServiceClientMeta(type): _transport_registry["grpc_asyncio"] = GroupServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[GroupServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -91,7 +88,8 @@ class GroupServiceClient(metaclass=GroupServiceClientMeta): @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: @@ -125,7 +123,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. @@ -142,7 +141,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 @@ -161,27 +160,28 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> GroupServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - GroupServiceTransport: The transport used by the client instance. + GroupServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def group_path(project: str, group: str,) -> str: - """Return a fully-qualified group string.""" + """Returns a fully-qualified group string.""" return "projects/{project}/groups/{group}".format(project=project, group=group,) @staticmethod def parse_group_path(path: str) -> Dict[str, str]: - """Parse a group path into its component segments.""" + """Parses a group path into its component segments.""" m = re.match(r"^projects/(?P.+?)/groups/(?P.+?)$", path) return m.groupdict() if m else {} @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, ) @@ -194,7 +194,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 @@ -205,7 +205,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 @@ -216,7 +216,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 @@ -227,7 +227,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, ) @@ -241,12 +241,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, GroupServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the group service client. + """Instantiates the group service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -301,9 +301,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: @@ -315,12 +316,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. @@ -335,8 +338,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: @@ -376,7 +379,6 @@ def list_groups( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -407,10 +409,8 @@ def list_groups( # there are no flattened fields. if not isinstance(request, group_service.ListGroupsRequest): request = group_service.ListGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -460,7 +460,6 @@ def get_group( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -520,10 +519,8 @@ def get_group( # there are no flattened fields. if not isinstance(request, group_service.GetGroupRequest): request = group_service.GetGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -576,7 +573,6 @@ def create_group( This corresponds to the ``group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -636,10 +632,8 @@ def create_group( # there are no flattened fields. if not isinstance(request, group_service.CreateGroupRequest): request = group_service.CreateGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if group is not None: @@ -684,7 +678,6 @@ def update_group( This corresponds to the ``group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -744,10 +737,8 @@ def update_group( # there are no flattened fields. if not isinstance(request, group_service.UpdateGroupRequest): request = group_service.UpdateGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if group is not None: request.group = group @@ -795,7 +786,6 @@ def delete_group( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -818,10 +808,8 @@ def delete_group( # there are no flattened fields. if not isinstance(request, group_service.DeleteGroupRequest): request = group_service.DeleteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -866,7 +854,6 @@ def list_group_members( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -897,10 +884,8 @@ def list_group_members( # there are no flattened fields. if not isinstance(request, group_service.ListGroupMembersRequest): request = group_service.ListGroupMembersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/monitoring_v3/services/group_service/pagers.py b/google/cloud/monitoring_v3/services/group_service/pagers.py index c2ff3904..92700563 100644 --- a/google/cloud/monitoring_v3/services/group_service/pagers.py +++ b/google/cloud/monitoring_v3/services/group_service/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, @@ -26,7 +24,7 @@ Optional, ) -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group_service @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -213,7 +211,7 @@ def pages(self) -> Iterable[group_service.ListGroupMembersResponse]: self._response = self._method(self._request, metadata=self._metadata) yield self._response - def __iter__(self) -> Iterable[monitored_resource.MonitoredResource]: + def __iter__(self) -> Iterable[monitored_resource_pb2.MonitoredResource]: for page in self.pages: yield from page.members @@ -247,7 +245,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -275,7 +273,7 @@ async def pages(self) -> AsyncIterable[group_service.ListGroupMembersResponse]: self._response = await self._method(self._request, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterable[monitored_resource.MonitoredResource]: + def __aiter__(self) -> AsyncIterable[monitored_resource_pb2.MonitoredResource]: async def async_generator(): async for page in self.pages: for response in page.members: diff --git a/google/cloud/monitoring_v3/services/group_service/transports/__init__.py b/google/cloud/monitoring_v3/services/group_service/transports/__init__.py index 12ae8abb..224c2c36 100644 --- a/google/cloud/monitoring_v3/services/group_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/group_service/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/google/cloud/monitoring_v3/services/group_service/transports/base.py b/google/cloud/monitoring_v3/services/group_service/transports/base.py index 905f2150..9048e1d3 100644 --- a/google/cloud/monitoring_v3/services/group_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/group_service/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.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service -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( @@ -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 GroupServiceTransport(abc.ABC): """Abstract transport class for GroupService.""" @@ -50,21 +60,24 @@ class GroupServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -120,7 +180,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -134,7 +195,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -151,7 +213,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -165,7 +228,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -179,7 +243,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -191,11 +256,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_groups( self, - ) -> typing.Callable[ + ) -> Callable[ [group_service.ListGroupsRequest], - typing.Union[ + Union[ group_service.ListGroupsResponse, - typing.Awaitable[group_service.ListGroupsResponse], + Awaitable[group_service.ListGroupsResponse], ], ]: raise NotImplementedError() @@ -203,47 +268,46 @@ def list_groups( @property def get_group( self, - ) -> typing.Callable[ - [group_service.GetGroupRequest], - typing.Union[group.Group, typing.Awaitable[group.Group]], + ) -> Callable[ + [group_service.GetGroupRequest], Union[group.Group, Awaitable[group.Group]] ]: raise NotImplementedError() @property def create_group( self, - ) -> typing.Callable[ + ) -> Callable[ [group_service.CreateGroupRequest], - typing.Union[gm_group.Group, typing.Awaitable[gm_group.Group]], + Union[gm_group.Group, Awaitable[gm_group.Group]], ]: raise NotImplementedError() @property def update_group( self, - ) -> typing.Callable[ + ) -> Callable[ [group_service.UpdateGroupRequest], - typing.Union[gm_group.Group, typing.Awaitable[gm_group.Group]], + Union[gm_group.Group, Awaitable[gm_group.Group]], ]: raise NotImplementedError() @property def delete_group( self, - ) -> typing.Callable[ + ) -> Callable[ [group_service.DeleteGroupRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_group_members( self, - ) -> typing.Callable[ + ) -> Callable[ [group_service.ListGroupMembersRequest], - typing.Union[ + Union[ group_service.ListGroupMembersResponse, - typing.Awaitable[group_service.ListGroupMembersResponse], + Awaitable[group_service.ListGroupMembersResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/group_service/transports/grpc.py b/google/cloud/monitoring_v3/services/group_service/transports/grpc.py index 4e360876..176f5913 100644 --- a/google/cloud/monitoring_v3/services/group_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/group_service/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,14 +13,13 @@ # 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 @@ -29,8 +27,7 @@ from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import GroupServiceTransport, DEFAULT_CLIENT_INFO @@ -64,7 +61,7 @@ def __init__( self, *, host: str = "monitoring.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -78,7 +75,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 @@ -188,7 +186,7 @@ def __init__( def create_channel( cls, host: str = "monitoring.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, @@ -219,13 +217,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, ) @@ -339,7 +339,9 @@ def update_group( return self._stubs["update_group"] @property - def delete_group(self) -> Callable[[group_service.DeleteGroupRequest], empty.Empty]: + def delete_group( + self, + ) -> Callable[[group_service.DeleteGroupRequest], empty_pb2.Empty]: r"""Return a callable for the delete group method over gRPC. Deletes an existing group. @@ -358,7 +360,7 @@ def delete_group(self) -> Callable[[group_service.DeleteGroupRequest], empty.Emp self._stubs["delete_group"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.GroupService/DeleteGroup", request_serializer=group_service.DeleteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_group"] diff --git a/google/cloud/monitoring_v3/services/group_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/group_service/transports/grpc_asyncio.py index f4bd5a30..ad9e3d1a 100644 --- a/google/cloud/monitoring_v3/services/group_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/group_service/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,15 +13,14 @@ # 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 @@ -30,8 +28,7 @@ from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import GroupServiceTransport, DEFAULT_CLIENT_INFO from .grpc import GroupServiceGrpcTransport @@ -67,7 +64,7 @@ class GroupServiceGrpcAsyncIOTransport(GroupServiceTransport): def create_channel( cls, host: str = "monitoring.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, @@ -94,13 +91,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, ) @@ -108,7 +107,7 @@ def __init__( self, *, host: str = "monitoring.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, @@ -122,7 +121,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 @@ -180,7 +180,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 @@ -349,7 +348,7 @@ def update_group( @property def delete_group( self, - ) -> Callable[[group_service.DeleteGroupRequest], Awaitable[empty.Empty]]: + ) -> Callable[[group_service.DeleteGroupRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete group method over gRPC. Deletes an existing group. @@ -368,7 +367,7 @@ def delete_group( self._stubs["delete_group"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.GroupService/DeleteGroup", request_serializer=group_service.DeleteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_group"] diff --git a/google/cloud/monitoring_v3/services/metric_service/__init__.py b/google/cloud/monitoring_v3/services/metric_service/__init__.py index 5e9a2418..64b952a7 100644 --- a/google/cloud/monitoring_v3/services/metric_service/__init__.py +++ b/google/cloud/monitoring_v3/services/metric_service/__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 MetricServiceClient from .async_client import MetricServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/metric_service/async_client.py b/google/cloud/monitoring_v3/services/metric_service/async_client.py index 495cb02c..cc75b672 100644 --- a/google/cloud/monitoring_v3/services/metric_service/async_client.py +++ b/google/cloud/monitoring_v3/services/metric_service/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,21 +20,20 @@ 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 import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.metric_service import pagers from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import metric as gm_metric from google.cloud.monitoring_v3.types import metric_service - from .transports.base import MetricServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import MetricServiceGrpcAsyncIOTransport from .client import MetricServiceClient @@ -62,31 +59,26 @@ class MetricServiceAsyncClient: ) time_series_path = staticmethod(MetricServiceClient.time_series_path) parse_time_series_path = staticmethod(MetricServiceClient.parse_time_series_path) - common_billing_account_path = staticmethod( MetricServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( MetricServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(MetricServiceClient.common_folder_path) parse_common_folder_path = staticmethod( MetricServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( MetricServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( MetricServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(MetricServiceClient.common_project_path) parse_common_project_path = staticmethod( MetricServiceClient.parse_common_project_path ) - common_location_path = staticmethod(MetricServiceClient.common_location_path) parse_common_location_path = staticmethod( MetricServiceClient.parse_common_location_path @@ -94,7 +86,8 @@ class MetricServiceAsyncClient: @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. @@ -109,7 +102,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 @@ -126,7 +119,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> MetricServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: MetricServiceTransport: The transport used by the client instance. @@ -140,12 +133,12 @@ def transport(self) -> MetricServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, MetricServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the metric service client. + """Instantiates the metric service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -177,7 +170,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = MetricServiceClient( credentials=credentials, transport=transport, @@ -212,7 +204,6 @@ async def list_monitored_resource_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -241,7 +232,6 @@ async def list_monitored_resource_descriptors( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -254,7 +244,8 @@ async def list_monitored_resource_descriptors( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -288,7 +279,7 @@ async def get_monitored_resource_descriptor( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> monitored_resource.MonitoredResourceDescriptor: + ) -> monitored_resource_pb2.MonitoredResourceDescriptor: r"""Gets a single monitored resource descriptor. This method does not require a Workspace. @@ -310,7 +301,6 @@ async def get_monitored_resource_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -346,7 +336,6 @@ async def get_monitored_resource_descriptor( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -359,7 +348,8 @@ async def get_monitored_resource_descriptor( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -405,7 +395,6 @@ async def list_metric_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -434,7 +423,6 @@ async def list_metric_descriptors( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -447,7 +435,8 @@ async def list_metric_descriptors( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -481,7 +470,7 @@ async def get_metric_descriptor( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> ga_metric.MetricDescriptor: + ) -> metric_pb2.MetricDescriptor: r"""Gets a single metric descriptor. This method does not require a Workspace. @@ -502,7 +491,6 @@ async def get_metric_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -532,7 +520,6 @@ async def get_metric_descriptor( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -545,7 +532,8 @@ async def get_metric_descriptor( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -570,11 +558,11 @@ async def create_metric_descriptor( request: metric_service.CreateMetricDescriptorRequest = None, *, name: str = None, - metric_descriptor: ga_metric.MetricDescriptor = None, + metric_descriptor: metric_pb2.MetricDescriptor = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> ga_metric.MetricDescriptor: + ) -> metric_pb2.MetricDescriptor: r"""Creates a new metric descriptor. User-created metric descriptors define `custom metrics `__. @@ -602,7 +590,6 @@ async def create_metric_descriptor( This corresponds to the ``metric_descriptor`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -632,7 +619,6 @@ async def create_metric_descriptor( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if metric_descriptor is not None: @@ -689,7 +675,6 @@ async def delete_metric_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -710,7 +695,6 @@ async def delete_metric_descriptor( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -723,7 +707,8 @@ async def delete_metric_descriptor( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -806,7 +791,6 @@ async def list_time_series( This corresponds to the ``view`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -835,7 +819,6 @@ async def list_time_series( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if filter is not None: @@ -854,7 +837,8 @@ async def list_time_series( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -925,7 +909,6 @@ async def create_time_series( This corresponds to the ``time_series`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -946,10 +929,8 @@ async def create_time_series( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name - if time_series: request.time_series.extend(time_series) diff --git a/google/cloud/monitoring_v3/services/metric_service/client.py b/google/cloud/monitoring_v3/services/metric_service/client.py index ec267304..f694a7eb 100644 --- a/google/cloud/monitoring_v3/services/metric_service/client.py +++ b/google/cloud/monitoring_v3/services/metric_service/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,24 +21,23 @@ 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 from google.oauth2 import service_account # type: ignore -from google.api import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.metric_service import pagers from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import metric as gm_metric from google.cloud.monitoring_v3.types import metric_service - from .transports.base import MetricServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import MetricServiceGrpcTransport from .transports.grpc_asyncio import MetricServiceGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class MetricServiceClientMeta(type): _transport_registry["grpc_asyncio"] = MetricServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[MetricServiceTransport]: - """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 MetricServiceClient(metaclass=MetricServiceClientMeta): @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,21 +153,22 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> MetricServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - MetricServiceTransport: The transport used by the client instance. + MetricServiceTransport: The transport used by the client + instance. """ return self._transport '''@staticmethod def metric_descriptor_path(project: str,) -> str: - """Return a fully-qualified metric_descriptor string.""" + """Returns a fully-qualified metric_descriptor string.""" return "projects/{project}/metricDescriptors/{metric_descriptor=**}".format(project=project, ) @staticmethod def parse_metric_descriptor_path(path: str) -> Dict[str,str]: - """Parse a metric_descriptor path into its component segments.""" + """Parses a metric_descriptor path into its component segments.""" m = re.match(r"^projects/(?P.+?)/metricDescriptors/{metric_descriptor=**}$", path) return m.groupdict() if m else {}''' @@ -176,7 +176,7 @@ def parse_metric_descriptor_path(path: str) -> Dict[str,str]: def monitored_resource_descriptor_path( project: str, monitored_resource_descriptor: str, ) -> str: - """Return a fully-qualified monitored_resource_descriptor string.""" + """Returns a fully-qualified monitored_resource_descriptor string.""" return "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}".format( project=project, monitored_resource_descriptor=monitored_resource_descriptor, @@ -184,7 +184,7 @@ def monitored_resource_descriptor_path( @staticmethod def parse_monitored_resource_descriptor_path(path: str) -> Dict[str, str]: - """Parse a monitored_resource_descriptor path into its component segments.""" + """Parses a monitored_resource_descriptor path into its component segments.""" m = re.match( r"^projects/(?P.+?)/monitoredResourceDescriptors/(?P.+?)$", path, @@ -193,14 +193,14 @@ def parse_monitored_resource_descriptor_path(path: str) -> Dict[str, str]: @staticmethod def time_series_path(project: str, time_series: str,) -> str: - """Return a fully-qualified time_series string.""" + """Returns a fully-qualified time_series string.""" return "projects/{project}/timeSeries/{time_series}".format( project=project, time_series=time_series, ) @staticmethod def parse_time_series_path(path: str) -> Dict[str, str]: - """Parse a time_series path into its component segments.""" + """Parses a time_series path into its component segments.""" m = re.match( r"^projects/(?P.+?)/timeSeries/(?P.+?)$", path ) @@ -208,7 +208,7 @@ def parse_time_series_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, ) @@ -221,7 +221,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 @@ -232,7 +232,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 @@ -243,7 +243,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 @@ -254,7 +254,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, ) @@ -268,12 +268,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, MetricServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the metric service client. + """Instantiates the metric service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -328,9 +328,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: @@ -342,12 +343,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. @@ -362,8 +365,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: @@ -405,7 +408,6 @@ def list_monitored_resource_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -438,10 +440,8 @@ def list_monitored_resource_descriptors( request, metric_service.ListMonitoredResourceDescriptorsRequest ): request = metric_service.ListMonitoredResourceDescriptorsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -477,7 +477,7 @@ def get_monitored_resource_descriptor( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> monitored_resource.MonitoredResourceDescriptor: + ) -> monitored_resource_pb2.MonitoredResourceDescriptor: r"""Gets a single monitored resource descriptor. This method does not require a Workspace. @@ -499,7 +499,6 @@ def get_monitored_resource_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -539,10 +538,8 @@ def get_monitored_resource_descriptor( request, metric_service.GetMonitoredResourceDescriptorRequest ): request = metric_service.GetMonitoredResourceDescriptorRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -590,7 +587,6 @@ def list_metric_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -621,10 +617,8 @@ def list_metric_descriptors( # there are no flattened fields. if not isinstance(request, metric_service.ListMetricDescriptorsRequest): request = metric_service.ListMetricDescriptorsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -658,7 +652,7 @@ def get_metric_descriptor( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> ga_metric.MetricDescriptor: + ) -> metric_pb2.MetricDescriptor: r"""Gets a single metric descriptor. This method does not require a Workspace. @@ -679,7 +673,6 @@ def get_metric_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -711,10 +704,8 @@ def get_metric_descriptor( # there are no flattened fields. if not isinstance(request, metric_service.GetMetricDescriptorRequest): request = metric_service.GetMetricDescriptorRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -739,11 +730,11 @@ def create_metric_descriptor( request: metric_service.CreateMetricDescriptorRequest = None, *, name: str = None, - metric_descriptor: ga_metric.MetricDescriptor = None, + metric_descriptor: metric_pb2.MetricDescriptor = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> ga_metric.MetricDescriptor: + ) -> metric_pb2.MetricDescriptor: r"""Creates a new metric descriptor. User-created metric descriptors define `custom metrics `__. @@ -771,7 +762,6 @@ def create_metric_descriptor( This corresponds to the ``metric_descriptor`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -803,10 +793,8 @@ def create_metric_descriptor( # there are no flattened fields. if not isinstance(request, metric_service.CreateMetricDescriptorRequest): request = metric_service.CreateMetricDescriptorRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if metric_descriptor is not None: @@ -859,7 +847,6 @@ def delete_metric_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -882,10 +869,8 @@ def delete_metric_descriptor( # there are no flattened fields. if not isinstance(request, metric_service.DeleteMetricDescriptorRequest): request = metric_service.DeleteMetricDescriptorRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -968,7 +953,6 @@ def list_time_series( This corresponds to the ``view`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -999,10 +983,8 @@ def list_time_series( # there are no flattened fields. if not isinstance(request, metric_service.ListTimeSeriesRequest): request = metric_service.ListTimeSeriesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if filter is not None: @@ -1079,7 +1061,6 @@ def create_time_series( This corresponds to the ``time_series`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1102,10 +1083,8 @@ def create_time_series( # there are no flattened fields. if not isinstance(request, metric_service.CreateTimeSeriesRequest): request = metric_service.CreateTimeSeriesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if time_series is not None: diff --git a/google/cloud/monitoring_v3/services/metric_service/pagers.py b/google/cloud/monitoring_v3/services/metric_service/pagers.py index 825bae02..1db13a3e 100644 --- a/google/cloud/monitoring_v3/services/metric_service/pagers.py +++ b/google/cloud/monitoring_v3/services/metric_service/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, @@ -26,8 +24,8 @@ Optional, ) -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import metric as gm_metric from google.cloud.monitoring_v3.types import metric_service @@ -88,7 +86,7 @@ def pages( self._response = self._method(self._request, metadata=self._metadata) yield self._response - def __iter__(self) -> Iterable[monitored_resource.MonitoredResourceDescriptor]: + def __iter__(self) -> Iterable[monitored_resource_pb2.MonitoredResourceDescriptor]: for page in self.pages: yield from page.resource_descriptors @@ -124,7 +122,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -156,7 +154,7 @@ async def pages( def __aiter__( self, - ) -> AsyncIterable[monitored_resource.MonitoredResourceDescriptor]: + ) -> AsyncIterable[monitored_resource_pb2.MonitoredResourceDescriptor]: async def async_generator(): async for page in self.pages: for response in page.resource_descriptors: @@ -222,7 +220,7 @@ def pages(self) -> Iterable[metric_service.ListMetricDescriptorsResponse]: self._response = self._method(self._request, metadata=self._metadata) yield self._response - def __iter__(self) -> Iterable[ga_metric.MetricDescriptor]: + def __iter__(self) -> Iterable[metric_pb2.MetricDescriptor]: for page in self.pages: yield from page.metric_descriptors @@ -256,7 +254,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -286,7 +284,7 @@ async def pages( self._response = await self._method(self._request, metadata=self._metadata) yield self._response - def __aiter__(self) -> AsyncIterable[ga_metric.MetricDescriptor]: + def __aiter__(self) -> AsyncIterable[metric_pb2.MetricDescriptor]: async def async_generator(): async for page in self.pages: for response in page.metric_descriptors: @@ -386,7 +384,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/google/cloud/monitoring_v3/services/metric_service/transports/__init__.py b/google/cloud/monitoring_v3/services/metric_service/transports/__init__.py index 943ac0a8..44986865 100644 --- a/google/cloud/monitoring_v3/services/metric_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/metric_service/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/google/cloud/monitoring_v3/services/metric_service/transports/base.py b/google/cloud/monitoring_v3/services/metric_service/transports/base.py index a708c2f5..a84ba976 100644 --- a/google/cloud/monitoring_v3/services/metric_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/metric_service/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.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import metric_service -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( @@ -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 MetricServiceTransport(abc.ABC): """Abstract transport class for MetricService.""" @@ -51,21 +61,24 @@ class MetricServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.write", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 @@ -74,7 +87,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): @@ -88,29 +101,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 = { @@ -121,7 +181,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -135,7 +196,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -149,7 +211,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -163,7 +226,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -182,7 +246,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -196,7 +261,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -211,11 +277,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_monitored_resource_descriptors( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.ListMonitoredResourceDescriptorsRequest], - typing.Union[ + Union[ metric_service.ListMonitoredResourceDescriptorsResponse, - typing.Awaitable[metric_service.ListMonitoredResourceDescriptorsResponse], + Awaitable[metric_service.ListMonitoredResourceDescriptorsResponse], ], ]: raise NotImplementedError() @@ -223,11 +289,11 @@ def list_monitored_resource_descriptors( @property def get_monitored_resource_descriptor( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.GetMonitoredResourceDescriptorRequest], - typing.Union[ - monitored_resource.MonitoredResourceDescriptor, - typing.Awaitable[monitored_resource.MonitoredResourceDescriptor], + Union[ + monitored_resource_pb2.MonitoredResourceDescriptor, + Awaitable[monitored_resource_pb2.MonitoredResourceDescriptor], ], ]: raise NotImplementedError() @@ -235,11 +301,11 @@ def get_monitored_resource_descriptor( @property def list_metric_descriptors( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.ListMetricDescriptorsRequest], - typing.Union[ + Union[ metric_service.ListMetricDescriptorsResponse, - typing.Awaitable[metric_service.ListMetricDescriptorsResponse], + Awaitable[metric_service.ListMetricDescriptorsResponse], ], ]: raise NotImplementedError() @@ -247,42 +313,38 @@ def list_metric_descriptors( @property def get_metric_descriptor( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.GetMetricDescriptorRequest], - typing.Union[ - ga_metric.MetricDescriptor, typing.Awaitable[ga_metric.MetricDescriptor] - ], + Union[metric_pb2.MetricDescriptor, Awaitable[metric_pb2.MetricDescriptor]], ]: raise NotImplementedError() @property def create_metric_descriptor( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.CreateMetricDescriptorRequest], - typing.Union[ - ga_metric.MetricDescriptor, typing.Awaitable[ga_metric.MetricDescriptor] - ], + Union[metric_pb2.MetricDescriptor, Awaitable[metric_pb2.MetricDescriptor]], ]: raise NotImplementedError() @property def delete_metric_descriptor( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.DeleteMetricDescriptorRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_time_series( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.ListTimeSeriesRequest], - typing.Union[ + Union[ metric_service.ListTimeSeriesResponse, - typing.Awaitable[metric_service.ListTimeSeriesResponse], + Awaitable[metric_service.ListTimeSeriesResponse], ], ]: raise NotImplementedError() @@ -290,9 +352,9 @@ def list_time_series( @property def create_time_series( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.CreateTimeSeriesRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/metric_service/transports/grpc.py b/google/cloud/monitoring_v3/services/metric_service/transports/grpc.py index 0c6f78b0..132e9c6d 100644 --- a/google/cloud/monitoring_v3/services/metric_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/metric_service/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 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.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import metric_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import MetricServiceTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "monitoring.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 = "monitoring.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, ) @@ -263,7 +263,7 @@ def get_monitored_resource_descriptor( self, ) -> Callable[ [metric_service.GetMonitoredResourceDescriptorRequest], - monitored_resource.MonitoredResourceDescriptor, + monitored_resource_pb2.MonitoredResourceDescriptor, ]: r"""Return a callable for the get monitored resource descriptor method over gRPC. @@ -287,7 +287,7 @@ def get_monitored_resource_descriptor( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/GetMonitoredResourceDescriptor", request_serializer=metric_service.GetMonitoredResourceDescriptorRequest.serialize, - response_deserializer=monitored_resource.MonitoredResourceDescriptor.FromString, + response_deserializer=monitored_resource_pb2.MonitoredResourceDescriptor.FromString, ) return self._stubs["get_monitored_resource_descriptor"] @@ -325,7 +325,7 @@ def list_metric_descriptors( def get_metric_descriptor( self, ) -> Callable[ - [metric_service.GetMetricDescriptorRequest], ga_metric.MetricDescriptor + [metric_service.GetMetricDescriptorRequest], metric_pb2.MetricDescriptor ]: r"""Return a callable for the get metric descriptor method over gRPC. @@ -346,7 +346,7 @@ def get_metric_descriptor( self._stubs["get_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/GetMetricDescriptor", request_serializer=metric_service.GetMetricDescriptorRequest.serialize, - response_deserializer=ga_metric.MetricDescriptor.FromString, + response_deserializer=metric_pb2.MetricDescriptor.FromString, ) return self._stubs["get_metric_descriptor"] @@ -354,7 +354,7 @@ def get_metric_descriptor( def create_metric_descriptor( self, ) -> Callable[ - [metric_service.CreateMetricDescriptorRequest], ga_metric.MetricDescriptor + [metric_service.CreateMetricDescriptorRequest], metric_pb2.MetricDescriptor ]: r"""Return a callable for the create metric descriptor method over gRPC. @@ -376,14 +376,14 @@ def create_metric_descriptor( self._stubs["create_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/CreateMetricDescriptor", request_serializer=metric_service.CreateMetricDescriptorRequest.serialize, - response_deserializer=ga_metric.MetricDescriptor.FromString, + response_deserializer=metric_pb2.MetricDescriptor.FromString, ) return self._stubs["create_metric_descriptor"] @property def delete_metric_descriptor( self, - ) -> Callable[[metric_service.DeleteMetricDescriptorRequest], empty.Empty]: + ) -> Callable[[metric_service.DeleteMetricDescriptorRequest], empty_pb2.Empty]: r"""Return a callable for the delete metric descriptor method over gRPC. Deletes a metric descriptor. Only user-created `custom @@ -404,7 +404,7 @@ def delete_metric_descriptor( self._stubs["delete_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/DeleteMetricDescriptor", request_serializer=metric_service.DeleteMetricDescriptorRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_metric_descriptor"] @@ -440,7 +440,7 @@ def list_time_series( @property def create_time_series( self, - ) -> Callable[[metric_service.CreateTimeSeriesRequest], empty.Empty]: + ) -> Callable[[metric_service.CreateTimeSeriesRequest], empty_pb2.Empty]: r"""Return a callable for the create time series method over gRPC. Creates or adds data to one or more time series. @@ -463,7 +463,7 @@ def create_time_series( self._stubs["create_time_series"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/CreateTimeSeries", request_serializer=metric_service.CreateTimeSeriesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["create_time_series"] diff --git a/google/cloud/monitoring_v3/services/metric_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/metric_service/transports/grpc_asyncio.py index 3f682d92..389c6c30 100644 --- a/google/cloud/monitoring_v3/services/metric_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/metric_service/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 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.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import metric_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import MetricServiceTransport, DEFAULT_CLIENT_INFO from .grpc import MetricServiceGrpcTransport @@ -57,7 +54,7 @@ class MetricServiceGrpcAsyncIOTransport(MetricServiceTransport): def create_channel( cls, host: str = "monitoring.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 = "monitoring.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 @@ -267,7 +266,7 @@ def get_monitored_resource_descriptor( self, ) -> Callable[ [metric_service.GetMonitoredResourceDescriptorRequest], - Awaitable[monitored_resource.MonitoredResourceDescriptor], + Awaitable[monitored_resource_pb2.MonitoredResourceDescriptor], ]: r"""Return a callable for the get monitored resource descriptor method over gRPC. @@ -291,7 +290,7 @@ def get_monitored_resource_descriptor( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/GetMonitoredResourceDescriptor", request_serializer=metric_service.GetMonitoredResourceDescriptorRequest.serialize, - response_deserializer=monitored_resource.MonitoredResourceDescriptor.FromString, + response_deserializer=monitored_resource_pb2.MonitoredResourceDescriptor.FromString, ) return self._stubs["get_monitored_resource_descriptor"] @@ -330,7 +329,7 @@ def get_metric_descriptor( self, ) -> Callable[ [metric_service.GetMetricDescriptorRequest], - Awaitable[ga_metric.MetricDescriptor], + Awaitable[metric_pb2.MetricDescriptor], ]: r"""Return a callable for the get metric descriptor method over gRPC. @@ -351,7 +350,7 @@ def get_metric_descriptor( self._stubs["get_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/GetMetricDescriptor", request_serializer=metric_service.GetMetricDescriptorRequest.serialize, - response_deserializer=ga_metric.MetricDescriptor.FromString, + response_deserializer=metric_pb2.MetricDescriptor.FromString, ) return self._stubs["get_metric_descriptor"] @@ -360,7 +359,7 @@ def create_metric_descriptor( self, ) -> Callable[ [metric_service.CreateMetricDescriptorRequest], - Awaitable[ga_metric.MetricDescriptor], + Awaitable[metric_pb2.MetricDescriptor], ]: r"""Return a callable for the create metric descriptor method over gRPC. @@ -382,7 +381,7 @@ def create_metric_descriptor( self._stubs["create_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/CreateMetricDescriptor", request_serializer=metric_service.CreateMetricDescriptorRequest.serialize, - response_deserializer=ga_metric.MetricDescriptor.FromString, + response_deserializer=metric_pb2.MetricDescriptor.FromString, ) return self._stubs["create_metric_descriptor"] @@ -390,7 +389,7 @@ def create_metric_descriptor( def delete_metric_descriptor( self, ) -> Callable[ - [metric_service.DeleteMetricDescriptorRequest], Awaitable[empty.Empty] + [metric_service.DeleteMetricDescriptorRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete metric descriptor method over gRPC. @@ -412,7 +411,7 @@ def delete_metric_descriptor( self._stubs["delete_metric_descriptor"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/DeleteMetricDescriptor", request_serializer=metric_service.DeleteMetricDescriptorRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_metric_descriptor"] @@ -449,7 +448,7 @@ def list_time_series( @property def create_time_series( self, - ) -> Callable[[metric_service.CreateTimeSeriesRequest], Awaitable[empty.Empty]]: + ) -> Callable[[metric_service.CreateTimeSeriesRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the create time series method over gRPC. Creates or adds data to one or more time series. @@ -472,7 +471,7 @@ def create_time_series( self._stubs["create_time_series"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.MetricService/CreateTimeSeries", request_serializer=metric_service.CreateTimeSeriesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["create_time_series"] diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/__init__.py b/google/cloud/monitoring_v3/services/notification_channel_service/__init__.py index a2a50f8b..bdda723c 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/__init__.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/__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 NotificationChannelServiceClient from .async_client import NotificationChannelServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/async_client.py b/google/cloud/monitoring_v3/services/notification_channel_service/async_client.py index 26a14a54..9f364a55 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/async_client.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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,23 +20,22 @@ 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 import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore from google.cloud.monitoring_v3.services.notification_channel_service import pagers from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record from google.cloud.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service -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 wrappers_pb2 as wrappers # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore from .transports.base import NotificationChannelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import NotificationChannelServiceGrpcAsyncIOTransport from .client import NotificationChannelServiceClient @@ -66,35 +63,30 @@ class NotificationChannelServiceAsyncClient: parse_notification_channel_descriptor_path = staticmethod( NotificationChannelServiceClient.parse_notification_channel_descriptor_path ) - common_billing_account_path = staticmethod( NotificationChannelServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( NotificationChannelServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod( NotificationChannelServiceClient.common_folder_path ) parse_common_folder_path = staticmethod( NotificationChannelServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( NotificationChannelServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( NotificationChannelServiceClient.parse_common_organization_path ) - common_project_path = staticmethod( NotificationChannelServiceClient.common_project_path ) parse_common_project_path = staticmethod( NotificationChannelServiceClient.parse_common_project_path ) - common_location_path = staticmethod( NotificationChannelServiceClient.common_location_path ) @@ -104,7 +96,8 @@ class NotificationChannelServiceAsyncClient: @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. @@ -119,7 +112,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 @@ -136,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NotificationChannelServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: NotificationChannelServiceTransport: The transport used by the client instance. @@ -151,12 +144,12 @@ def transport(self) -> NotificationChannelServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, NotificationChannelServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the notification channel service client. + """Instantiates the notification channel service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -188,7 +181,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = NotificationChannelServiceClient( credentials=credentials, transport=transport, @@ -231,7 +223,6 @@ async def list_notification_channel_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -262,7 +253,6 @@ async def list_notification_channel_descriptors( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -275,7 +265,8 @@ async def list_notification_channel_descriptors( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -329,7 +320,6 @@ async def get_notification_channel_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -359,7 +349,6 @@ async def get_notification_channel_descriptor( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -372,7 +361,8 @@ async def get_notification_channel_descriptor( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -426,7 +416,6 @@ async def list_notification_channels( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -455,7 +444,6 @@ async def list_notification_channels( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -468,7 +456,8 @@ async def list_notification_channels( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -526,7 +515,6 @@ async def get_notification_channel( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -558,7 +546,6 @@ async def get_notification_channel( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -571,7 +558,8 @@ async def get_notification_channel( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -634,7 +622,6 @@ async def create_notification_channel( This corresponds to the ``notification_channel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -666,7 +653,6 @@ async def create_notification_channel( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if notification_channel is not None: @@ -696,7 +682,7 @@ async def update_notification_channel( self, request: notification_service.UpdateNotificationChannelRequest = None, *, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, notification_channel: notification.NotificationChannel = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -724,7 +710,6 @@ async def update_notification_channel( This corresponds to the ``notification_channel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -756,7 +741,6 @@ async def update_notification_channel( # If we have keyword arguments corresponding to fields on the # request, apply these. - if update_mask is not None: request.update_mask = update_mask if notification_channel is not None: @@ -824,7 +808,6 @@ async def delete_notification_channel( This corresponds to the ``force`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -845,7 +828,6 @@ async def delete_notification_channel( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if force is not None: @@ -860,7 +842,8 @@ async def delete_notification_channel( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -903,7 +886,6 @@ async def send_notification_channel_verification_code( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -926,7 +908,6 @@ async def send_notification_channel_verification_code( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1002,7 +983,6 @@ async def get_notification_channel_verification_code( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1029,7 +1009,6 @@ async def get_notification_channel_verification_code( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1042,7 +1021,8 @@ async def get_notification_channel_verification_code( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -1101,7 +1081,6 @@ async def verify_notification_channel( This corresponds to the ``code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1133,7 +1112,6 @@ async def verify_notification_channel( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if code is not None: @@ -1148,7 +1126,8 @@ async def verify_notification_channel( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/client.py b/google/cloud/monitoring_v3/services/notification_channel_service/client.py index fae66469..dd7c4e1c 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/client.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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,26 +21,25 @@ 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 from google.oauth2 import service_account # type: ignore -from google.api import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore from google.cloud.monitoring_v3.services.notification_channel_service import pagers from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record from google.cloud.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service -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 wrappers_pb2 as wrappers # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore from .transports.base import NotificationChannelServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import NotificationChannelServiceGrpcTransport from .transports.grpc_asyncio import NotificationChannelServiceGrpcAsyncIOTransport @@ -65,7 +62,7 @@ class NotificationChannelServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[NotificationChannelServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -90,7 +87,8 @@ class NotificationChannelServiceClient(metaclass=NotificationChannelServiceClien @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: @@ -124,7 +122,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. @@ -141,7 +140,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 @@ -160,23 +159,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> NotificationChannelServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - NotificationChannelServiceTransport: The transport used by the client instance. + NotificationChannelServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def notification_channel_path(project: str, notification_channel: str,) -> str: - """Return a fully-qualified notification_channel string.""" + """Returns a fully-qualified notification_channel string.""" return "projects/{project}/notificationChannels/{notification_channel}".format( project=project, notification_channel=notification_channel, ) @staticmethod def parse_notification_channel_path(path: str) -> Dict[str, str]: - """Parse a notification_channel path into its component segments.""" + """Parses a notification_channel path into its component segments.""" m = re.match( r"^projects/(?P.+?)/notificationChannels/(?P.+?)$", path, @@ -187,14 +187,14 @@ def parse_notification_channel_path(path: str) -> Dict[str, str]: def notification_channel_descriptor_path( project: str, channel_descriptor: str, ) -> str: - """Return a fully-qualified notification_channel_descriptor string.""" + """Returns a fully-qualified notification_channel_descriptor string.""" return "projects/{project}/notificationChannelDescriptors/{channel_descriptor}".format( project=project, channel_descriptor=channel_descriptor, ) @staticmethod def parse_notification_channel_descriptor_path(path: str) -> Dict[str, str]: - """Parse a notification_channel_descriptor path into its component segments.""" + """Parses a notification_channel_descriptor path into its component segments.""" m = re.match( r"^projects/(?P.+?)/notificationChannelDescriptors/(?P.+?)$", path, @@ -203,7 +203,7 @@ def parse_notification_channel_descriptor_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, ) @@ -216,7 +216,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 @@ -227,7 +227,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 @@ -238,7 +238,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 @@ -249,7 +249,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, ) @@ -263,12 +263,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, NotificationChannelServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the notification channel service client. + """Instantiates the notification channel service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -323,9 +323,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: @@ -337,12 +338,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. @@ -357,8 +360,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: @@ -408,7 +411,6 @@ def list_notification_channel_descriptors( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -443,10 +445,8 @@ def list_notification_channel_descriptors( request = notification_service.ListNotificationChannelDescriptorsRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -502,7 +502,6 @@ def get_notification_channel_descriptor( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -538,10 +537,8 @@ def get_notification_channel_descriptor( request = notification_service.GetNotificationChannelDescriptorRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -597,7 +594,6 @@ def list_notification_channels( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -630,10 +626,8 @@ def list_notification_channels( request, notification_service.ListNotificationChannelsRequest ): request = notification_service.ListNotificationChannelsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -693,7 +687,6 @@ def get_notification_channel( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -727,10 +720,8 @@ def get_notification_channel( # there are no flattened fields. if not isinstance(request, notification_service.GetNotificationChannelRequest): request = notification_service.GetNotificationChannelRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -793,7 +784,6 @@ def create_notification_channel( This corresponds to the ``notification_channel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -829,10 +819,8 @@ def create_notification_channel( request, notification_service.CreateNotificationChannelRequest ): request = notification_service.CreateNotificationChannelRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if notification_channel is not None: @@ -860,7 +848,7 @@ def update_notification_channel( self, request: notification_service.UpdateNotificationChannelRequest = None, *, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, notification_channel: notification.NotificationChannel = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -888,7 +876,6 @@ def update_notification_channel( This corresponds to the ``notification_channel`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -924,10 +911,8 @@ def update_notification_channel( request, notification_service.UpdateNotificationChannelRequest ): request = notification_service.UpdateNotificationChannelRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if update_mask is not None: request.update_mask = update_mask if notification_channel is not None: @@ -993,7 +978,6 @@ def delete_notification_channel( This corresponds to the ``force`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1018,10 +1002,8 @@ def delete_notification_channel( request, notification_service.DeleteNotificationChannelRequest ): request = notification_service.DeleteNotificationChannelRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if force is not None: @@ -1068,7 +1050,6 @@ def send_notification_channel_verification_code( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1095,10 +1076,8 @@ def send_notification_channel_verification_code( request = notification_service.SendNotificationChannelVerificationCodeRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1172,7 +1151,6 @@ def get_notification_channel_verification_code( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1203,10 +1181,8 @@ def get_notification_channel_verification_code( request = notification_service.GetNotificationChannelVerificationCodeRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1267,7 +1243,6 @@ def verify_notification_channel( This corresponds to the ``code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1303,10 +1278,8 @@ def verify_notification_channel( request, notification_service.VerifyNotificationChannelRequest ): request = notification_service.VerifyNotificationChannelRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if code is not None: diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/pagers.py b/google/cloud/monitoring_v3/services/notification_channel_service/pagers.py index 01dc3879..2640ed20 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/pagers.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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, @@ -127,7 +125,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -261,7 +259,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/google/cloud/monitoring_v3/services/notification_channel_service/transports/__init__.py b/google/cloud/monitoring_v3/services/notification_channel_service/transports/__init__.py index 3b8843d6..83f3878d 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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/google/cloud/monitoring_v3/services/notification_channel_service/transports/base.py b/google/cloud/monitoring_v3/services/notification_channel_service/transports/base.py index a856407e..d86bc922 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service -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 NotificationChannelServiceTransport(abc.ABC): """Abstract transport class for NotificationChannelService.""" @@ -49,21 +59,24 @@ class NotificationChannelServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -119,7 +179,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -133,7 +194,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -147,7 +209,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -161,7 +224,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -185,7 +249,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -204,7 +269,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -218,7 +284,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -230,13 +297,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_notification_channel_descriptors( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.ListNotificationChannelDescriptorsRequest], - typing.Union[ + Union[ notification_service.ListNotificationChannelDescriptorsResponse, - typing.Awaitable[ - notification_service.ListNotificationChannelDescriptorsResponse - ], + Awaitable[notification_service.ListNotificationChannelDescriptorsResponse], ], ]: raise NotImplementedError() @@ -244,11 +309,11 @@ def list_notification_channel_descriptors( @property def get_notification_channel_descriptor( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.GetNotificationChannelDescriptorRequest], - typing.Union[ + Union[ notification.NotificationChannelDescriptor, - typing.Awaitable[notification.NotificationChannelDescriptor], + Awaitable[notification.NotificationChannelDescriptor], ], ]: raise NotImplementedError() @@ -256,11 +321,11 @@ def get_notification_channel_descriptor( @property def list_notification_channels( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.ListNotificationChannelsRequest], - typing.Union[ + Union[ notification_service.ListNotificationChannelsResponse, - typing.Awaitable[notification_service.ListNotificationChannelsResponse], + Awaitable[notification_service.ListNotificationChannelsResponse], ], ]: raise NotImplementedError() @@ -268,11 +333,11 @@ def list_notification_channels( @property def get_notification_channel( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.GetNotificationChannelRequest], - typing.Union[ + Union[ notification.NotificationChannel, - typing.Awaitable[notification.NotificationChannel], + Awaitable[notification.NotificationChannel], ], ]: raise NotImplementedError() @@ -280,11 +345,11 @@ def get_notification_channel( @property def create_notification_channel( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.CreateNotificationChannelRequest], - typing.Union[ + Union[ notification.NotificationChannel, - typing.Awaitable[notification.NotificationChannel], + Awaitable[notification.NotificationChannel], ], ]: raise NotImplementedError() @@ -292,11 +357,11 @@ def create_notification_channel( @property def update_notification_channel( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.UpdateNotificationChannelRequest], - typing.Union[ + Union[ notification.NotificationChannel, - typing.Awaitable[notification.NotificationChannel], + Awaitable[notification.NotificationChannel], ], ]: raise NotImplementedError() @@ -304,29 +369,29 @@ def update_notification_channel( @property def delete_notification_channel( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.DeleteNotificationChannelRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def send_notification_channel_verification_code( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.SendNotificationChannelVerificationCodeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_notification_channel_verification_code( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.GetNotificationChannelVerificationCodeRequest], - typing.Union[ + Union[ notification_service.GetNotificationChannelVerificationCodeResponse, - typing.Awaitable[ + Awaitable[ notification_service.GetNotificationChannelVerificationCodeResponse ], ], @@ -336,11 +401,11 @@ def get_notification_channel_verification_code( @property def verify_notification_channel( self, - ) -> typing.Callable[ + ) -> Callable[ [notification_service.VerifyNotificationChannelRequest], - typing.Union[ + Union[ notification.NotificationChannel, - typing.Awaitable[notification.NotificationChannel], + Awaitable[notification.NotificationChannel], ], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc.py b/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc.py index 6c84eced..4d6b3f66 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import NotificationChannelServiceTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "monitoring.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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "monitoring.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, @@ -208,13 +206,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, ) @@ -421,7 +421,9 @@ def update_notification_channel( @property def delete_notification_channel( self, - ) -> Callable[[notification_service.DeleteNotificationChannelRequest], empty.Empty]: + ) -> Callable[ + [notification_service.DeleteNotificationChannelRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete notification channel method over gRPC. Deletes a notification channel. @@ -440,7 +442,7 @@ def delete_notification_channel( self._stubs["delete_notification_channel"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.NotificationChannelService/DeleteNotificationChannel", request_serializer=notification_service.DeleteNotificationChannelRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_channel"] @@ -449,7 +451,7 @@ def send_notification_channel_verification_code( self, ) -> Callable[ [notification_service.SendNotificationChannelVerificationCodeRequest], - empty.Empty, + empty_pb2.Empty, ]: r"""Return a callable for the send notification channel verification code method over gRPC. @@ -474,7 +476,7 @@ def send_notification_channel_verification_code( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.NotificationChannelService/SendNotificationChannelVerificationCode", request_serializer=notification_service.SendNotificationChannelVerificationCodeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["send_notification_channel_verification_code"] diff --git a/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc_asyncio.py index 5d7d4d53..5cf4c952 100644 --- a/google/cloud/monitoring_v3/services/notification_channel_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/notification_channel_service/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.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import NotificationChannelServiceTransport, DEFAULT_CLIENT_INFO from .grpc import NotificationChannelServiceGrpcTransport @@ -58,7 +55,7 @@ class NotificationChannelServiceGrpcAsyncIOTransport( def create_channel( cls, host: str = "monitoring.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, @@ -85,13 +82,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, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "monitoring.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, @@ -113,7 +112,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 @@ -171,7 +171,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 @@ -428,7 +427,8 @@ def update_notification_channel( def delete_notification_channel( self, ) -> Callable[ - [notification_service.DeleteNotificationChannelRequest], Awaitable[empty.Empty] + [notification_service.DeleteNotificationChannelRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete notification channel method over gRPC. @@ -448,7 +448,7 @@ def delete_notification_channel( self._stubs["delete_notification_channel"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.NotificationChannelService/DeleteNotificationChannel", request_serializer=notification_service.DeleteNotificationChannelRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_channel"] @@ -457,7 +457,7 @@ def send_notification_channel_verification_code( self, ) -> Callable[ [notification_service.SendNotificationChannelVerificationCodeRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the send notification channel verification code method over gRPC. @@ -482,7 +482,7 @@ def send_notification_channel_verification_code( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.NotificationChannelService/SendNotificationChannelVerificationCode", request_serializer=notification_service.SendNotificationChannelVerificationCodeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["send_notification_channel_verification_code"] diff --git a/google/cloud/monitoring_v3/services/query_service/__init__.py b/google/cloud/monitoring_v3/services/query_service/__init__.py index 4d7b09e5..de309faa 100644 --- a/google/cloud/monitoring_v3/services/query_service/__init__.py +++ b/google/cloud/monitoring_v3/services/query_service/__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 QueryServiceClient from .async_client import QueryServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/query_service/async_client.py b/google/cloud/monitoring_v3/services/query_service/async_client.py index 1b320eb0..f86aa667 100644 --- a/google/cloud/monitoring_v3/services/query_service/async_client.py +++ b/google/cloud/monitoring_v3/services/query_service/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.monitoring_v3.services.query_service import pagers from google.cloud.monitoring_v3.types import metric from google.cloud.monitoring_v3.types import metric_service - from .transports.base import QueryServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import QueryServiceGrpcAsyncIOTransport from .client import QueryServiceClient @@ -54,20 +51,16 @@ class QueryServiceAsyncClient: parse_common_billing_account_path = staticmethod( QueryServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(QueryServiceClient.common_folder_path) parse_common_folder_path = staticmethod(QueryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(QueryServiceClient.common_organization_path) parse_common_organization_path = staticmethod( QueryServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(QueryServiceClient.common_project_path) parse_common_project_path = staticmethod( QueryServiceClient.parse_common_project_path ) - common_location_path = staticmethod(QueryServiceClient.common_location_path) parse_common_location_path = staticmethod( QueryServiceClient.parse_common_location_path @@ -75,7 +68,8 @@ class QueryServiceAsyncClient: @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) -> QueryServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: QueryServiceTransport: The transport used by the client instance. @@ -121,12 +115,12 @@ def transport(self) -> QueryServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, QueryServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the query service client. + """Instantiates the query service 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 = QueryServiceClient( credentials=credentials, transport=transport, @@ -180,7 +173,6 @@ async def query_time_series( Args: request (:class:`google.cloud.monitoring_v3.types.QueryTimeSeriesRequest`): The request object. The `QueryTimeSeries` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -196,7 +188,6 @@ async def query_time_series( """ # Create or coerce a protobuf request object. - request = metric_service.QueryTimeSeriesRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/monitoring_v3/services/query_service/client.py b/google/cloud/monitoring_v3/services/query_service/client.py index 583c1934..6451e732 100644 --- a/google/cloud/monitoring_v3/services/query_service/client.py +++ b/google/cloud/monitoring_v3/services/query_service/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.monitoring_v3.services.query_service import pagers from google.cloud.monitoring_v3.types import metric from google.cloud.monitoring_v3.types import metric_service - from .transports.base import QueryServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import QueryServiceGrpcTransport from .transports.grpc_asyncio import QueryServiceGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class QueryServiceClientMeta(type): _transport_registry["grpc_asyncio"] = QueryServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[QueryServiceTransport]: - """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 QueryServiceClient(metaclass=QueryServiceClientMeta): @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) -> QueryServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - QueryServiceTransport: The transport used by the client instance. + QueryServiceTransport: 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, QueryServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the query service client. + """Instantiates the query service 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 query_time_series( Args: request (google.cloud.monitoring_v3.types.QueryTimeSeriesRequest): The request object. The `QueryTimeSeries` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -359,7 +361,6 @@ def query_time_series( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a metric_service.QueryTimeSeriesRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/monitoring_v3/services/query_service/pagers.py b/google/cloud/monitoring_v3/services/query_service/pagers.py index 0c8a5059..01905b3c 100644 --- a/google/cloud/monitoring_v3/services/query_service/pagers.py +++ b/google/cloud/monitoring_v3/services/query_service/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/google/cloud/monitoring_v3/services/query_service/transports/__init__.py b/google/cloud/monitoring_v3/services/query_service/transports/__init__.py index cdf23933..b43ce0b8 100644 --- a/google/cloud/monitoring_v3/services/query_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/query_service/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/google/cloud/monitoring_v3/services/query_service/transports/base.py b/google/cloud/monitoring_v3/services/query_service/transports/base.py index b43f052c..4c82239e 100644 --- a/google/cloud/monitoring_v3/services/query_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/query_service/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.monitoring_v3.types import metric_service - 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 QueryServiceTransport(abc.ABC): """Abstract transport class for QueryService.""" @@ -47,21 +57,24 @@ class QueryServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -118,11 +178,11 @@ def _prep_wrapped_messages(self, client_info): @property def query_time_series( self, - ) -> typing.Callable[ + ) -> Callable[ [metric_service.QueryTimeSeriesRequest], - typing.Union[ + Union[ metric_service.QueryTimeSeriesResponse, - typing.Awaitable[metric_service.QueryTimeSeriesResponse], + Awaitable[metric_service.QueryTimeSeriesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/query_service/transports/grpc.py b/google/cloud/monitoring_v3/services/query_service/transports/grpc.py index 83b5dbc8..101353ed 100644 --- a/google/cloud/monitoring_v3/services/query_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/query_service/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.monitoring_v3.types import metric_service - from .base import QueryServiceTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "monitoring.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 = "monitoring.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/google/cloud/monitoring_v3/services/query_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/query_service/transports/grpc_asyncio.py index eaaa49b1..d212df3f 100644 --- a/google/cloud/monitoring_v3/services/query_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/query_service/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.monitoring_v3.types import metric_service - from .base import QueryServiceTransport, DEFAULT_CLIENT_INFO from .grpc import QueryServiceGrpcTransport @@ -55,7 +52,7 @@ class QueryServiceGrpcAsyncIOTransport(QueryServiceTransport): def create_channel( cls, host: str = "monitoring.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 = "monitoring.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/google/cloud/monitoring_v3/services/service_monitoring_service/__init__.py b/google/cloud/monitoring_v3/services/service_monitoring_service/__init__.py index e0de505e..d9af87b2 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/__init__.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/__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 ServiceMonitoringServiceClient from .async_client import ServiceMonitoringServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/service_monitoring_service/async_client.py b/google/cloud/monitoring_v3/services/service_monitoring_service/async_client.py index 9e2e7519..fc940793 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/async_client.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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,19 +20,18 @@ 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.monitoring_v3.services.service_monitoring_service import pagers from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service -from google.protobuf import duration_pb2 as duration # type: ignore -from google.type import calendar_period_pb2 as calendar_period # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.type import calendar_period_pb2 # type: ignore from .transports.base import ServiceMonitoringServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ServiceMonitoringServiceGrpcAsyncIOTransport from .client import ServiceMonitoringServiceClient @@ -60,33 +57,28 @@ class ServiceMonitoringServiceAsyncClient: parse_service_level_objective_path = staticmethod( ServiceMonitoringServiceClient.parse_service_level_objective_path ) - common_billing_account_path = staticmethod( ServiceMonitoringServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ServiceMonitoringServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ServiceMonitoringServiceClient.common_folder_path) parse_common_folder_path = staticmethod( ServiceMonitoringServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( ServiceMonitoringServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( ServiceMonitoringServiceClient.parse_common_organization_path ) - common_project_path = staticmethod( ServiceMonitoringServiceClient.common_project_path ) parse_common_project_path = staticmethod( ServiceMonitoringServiceClient.parse_common_project_path ) - common_location_path = staticmethod( ServiceMonitoringServiceClient.common_location_path ) @@ -96,7 +88,8 @@ class ServiceMonitoringServiceAsyncClient: @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. @@ -111,7 +104,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 @@ -128,7 +121,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ServiceMonitoringServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ServiceMonitoringServiceTransport: The transport used by the client instance. @@ -143,12 +136,12 @@ def transport(self) -> ServiceMonitoringServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ServiceMonitoringServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the service monitoring service client. + """Instantiates the service monitoring service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -180,7 +173,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ServiceMonitoringServiceClient( credentials=credentials, transport=transport, @@ -219,7 +211,6 @@ async def create_service( This corresponds to the ``service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -250,7 +241,6 @@ async def create_service( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if service is not None: @@ -301,7 +291,6 @@ async def get_service( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -332,7 +321,6 @@ async def get_service( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -345,7 +333,8 @@ async def get_service( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -392,7 +381,6 @@ async def list_services( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -421,7 +409,6 @@ async def list_services( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -434,7 +421,8 @@ async def list_services( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -481,7 +469,6 @@ async def update_service( This corresponds to the ``service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -512,7 +499,6 @@ async def update_service( # If we have keyword arguments corresponding to fields on the # request, apply these. - if service is not None: request.service = service @@ -563,7 +549,6 @@ async def delete_service( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -584,7 +569,6 @@ async def delete_service( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -597,7 +581,8 @@ async def delete_service( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -651,7 +636,6 @@ async def create_service_level_objective( This corresponds to the ``service_level_objective`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -689,7 +673,6 @@ async def create_service_level_objective( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if service_level_objective is not None: @@ -741,7 +724,6 @@ async def get_service_level_objective( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -779,7 +761,6 @@ async def get_service_level_objective( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -792,7 +773,8 @@ async def get_service_level_objective( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -840,7 +822,6 @@ async def list_service_level_objectives( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -869,7 +850,6 @@ async def list_service_level_objectives( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -882,7 +862,8 @@ async def list_service_level_objectives( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -931,7 +912,6 @@ async def update_service_level_objective( This corresponds to the ``service_level_objective`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -969,7 +949,6 @@ async def update_service_level_objective( # If we have keyword arguments corresponding to fields on the # request, apply these. - if service_level_objective is not None: request.service_level_objective = service_level_objective @@ -1026,7 +1005,6 @@ async def delete_service_level_objective( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1047,7 +1025,6 @@ async def delete_service_level_objective( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1060,7 +1037,8 @@ async def delete_service_level_objective( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), diff --git a/google/cloud/monitoring_v3/services/service_monitoring_service/client.py b/google/cloud/monitoring_v3/services/service_monitoring_service/client.py index 3078d125..88d4802d 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/client.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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 @@ -36,9 +34,8 @@ from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service -from google.protobuf import duration_pb2 as duration # type: ignore -from google.type import calendar_period_pb2 as calendar_period # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.type import calendar_period_pb2 # type: ignore from .transports.base import ServiceMonitoringServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ServiceMonitoringServiceGrpcTransport from .transports.grpc_asyncio import ServiceMonitoringServiceGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class ServiceMonitoringServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[ServiceMonitoringServiceTransport]: - """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 ServiceMonitoringServiceClient(metaclass=ServiceMonitoringServiceClientMet @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,23 +157,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ServiceMonitoringServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ServiceMonitoringServiceTransport: The transport used by the client instance. + ServiceMonitoringServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def service_path(project: str, service: str,) -> str: - """Return a fully-qualified service string.""" + """Returns a fully-qualified service string.""" return "projects/{project}/services/{service}".format( project=project, service=service, ) @staticmethod def parse_service_path(path: str) -> Dict[str, str]: - """Parse a service path into its component segments.""" + """Parses a service path into its component segments.""" m = re.match(r"^projects/(?P.+?)/services/(?P.+?)$", path) return m.groupdict() if m else {} @@ -182,7 +182,7 @@ def parse_service_path(path: str) -> Dict[str, str]: def service_level_objective_path( project: str, service: str, service_level_objective: str, ) -> str: - """Return a fully-qualified service_level_objective string.""" + """Returns a fully-qualified service_level_objective string.""" return "projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}".format( project=project, service=service, @@ -191,7 +191,7 @@ def service_level_objective_path( @staticmethod def parse_service_level_objective_path(path: str) -> Dict[str, str]: - """Parse a service_level_objective path into its component segments.""" + """Parses a service_level_objective path into its component segments.""" m = re.match( r"^projects/(?P.+?)/services/(?P.+?)/serviceLevelObjectives/(?P.+?)$", path, @@ -200,7 +200,7 @@ def parse_service_level_objective_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, ) @@ -213,7 +213,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 @@ -224,7 +224,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 @@ -235,7 +235,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 @@ -246,7 +246,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, ) @@ -260,12 +260,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, ServiceMonitoringServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the service monitoring service client. + """Instantiates the service monitoring service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -320,9 +320,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: @@ -334,12 +335,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. @@ -354,8 +357,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: @@ -401,7 +404,6 @@ def create_service( This corresponds to the ``service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -434,10 +436,8 @@ def create_service( # there are no flattened fields. if not isinstance(request, service_service.CreateServiceRequest): request = service_service.CreateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if service is not None: @@ -484,7 +484,6 @@ def get_service( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -517,10 +516,8 @@ def get_service( # there are no flattened fields. if not isinstance(request, service_service.GetServiceRequest): request = service_service.GetServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -567,7 +564,6 @@ def list_services( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -598,10 +594,8 @@ def list_services( # there are no flattened fields. if not isinstance(request, service_service.ListServicesRequest): request = service_service.ListServicesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -648,7 +642,6 @@ def update_service( This corresponds to the ``service`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -681,10 +674,8 @@ def update_service( # there are no flattened fields. if not isinstance(request, service_service.UpdateServiceRequest): request = service_service.UpdateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if service is not None: request.service = service @@ -731,7 +722,6 @@ def delete_service( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -754,10 +744,8 @@ def delete_service( # there are no flattened fields. if not isinstance(request, service_service.DeleteServiceRequest): request = service_service.DeleteServiceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -811,7 +799,6 @@ def create_service_level_objective( This corresponds to the ``service_level_objective`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -851,10 +838,8 @@ def create_service_level_objective( # there are no flattened fields. if not isinstance(request, service_service.CreateServiceLevelObjectiveRequest): request = service_service.CreateServiceLevelObjectiveRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if service_level_objective is not None: @@ -904,7 +889,6 @@ def get_service_level_objective( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -944,10 +928,8 @@ def get_service_level_objective( # there are no flattened fields. if not isinstance(request, service_service.GetServiceLevelObjectiveRequest): request = service_service.GetServiceLevelObjectiveRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -997,7 +979,6 @@ def list_service_level_objectives( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1028,10 +1009,8 @@ def list_service_level_objectives( # there are no flattened fields. if not isinstance(request, service_service.ListServiceLevelObjectivesRequest): request = service_service.ListServiceLevelObjectivesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1082,7 +1061,6 @@ def update_service_level_objective( This corresponds to the ``service_level_objective`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1122,10 +1100,8 @@ def update_service_level_objective( # there are no flattened fields. if not isinstance(request, service_service.UpdateServiceLevelObjectiveRequest): request = service_service.UpdateServiceLevelObjectiveRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if service_level_objective is not None: request.service_level_objective = service_level_objective @@ -1180,7 +1156,6 @@ def delete_service_level_objective( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1203,10 +1178,8 @@ def delete_service_level_objective( # there are no flattened fields. if not isinstance(request, service_service.DeleteServiceLevelObjectiveRequest): request = service_service.DeleteServiceLevelObjectiveRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/monitoring_v3/services/service_monitoring_service/pagers.py b/google/cloud/monitoring_v3/services/service_monitoring_service/pagers.py index 8af3947c..33da2e1a 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/pagers.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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 @@ -248,7 +246,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/google/cloud/monitoring_v3/services/service_monitoring_service/transports/__init__.py b/google/cloud/monitoring_v3/services/service_monitoring_service/transports/__init__.py index ce9d3d3d..f87e9da0 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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/google/cloud/monitoring_v3/services/service_monitoring_service/transports/base.py b/google/cloud/monitoring_v3/services/service_monitoring_service/transports/base.py index 39fddfd3..148b0c9c 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service -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( @@ -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 ServiceMonitoringServiceTransport(abc.ABC): """Abstract transport class for ServiceMonitoringService.""" @@ -50,21 +60,24 @@ class ServiceMonitoringServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -123,7 +183,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -137,7 +198,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -154,7 +216,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -173,7 +236,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -187,7 +251,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -206,7 +271,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -218,29 +284,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_service( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.CreateServiceRequest], - typing.Union[gm_service.Service, typing.Awaitable[gm_service.Service]], + Union[gm_service.Service, Awaitable[gm_service.Service]], ]: raise NotImplementedError() @property def get_service( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.GetServiceRequest], - typing.Union[service.Service, typing.Awaitable[service.Service]], + Union[service.Service, Awaitable[service.Service]], ]: raise NotImplementedError() @property def list_services( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.ListServicesRequest], - typing.Union[ + Union[ service_service.ListServicesResponse, - typing.Awaitable[service_service.ListServicesResponse], + Awaitable[service_service.ListServicesResponse], ], ]: raise NotImplementedError() @@ -248,53 +314,47 @@ def list_services( @property def update_service( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.UpdateServiceRequest], - typing.Union[gm_service.Service, typing.Awaitable[gm_service.Service]], + Union[gm_service.Service, Awaitable[gm_service.Service]], ]: raise NotImplementedError() @property def delete_service( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.DeleteServiceRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_service_level_objective( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.CreateServiceLevelObjectiveRequest], - typing.Union[ - service.ServiceLevelObjective, - typing.Awaitable[service.ServiceLevelObjective], - ], + Union[service.ServiceLevelObjective, Awaitable[service.ServiceLevelObjective]], ]: raise NotImplementedError() @property def get_service_level_objective( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.GetServiceLevelObjectiveRequest], - typing.Union[ - service.ServiceLevelObjective, - typing.Awaitable[service.ServiceLevelObjective], - ], + Union[service.ServiceLevelObjective, Awaitable[service.ServiceLevelObjective]], ]: raise NotImplementedError() @property def list_service_level_objectives( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.ListServiceLevelObjectivesRequest], - typing.Union[ + Union[ service_service.ListServiceLevelObjectivesResponse, - typing.Awaitable[service_service.ListServiceLevelObjectivesResponse], + Awaitable[service_service.ListServiceLevelObjectivesResponse], ], ]: raise NotImplementedError() @@ -302,21 +362,18 @@ def list_service_level_objectives( @property def update_service_level_objective( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.UpdateServiceLevelObjectiveRequest], - typing.Union[ - service.ServiceLevelObjective, - typing.Awaitable[service.ServiceLevelObjective], - ], + Union[service.ServiceLevelObjective, Awaitable[service.ServiceLevelObjective]], ]: raise NotImplementedError() @property def delete_service_level_objective( self, - ) -> typing.Callable[ + ) -> Callable[ [service_service.DeleteServiceLevelObjectiveRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc.py b/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc.py index e08155e7..b970b86d 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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,14 +13,13 @@ # 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 @@ -29,8 +27,7 @@ from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ServiceMonitoringServiceTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "monitoring.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,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 @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "monitoring.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, @@ -211,13 +209,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, ) @@ -336,7 +336,7 @@ def update_service( @property def delete_service( self, - ) -> Callable[[service_service.DeleteServiceRequest], empty.Empty]: + ) -> Callable[[service_service.DeleteServiceRequest], empty_pb2.Empty]: r"""Return a callable for the delete service method over gRPC. Soft delete this ``Service``. @@ -355,7 +355,7 @@ def delete_service( self._stubs["delete_service"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.ServiceMonitoringService/DeleteService", request_serializer=service_service.DeleteServiceRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_service"] @@ -483,7 +483,9 @@ def update_service_level_objective( @property def delete_service_level_objective( self, - ) -> Callable[[service_service.DeleteServiceLevelObjectiveRequest], empty.Empty]: + ) -> Callable[ + [service_service.DeleteServiceLevelObjectiveRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete service level objective method over gRPC. Delete the given ``ServiceLevelObjective``. @@ -504,7 +506,7 @@ def delete_service_level_objective( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.ServiceMonitoringService/DeleteServiceLevelObjective", request_serializer=service_service.DeleteServiceLevelObjectiveRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_service_level_objective"] diff --git a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc_asyncio.py index 3e562dc8..f59476d4 100644 --- a/google/cloud/monitoring_v3/services/service_monitoring_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/service_monitoring_service/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,15 +13,14 @@ # 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 @@ -30,8 +28,7 @@ from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ServiceMonitoringServiceTransport, DEFAULT_CLIENT_INFO from .grpc import ServiceMonitoringServiceGrpcTransport @@ -59,7 +56,7 @@ class ServiceMonitoringServiceGrpcAsyncIOTransport(ServiceMonitoringServiceTrans def create_channel( cls, host: str = "monitoring.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, @@ -86,13 +83,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, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "monitoring.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, @@ -114,7 +113,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 @@ -172,7 +172,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 @@ -345,7 +344,7 @@ def update_service( @property def delete_service( self, - ) -> Callable[[service_service.DeleteServiceRequest], Awaitable[empty.Empty]]: + ) -> Callable[[service_service.DeleteServiceRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete service method over gRPC. Soft delete this ``Service``. @@ -364,7 +363,7 @@ def delete_service( self._stubs["delete_service"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.ServiceMonitoringService/DeleteService", request_serializer=service_service.DeleteServiceRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_service"] @@ -494,7 +493,7 @@ def update_service_level_objective( def delete_service_level_objective( self, ) -> Callable[ - [service_service.DeleteServiceLevelObjectiveRequest], Awaitable[empty.Empty] + [service_service.DeleteServiceLevelObjectiveRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete service level objective method over gRPC. @@ -516,7 +515,7 @@ def delete_service_level_objective( ] = self.grpc_channel.unary_unary( "/google.monitoring.v3.ServiceMonitoringService/DeleteServiceLevelObjective", request_serializer=service_service.DeleteServiceLevelObjectiveRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_service_level_objective"] diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/__init__.py b/google/cloud/monitoring_v3/services/uptime_check_service/__init__.py index 5fb9abc6..f7be8d80 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/__init__.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/__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 UptimeCheckServiceClient from .async_client import UptimeCheckServiceAsyncClient diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/async_client.py b/google/cloud/monitoring_v3/services/uptime_check_service/async_client.py index e8fd9937..5cf92c80 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/async_client.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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,18 +20,17 @@ 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 import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.uptime_check_service import pagers from google.cloud.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service -from google.protobuf import duration_pb2 as duration # type: ignore - +from google.protobuf import duration_pb2 # type: ignore from .transports.base import UptimeCheckServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import UptimeCheckServiceGrpcAsyncIOTransport from .client import UptimeCheckServiceClient @@ -61,31 +58,26 @@ class UptimeCheckServiceAsyncClient: parse_uptime_check_config_path = staticmethod( UptimeCheckServiceClient.parse_uptime_check_config_path ) - common_billing_account_path = staticmethod( UptimeCheckServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( UptimeCheckServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(UptimeCheckServiceClient.common_folder_path) parse_common_folder_path = staticmethod( UptimeCheckServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( UptimeCheckServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( UptimeCheckServiceClient.parse_common_organization_path ) - common_project_path = staticmethod(UptimeCheckServiceClient.common_project_path) parse_common_project_path = staticmethod( UptimeCheckServiceClient.parse_common_project_path ) - common_location_path = staticmethod(UptimeCheckServiceClient.common_location_path) parse_common_location_path = staticmethod( UptimeCheckServiceClient.parse_common_location_path @@ -93,7 +85,8 @@ class UptimeCheckServiceAsyncClient: @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. @@ -108,7 +101,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 @@ -125,7 +118,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> UptimeCheckServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: UptimeCheckServiceTransport: The transport used by the client instance. @@ -140,12 +133,12 @@ def transport(self) -> UptimeCheckServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, UptimeCheckServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the uptime check service client. + """Instantiates the uptime check service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -177,7 +170,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = UptimeCheckServiceClient( credentials=credentials, transport=transport, @@ -213,7 +205,6 @@ async def list_uptime_check_configs( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -242,7 +233,6 @@ async def list_uptime_check_configs( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -255,7 +245,8 @@ async def list_uptime_check_configs( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -307,7 +298,6 @@ async def get_uptime_check_config( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -335,7 +325,6 @@ async def get_uptime_check_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -348,7 +337,8 @@ async def get_uptime_check_config( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -402,7 +392,6 @@ async def create_uptime_check_config( This corresponds to the ``uptime_check_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -430,7 +419,6 @@ async def create_uptime_check_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if uptime_check_config is not None: @@ -493,7 +481,6 @@ async def update_uptime_check_config( This corresponds to the ``uptime_check_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -521,7 +508,6 @@ async def update_uptime_check_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if uptime_check_config is not None: request.uptime_check_config = uptime_check_config @@ -576,7 +562,6 @@ async def delete_uptime_check_config( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -597,7 +582,6 @@ async def delete_uptime_check_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -610,7 +594,8 @@ async def delete_uptime_check_config( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -644,7 +629,6 @@ async def list_uptime_check_ips( request (:class:`google.cloud.monitoring_v3.types.ListUptimeCheckIpsRequest`): The request object. The protocol for the `ListUptimeCheckIps` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -660,7 +644,6 @@ async def list_uptime_check_ips( """ # Create or coerce a protobuf request object. - request = uptime_service.ListUptimeCheckIpsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -672,7 +655,8 @@ async def list_uptime_check_ips( maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/client.py b/google/cloud/monitoring_v3/services/uptime_check_service/client.py index d7d55120..ae64e42b 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/client.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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,21 +21,20 @@ 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 from google.oauth2 import service_account # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.services.uptime_check_service import pagers from google.cloud.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service -from google.protobuf import duration_pb2 as duration # type: ignore - +from google.protobuf import duration_pb2 # type: ignore from .transports.base import UptimeCheckServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import UptimeCheckServiceGrpcTransport from .transports.grpc_asyncio import UptimeCheckServiceGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class UptimeCheckServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[UptimeCheckServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -91,7 +88,8 @@ class UptimeCheckServiceClient(metaclass=UptimeCheckServiceClientMeta): @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: @@ -125,7 +123,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. @@ -142,7 +141,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 @@ -161,23 +160,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> UptimeCheckServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - UptimeCheckServiceTransport: The transport used by the client instance. + UptimeCheckServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def uptime_check_config_path(project: str, uptime_check_config: str,) -> str: - """Return a fully-qualified uptime_check_config string.""" + """Returns a fully-qualified uptime_check_config string.""" return "projects/{project}/uptimeCheckConfigs/{uptime_check_config}".format( project=project, uptime_check_config=uptime_check_config, ) @staticmethod def parse_uptime_check_config_path(path: str) -> Dict[str, str]: - """Parse a uptime_check_config path into its component segments.""" + """Parses a uptime_check_config path into its component segments.""" m = re.match( r"^projects/(?P.+?)/uptimeCheckConfigs/(?P.+?)$", path, @@ -186,7 +186,7 @@ def parse_uptime_check_config_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, ) @@ -199,7 +199,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 @@ -210,7 +210,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 @@ -221,7 +221,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 @@ -232,7 +232,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, ) @@ -246,12 +246,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, UptimeCheckServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the uptime check service client. + """Instantiates the uptime check service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -306,9 +306,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: @@ -320,12 +321,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. @@ -340,8 +343,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: @@ -384,7 +387,6 @@ def list_uptime_check_configs( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -415,10 +417,8 @@ def list_uptime_check_configs( # there are no flattened fields. if not isinstance(request, uptime_service.ListUptimeCheckConfigsRequest): request = uptime_service.ListUptimeCheckConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -472,7 +472,6 @@ def get_uptime_check_config( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -502,10 +501,8 @@ def get_uptime_check_config( # there are no flattened fields. if not isinstance(request, uptime_service.GetUptimeCheckConfigRequest): request = uptime_service.GetUptimeCheckConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -559,7 +556,6 @@ def create_uptime_check_config( This corresponds to the ``uptime_check_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -589,10 +585,8 @@ def create_uptime_check_config( # there are no flattened fields. if not isinstance(request, uptime_service.CreateUptimeCheckConfigRequest): request = uptime_service.CreateUptimeCheckConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if uptime_check_config is not None: @@ -653,7 +647,6 @@ def update_uptime_check_config( This corresponds to the ``uptime_check_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -683,10 +676,8 @@ def update_uptime_check_config( # there are no flattened fields. if not isinstance(request, uptime_service.UpdateUptimeCheckConfigRequest): request = uptime_service.UpdateUptimeCheckConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if uptime_check_config is not None: request.uptime_check_config = uptime_check_config @@ -739,7 +730,6 @@ def delete_uptime_check_config( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -762,10 +752,8 @@ def delete_uptime_check_config( # there are no flattened fields. if not isinstance(request, uptime_service.DeleteUptimeCheckConfigRequest): request = uptime_service.DeleteUptimeCheckConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -801,7 +789,6 @@ def list_uptime_check_ips( request (google.cloud.monitoring_v3.types.ListUptimeCheckIpsRequest): The request object. The protocol for the `ListUptimeCheckIps` request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -817,7 +804,6 @@ def list_uptime_check_ips( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a uptime_service.ListUptimeCheckIpsRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/pagers.py b/google/cloud/monitoring_v3/services/uptime_check_service/pagers.py index ec69778f..495fbefc 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/pagers.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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 @@ -248,7 +246,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/google/cloud/monitoring_v3/services/uptime_check_service/transports/__init__.py b/google/cloud/monitoring_v3/services/uptime_check_service/transports/__init__.py index bfe3276f..55981b7f 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/transports/__init__.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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/google/cloud/monitoring_v3/services/uptime_check_service/transports/base.py b/google/cloud/monitoring_v3/services/uptime_check_service/transports/base.py index 7864e472..2202b368 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/transports/base.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service -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 UptimeCheckServiceTransport(abc.ABC): """Abstract transport class for UptimeCheckService.""" @@ -49,21 +59,24 @@ class UptimeCheckServiceTransport(abc.ABC): "https://www.googleapis.com/auth/monitoring.read", ) + DEFAULT_HOST: str = "monitoring.googleapis.com" + def __init__( self, *, - host: str = "monitoring.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 = { @@ -119,7 +179,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -133,7 +194,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -157,7 +219,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -171,7 +234,8 @@ def _prep_wrapped_messages(self, client_info): maximum=30.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=30.0, ), @@ -183,11 +247,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_uptime_check_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.ListUptimeCheckConfigsRequest], - typing.Union[ + Union[ uptime_service.ListUptimeCheckConfigsResponse, - typing.Awaitable[uptime_service.ListUptimeCheckConfigsResponse], + Awaitable[uptime_service.ListUptimeCheckConfigsResponse], ], ]: raise NotImplementedError() @@ -195,53 +259,47 @@ def list_uptime_check_configs( @property def get_uptime_check_config( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.GetUptimeCheckConfigRequest], - typing.Union[ - uptime.UptimeCheckConfig, typing.Awaitable[uptime.UptimeCheckConfig] - ], + Union[uptime.UptimeCheckConfig, Awaitable[uptime.UptimeCheckConfig]], ]: raise NotImplementedError() @property def create_uptime_check_config( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.CreateUptimeCheckConfigRequest], - typing.Union[ - uptime.UptimeCheckConfig, typing.Awaitable[uptime.UptimeCheckConfig] - ], + Union[uptime.UptimeCheckConfig, Awaitable[uptime.UptimeCheckConfig]], ]: raise NotImplementedError() @property def update_uptime_check_config( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.UpdateUptimeCheckConfigRequest], - typing.Union[ - uptime.UptimeCheckConfig, typing.Awaitable[uptime.UptimeCheckConfig] - ], + Union[uptime.UptimeCheckConfig, Awaitable[uptime.UptimeCheckConfig]], ]: raise NotImplementedError() @property def delete_uptime_check_config( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.DeleteUptimeCheckConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_uptime_check_ips( self, - ) -> typing.Callable[ + ) -> Callable[ [uptime_service.ListUptimeCheckIpsRequest], - typing.Union[ + Union[ uptime_service.ListUptimeCheckIpsResponse, - typing.Awaitable[uptime_service.ListUptimeCheckIpsResponse], + Awaitable[uptime_service.ListUptimeCheckIpsResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc.py b/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc.py index 43813c1e..97669b35 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import UptimeCheckServiceTransport, DEFAULT_CLIENT_INFO @@ -59,7 +56,7 @@ def __init__( self, *, host: str = "monitoring.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -73,7 +70,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 @@ -183,7 +181,7 @@ def __init__( def create_channel( cls, host: str = "monitoring.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, @@ -214,13 +212,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, ) @@ -352,7 +352,7 @@ def update_uptime_check_config( @property def delete_uptime_check_config( self, - ) -> Callable[[uptime_service.DeleteUptimeCheckConfigRequest], empty.Empty]: + ) -> Callable[[uptime_service.DeleteUptimeCheckConfigRequest], empty_pb2.Empty]: r"""Return a callable for the delete uptime check config method over gRPC. Deletes an Uptime check configuration. Note that this @@ -374,7 +374,7 @@ def delete_uptime_check_config( self._stubs["delete_uptime_check_config"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.UptimeCheckService/DeleteUptimeCheckConfig", request_serializer=uptime_service.DeleteUptimeCheckConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_uptime_check_config"] diff --git a/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc_asyncio.py b/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc_asyncio.py index 3f9ff388..68f491cb 100644 --- a/google/cloud/monitoring_v3/services/uptime_check_service/transports/grpc_asyncio.py +++ b/google/cloud/monitoring_v3/services/uptime_check_service/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.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import UptimeCheckServiceTransport, DEFAULT_CLIENT_INFO from .grpc import UptimeCheckServiceGrpcTransport @@ -62,7 +59,7 @@ class UptimeCheckServiceGrpcAsyncIOTransport(UptimeCheckServiceTransport): def create_channel( cls, host: str = "monitoring.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, @@ -89,13 +86,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, ) @@ -103,7 +102,7 @@ def __init__( self, *, host: str = "monitoring.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, @@ -117,7 +116,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 @@ -175,7 +175,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 @@ -360,7 +359,7 @@ def update_uptime_check_config( def delete_uptime_check_config( self, ) -> Callable[ - [uptime_service.DeleteUptimeCheckConfigRequest], Awaitable[empty.Empty] + [uptime_service.DeleteUptimeCheckConfigRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete uptime check config method over gRPC. @@ -383,7 +382,7 @@ def delete_uptime_check_config( self._stubs["delete_uptime_check_config"] = self.grpc_channel.unary_unary( "/google.monitoring.v3.UptimeCheckService/DeleteUptimeCheckConfig", request_serializer=uptime_service.DeleteUptimeCheckConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_uptime_check_config"] diff --git a/google/cloud/monitoring_v3/types/__init__.py b/google/cloud/monitoring_v3/types/__init__.py index 11955c00..427f3a20 100644 --- a/google/cloud/monitoring_v3/types/__init__.py +++ b/google/cloud/monitoring_v3/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 .alert import AlertPolicy from .alert_service import ( CreateAlertPolicyRequest, diff --git a/google/cloud/monitoring_v3/types/alert.py b/google/cloud/monitoring_v3/types/alert.py index 0d1cd807..74d67610 100644 --- a/google/cloud/monitoring_v3/types/alert.py +++ b/google/cloud/monitoring_v3/types/alert.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record as gm_mutation_record -from google.protobuf import duration_pb2 as gp_duration # type: ignore -from google.protobuf import wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module(package="google.monitoring.v3", manifest={"AlertPolicy",},) @@ -149,9 +146,8 @@ class Documentation(proto.Message): more information. """ - content = proto.Field(proto.STRING, number=1) - - mime_type = proto.Field(proto.STRING, number=2) + content = proto.Field(proto.STRING, number=1,) + mime_type = proto.Field(proto.STRING, number=2,) class Condition(proto.Message): r"""A condition is a true/false test that determines when an @@ -220,9 +216,8 @@ class Trigger(proto.Message): the predicate for the condition to be triggered. """ - count = proto.Field(proto.INT32, number=1, oneof="type") - - percent = proto.Field(proto.DOUBLE, number=2, oneof="type") + count = proto.Field(proto.INT32, number=1, oneof="type",) + percent = proto.Field(proto.DOUBLE, number=2, oneof="type",) class MetricThreshold(proto.Message): r"""A condition type that compares a collection of time series @@ -315,26 +310,19 @@ class MetricThreshold(proto.Message): ``denominator_aggregations`` are specified. """ - filter = proto.Field(proto.STRING, number=2) - + filter = proto.Field(proto.STRING, number=2,) aggregations = proto.RepeatedField( proto.MESSAGE, number=8, message=common.Aggregation, ) - - denominator_filter = proto.Field(proto.STRING, number=9) - + denominator_filter = proto.Field(proto.STRING, number=9,) denominator_aggregations = proto.RepeatedField( proto.MESSAGE, number=10, message=common.Aggregation, ) - comparison = proto.Field(proto.ENUM, number=4, enum=common.ComparisonType,) - - threshold_value = proto.Field(proto.DOUBLE, number=5) - + threshold_value = proto.Field(proto.DOUBLE, number=5,) duration = proto.Field( - proto.MESSAGE, number=6, message=gp_duration.Duration, + proto.MESSAGE, number=6, message=duration_pb2.Duration, ) - trigger = proto.Field( proto.MESSAGE, number=7, message="AlertPolicy.Condition.Trigger", ) @@ -389,16 +377,13 @@ class MetricAbsence(proto.Message): identified by ``filter`` and ``aggregations``. """ - filter = proto.Field(proto.STRING, number=1) - + filter = proto.Field(proto.STRING, number=1,) aggregations = proto.RepeatedField( proto.MESSAGE, number=5, message=common.Aggregation, ) - duration = proto.Field( - proto.MESSAGE, number=2, message=gp_duration.Duration, + proto.MESSAGE, number=2, message=duration_pb2.Duration, ) - trigger = proto.Field( proto.MESSAGE, number=3, message="AlertPolicy.Condition.Trigger", ) @@ -435,34 +420,28 @@ class MonitoringQueryLanguageCondition(proto.Message): ``denominator_aggregations`` are specified. """ - query = proto.Field(proto.STRING, number=1) - + query = proto.Field(proto.STRING, number=1,) duration = proto.Field( - proto.MESSAGE, number=2, message=gp_duration.Duration, + proto.MESSAGE, number=2, message=duration_pb2.Duration, ) - trigger = proto.Field( proto.MESSAGE, number=3, message="AlertPolicy.Condition.Trigger", ) - name = proto.Field(proto.STRING, number=12) - - display_name = proto.Field(proto.STRING, number=6) - + name = proto.Field(proto.STRING, number=12,) + display_name = proto.Field(proto.STRING, number=6,) condition_threshold = proto.Field( proto.MESSAGE, number=1, oneof="condition", message="AlertPolicy.Condition.MetricThreshold", ) - condition_absent = proto.Field( proto.MESSAGE, number=2, oneof="condition", message="AlertPolicy.Condition.MetricAbsence", ) - condition_monitoring_query_language = proto.Field( proto.MESSAGE, number=19, @@ -470,28 +449,18 @@ class MonitoringQueryLanguageCondition(proto.Message): message="AlertPolicy.Condition.MonitoringQueryLanguageCondition", ) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) documentation = proto.Field(proto.MESSAGE, number=13, message=Documentation,) - - user_labels = proto.MapField(proto.STRING, proto.STRING, number=16) - + user_labels = proto.MapField(proto.STRING, proto.STRING, number=16,) conditions = proto.RepeatedField(proto.MESSAGE, number=12, message=Condition,) - combiner = proto.Field(proto.ENUM, number=6, enum=ConditionCombinerType,) - - enabled = proto.Field(proto.MESSAGE, number=17, message=wrappers.BoolValue,) - - validity = proto.Field(proto.MESSAGE, number=18, message=status.Status,) - - notification_channels = proto.RepeatedField(proto.STRING, number=14) - + enabled = proto.Field(proto.MESSAGE, number=17, message=wrappers_pb2.BoolValue,) + validity = proto.Field(proto.MESSAGE, number=18, message=status_pb2.Status,) + notification_channels = proto.RepeatedField(proto.STRING, number=14,) creation_record = proto.Field( proto.MESSAGE, number=10, message=gm_mutation_record.MutationRecord, ) - mutation_record = proto.Field( proto.MESSAGE, number=11, message=gm_mutation_record.MutationRecord, ) diff --git a/google/cloud/monitoring_v3/types/alert_service.py b/google/cloud/monitoring_v3/types/alert_service.py index ede64c59..531ed7c9 100644 --- a/google/cloud/monitoring_v3/types/alert_service.py +++ b/google/cloud/monitoring_v3/types/alert_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.monitoring_v3.types import alert -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -37,7 +34,6 @@ class CreateAlertPolicyRequest(proto.Message): r"""The protocol for the ``CreateAlertPolicy`` request. - Attributes: name (str): Required. The project in which to create the alerting @@ -61,14 +57,12 @@ class CreateAlertPolicyRequest(proto.Message): the new policy, including a new ``[ALERT_POLICY_ID]`` value. """ - name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=3,) alert_policy = proto.Field(proto.MESSAGE, number=2, message=alert.AlertPolicy,) class GetAlertPolicyRequest(proto.Message): r"""The protocol for the ``GetAlertPolicy`` request. - Attributes: name (str): Required. The alerting policy to retrieve. The format is: @@ -78,12 +72,11 @@ class GetAlertPolicyRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class ListAlertPoliciesRequest(proto.Message): r"""The protocol for the ``ListAlertPolicies`` request. - Attributes: name (str): Required. The project whose alert policies are to be listed. @@ -122,20 +115,15 @@ class ListAlertPoliciesRequest(proto.Message): results from the previous method call. """ - name = proto.Field(proto.STRING, number=4) - - filter = proto.Field(proto.STRING, number=5) - - order_by = proto.Field(proto.STRING, number=6) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=4,) + filter = proto.Field(proto.STRING, number=5,) + order_by = proto.Field(proto.STRING, number=6,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListAlertPoliciesResponse(proto.Message): r"""The protocol for the ``ListAlertPolicies`` response. - Attributes: alert_policies (Sequence[google.cloud.monitoring_v3.types.AlertPolicy]): The returned alert policies. @@ -157,15 +145,12 @@ def raw_page(self): alert_policies = proto.RepeatedField( proto.MESSAGE, number=3, message=alert.AlertPolicy, ) - - next_page_token = proto.Field(proto.STRING, number=2) - - total_size = proto.Field(proto.INT32, number=4) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=4,) class UpdateAlertPolicyRequest(proto.Message): r"""The protocol for the ``UpdateAlertPolicy`` request. - Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. A list of alerting policy field names. If this @@ -202,14 +187,14 @@ class UpdateAlertPolicyRequest(proto.Message): ``update_mask`` are ignored. """ - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) alert_policy = proto.Field(proto.MESSAGE, number=3, message=alert.AlertPolicy,) class DeleteAlertPolicyRequest(proto.Message): r"""The protocol for the ``DeleteAlertPolicy`` request. - Attributes: name (str): Required. The alerting policy to delete. The format is: @@ -222,7 +207,7 @@ class DeleteAlertPolicyRequest(proto.Message): [AlertPolicy][google.monitoring.v3.AlertPolicy]. """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/common.py b/google/cloud/monitoring_v3/types/common.py index 3a8a4770..363c393f 100644 --- a/google/cloud/monitoring_v3/types/common.py +++ b/google/cloud/monitoring_v3/types/common.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.api import distribution_pb2 as distribution # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.api import distribution_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -61,7 +58,6 @@ class ServiceTier(proto.Enum): class TypedValue(proto.Message): r"""A single strongly-typed value. - Attributes: bool_value (bool): A Boolean value: ``true`` or ``false``. @@ -79,16 +75,12 @@ class TypedValue(proto.Message): A distribution value. """ - bool_value = proto.Field(proto.BOOL, number=1, oneof="value") - - int64_value = proto.Field(proto.INT64, number=2, oneof="value") - - double_value = proto.Field(proto.DOUBLE, number=3, oneof="value") - - string_value = proto.Field(proto.STRING, number=4, oneof="value") - + bool_value = proto.Field(proto.BOOL, number=1, oneof="value",) + int64_value = proto.Field(proto.INT64, number=2, oneof="value",) + double_value = proto.Field(proto.DOUBLE, number=3, oneof="value",) + string_value = proto.Field(proto.STRING, number=4, oneof="value",) distribution_value = proto.Field( - proto.MESSAGE, number=5, oneof="value", message=distribution.Distribution, + proto.MESSAGE, number=5, oneof="value", message=distribution_pb2.Distribution, ) @@ -140,9 +132,8 @@ class TimeInterval(proto.Message): end time. """ - end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) class Aggregation(proto.Message): @@ -304,13 +295,12 @@ class Reducer(proto.Enum): REDUCE_PERCENTILE_50 = 11 REDUCE_PERCENTILE_05 = 12 - alignment_period = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - + alignment_period = proto.Field( + proto.MESSAGE, number=1, message=duration_pb2.Duration, + ) per_series_aligner = proto.Field(proto.ENUM, number=2, enum=Aligner,) - cross_series_reducer = proto.Field(proto.ENUM, number=4, enum=Reducer,) - - group_by_fields = proto.RepeatedField(proto.STRING, number=5) + group_by_fields = proto.RepeatedField(proto.STRING, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/dropped_labels.py b/google/cloud/monitoring_v3/types/dropped_labels.py index d49a1783..3d59507d 100644 --- a/google/cloud/monitoring_v3/types/dropped_labels.py +++ b/google/cloud/monitoring_v3/types/dropped_labels.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 @@ -48,7 +46,7 @@ class DroppedLabels(proto.Message): dropped in any aggregation. """ - label = proto.MapField(proto.STRING, proto.STRING, number=1) + label = proto.MapField(proto.STRING, proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/group.py b/google/cloud/monitoring_v3/types/group.py index 24c110ca..f2bfe515 100644 --- a/google/cloud/monitoring_v3/types/group.py +++ b/google/cloud/monitoring_v3/types/group.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 @@ -84,15 +82,11 @@ class Group(proto.Message): clusters. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - parent_name = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=5) - - is_cluster = proto.Field(proto.BOOL, number=6) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + parent_name = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=5,) + is_cluster = proto.Field(proto.BOOL, number=6,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/group_service.py b/google/cloud/monitoring_v3/types/group_service.py index b1bd4573..ecd9241e 100644 --- a/google/cloud/monitoring_v3/types/group_service.py +++ b/google/cloud/monitoring_v3/types/group_service.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.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import group as gm_group @@ -40,7 +37,6 @@ class ListGroupsRequest(proto.Message): r"""The ``ListGroup`` request. - Attributes: name (str): Required. The project whose groups are to be listed. The @@ -92,22 +88,16 @@ class ListGroupsRequest(proto.Message): additional results from the previous method call. """ - name = proto.Field(proto.STRING, number=7) - - children_of_group = proto.Field(proto.STRING, number=2, oneof="filter") - - ancestors_of_group = proto.Field(proto.STRING, number=3, oneof="filter") - - descendants_of_group = proto.Field(proto.STRING, number=4, oneof="filter") - - page_size = proto.Field(proto.INT32, number=5) - - page_token = proto.Field(proto.STRING, number=6) + name = proto.Field(proto.STRING, number=7,) + children_of_group = proto.Field(proto.STRING, number=2, oneof="filter",) + ancestors_of_group = proto.Field(proto.STRING, number=3, oneof="filter",) + descendants_of_group = proto.Field(proto.STRING, number=4, oneof="filter",) + page_size = proto.Field(proto.INT32, number=5,) + page_token = proto.Field(proto.STRING, number=6,) class ListGroupsResponse(proto.Message): r"""The ``ListGroups`` response. - Attributes: group (Sequence[google.cloud.monitoring_v3.types.Group]): The groups that match the specified filters. @@ -123,13 +113,11 @@ def raw_page(self): return self group = proto.RepeatedField(proto.MESSAGE, number=1, message=gm_group.Group,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetGroupRequest(proto.Message): r"""The ``GetGroup`` request. - Attributes: name (str): Required. The group to retrieve. The format is: @@ -139,12 +127,11 @@ class GetGroupRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class CreateGroupRequest(proto.Message): r"""The ``CreateGroup`` request. - Attributes: name (str): Required. The project in which to create the group. The @@ -161,16 +148,13 @@ class CreateGroupRequest(proto.Message): create the group. """ - name = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=4,) group = proto.Field(proto.MESSAGE, number=2, message=gm_group.Group,) - - validate_only = proto.Field(proto.BOOL, number=3) + validate_only = proto.Field(proto.BOOL, number=3,) class UpdateGroupRequest(proto.Message): r"""The ``UpdateGroup`` request. - Attributes: group (google.cloud.monitoring_v3.types.Group): Required. The new definition of the group. All fields of the @@ -182,8 +166,7 @@ class UpdateGroupRequest(proto.Message): """ group = proto.Field(proto.MESSAGE, number=2, message=gm_group.Group,) - - validate_only = proto.Field(proto.BOOL, number=3) + validate_only = proto.Field(proto.BOOL, number=3,) class DeleteGroupRequest(proto.Message): @@ -205,14 +188,12 @@ class DeleteGroupRequest(proto.Message): value is false. """ - name = proto.Field(proto.STRING, number=3) - - recursive = proto.Field(proto.BOOL, number=4) + name = proto.Field(proto.STRING, number=3,) + recursive = proto.Field(proto.BOOL, number=4,) class ListGroupMembersRequest(proto.Message): r"""The ``ListGroupMembers`` request. - Attributes: name (str): Required. The group whose members are listed. The format is: @@ -249,20 +230,15 @@ class ListGroupMembersRequest(proto.Message): minute is returned. """ - name = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) - - filter = proto.Field(proto.STRING, number=5) - + name = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + filter = proto.Field(proto.STRING, number=5,) interval = proto.Field(proto.MESSAGE, number=6, message=common.TimeInterval,) class ListGroupMembersResponse(proto.Message): r"""The ``ListGroupMembers`` response. - Attributes: members (Sequence[google.api.monitored_resource_pb2.MonitoredResource]): A set of monitored resources in the group. @@ -281,12 +257,10 @@ def raw_page(self): return self members = proto.RepeatedField( - proto.MESSAGE, number=1, message=monitored_resource.MonitoredResource, + proto.MESSAGE, number=1, message=monitored_resource_pb2.MonitoredResource, ) - - next_page_token = proto.Field(proto.STRING, number=2) - - total_size = proto.Field(proto.INT32, number=3) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/metric.py b/google/cloud/monitoring_v3/types/metric.py index dda03299..8c7d56ca 100644 --- a/google/cloud/monitoring_v3/types/metric.py +++ b/google/cloud/monitoring_v3/types/metric.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.api import label_pb2 as label # type: ignore -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import common @@ -40,7 +37,6 @@ class Point(proto.Message): r"""A single data point in a time series. - Attributes: interval (google.cloud.monitoring_v3.types.TimeInterval): The time interval to which the data point applies. For @@ -59,7 +55,6 @@ class Point(proto.Message): """ interval = proto.Field(proto.MESSAGE, number=1, message=common.TimeInterval,) - value = proto.Field(proto.MESSAGE, number=2, message=common.TypedValue,) @@ -122,32 +117,27 @@ class TimeSeries(proto.Message): of the stored metric values. """ - metric = proto.Field(proto.MESSAGE, number=1, message=ga_metric.Metric,) - + metric = proto.Field(proto.MESSAGE, number=1, message=metric_pb2.Metric,) resource = proto.Field( - proto.MESSAGE, number=2, message=monitored_resource.MonitoredResource, + proto.MESSAGE, number=2, message=monitored_resource_pb2.MonitoredResource, ) - metadata = proto.Field( - proto.MESSAGE, number=7, message=monitored_resource.MonitoredResourceMetadata, + proto.MESSAGE, + number=7, + message=monitored_resource_pb2.MonitoredResourceMetadata, ) - metric_kind = proto.Field( - proto.ENUM, number=3, enum=ga_metric.MetricDescriptor.MetricKind, + proto.ENUM, number=3, enum=metric_pb2.MetricDescriptor.MetricKind, ) - value_type = proto.Field( - proto.ENUM, number=4, enum=ga_metric.MetricDescriptor.ValueType, + proto.ENUM, number=4, enum=metric_pb2.MetricDescriptor.ValueType, ) - points = proto.RepeatedField(proto.MESSAGE, number=5, message="Point",) - - unit = proto.Field(proto.STRING, number=8) + unit = proto.Field(proto.STRING, number=8,) class TimeSeriesDescriptor(proto.Message): r"""A descriptor for the labels and points in a time series. - Attributes: label_descriptors (Sequence[google.api.label_pb2.LabelDescriptor]): Descriptors for the labels. @@ -157,7 +147,6 @@ class TimeSeriesDescriptor(proto.Message): class ValueDescriptor(proto.Message): r"""A descriptor for the value columns in a data point. - Attributes: key (str): The value key. @@ -172,22 +161,18 @@ class ValueDescriptor(proto.Message): if ``value_type`` is INTEGER, DOUBLE, DISTRIBUTION. """ - key = proto.Field(proto.STRING, number=1) - + key = proto.Field(proto.STRING, number=1,) value_type = proto.Field( - proto.ENUM, number=2, enum=ga_metric.MetricDescriptor.ValueType, + proto.ENUM, number=2, enum=metric_pb2.MetricDescriptor.ValueType, ) - metric_kind = proto.Field( - proto.ENUM, number=3, enum=ga_metric.MetricDescriptor.MetricKind, + proto.ENUM, number=3, enum=metric_pb2.MetricDescriptor.MetricKind, ) - - unit = proto.Field(proto.STRING, number=4) + unit = proto.Field(proto.STRING, number=4,) label_descriptors = proto.RepeatedField( - proto.MESSAGE, number=1, message=label.LabelDescriptor, + proto.MESSAGE, number=1, message=label_pb2.LabelDescriptor, ) - point_descriptors = proto.RepeatedField( proto.MESSAGE, number=5, message=ValueDescriptor, ) @@ -224,19 +209,16 @@ class PointData(proto.Message): values = proto.RepeatedField( proto.MESSAGE, number=1, message=common.TypedValue, ) - time_interval = proto.Field( proto.MESSAGE, number=2, message=common.TimeInterval, ) label_values = proto.RepeatedField(proto.MESSAGE, number=1, message="LabelValue",) - point_data = proto.RepeatedField(proto.MESSAGE, number=2, message=PointData,) class LabelValue(proto.Message): r"""A label value. - Attributes: bool_value (bool): A bool label value. @@ -246,11 +228,9 @@ class LabelValue(proto.Message): A string label value. """ - bool_value = proto.Field(proto.BOOL, number=1, oneof="value") - - int64_value = proto.Field(proto.INT64, number=2, oneof="value") - - string_value = proto.Field(proto.STRING, number=3, oneof="value") + bool_value = proto.Field(proto.BOOL, number=1, oneof="value",) + int64_value = proto.Field(proto.INT64, number=2, oneof="value",) + string_value = proto.Field(proto.STRING, number=3, oneof="value",) class QueryError(proto.Message): @@ -266,8 +246,7 @@ class QueryError(proto.Message): """ locator = proto.Field(proto.MESSAGE, number=1, message="TextLocator",) - - message = proto.Field(proto.STRING, number=2) + message = proto.Field(proto.STRING, number=2,) class TextLocator(proto.Message): @@ -319,7 +298,6 @@ class TextLocator(proto.Message): class Position(proto.Message): r"""The position of a byte within the text. - Attributes: line (int): The line, starting with 1, where the byte is @@ -330,19 +308,14 @@ class Position(proto.Message): index even though the text is UTF-8. """ - line = proto.Field(proto.INT32, number=1) - - column = proto.Field(proto.INT32, number=2) - - source = proto.Field(proto.STRING, number=1) + line = proto.Field(proto.INT32, number=1,) + column = proto.Field(proto.INT32, number=2,) + source = proto.Field(proto.STRING, number=1,) start_position = proto.Field(proto.MESSAGE, number=2, message=Position,) - end_position = proto.Field(proto.MESSAGE, number=3, message=Position,) - nested_locator = proto.Field(proto.MESSAGE, number=4, message="TextLocator",) - - nesting_reason = proto.Field(proto.STRING, number=5) + nesting_reason = proto.Field(proto.STRING, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/metric_service.py b/google/cloud/monitoring_v3/types/metric_service.py index 64ddf330..14d1005b 100644 --- a/google/cloud/monitoring_v3/types/metric_service.py +++ b/google/cloud/monitoring_v3/types/metric_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import metric as gm_metric -from google.rpc import status_pb2 as gr_status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -50,7 +47,6 @@ class ListMonitoredResourceDescriptorsRequest(proto.Message): r"""The ``ListMonitoredResourceDescriptors`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -80,18 +76,14 @@ class ListMonitoredResourceDescriptorsRequest(proto.Message): additional results from the previous method call. """ - name = proto.Field(proto.STRING, number=5) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=5,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListMonitoredResourceDescriptorsResponse(proto.Message): r"""The ``ListMonitoredResourceDescriptors`` response. - Attributes: resource_descriptors (Sequence[google.api.monitored_resource_pb2.MonitoredResourceDescriptor]): The monitored resource descriptors that are available to @@ -108,15 +100,15 @@ def raw_page(self): return self resource_descriptors = proto.RepeatedField( - proto.MESSAGE, number=1, message=monitored_resource.MonitoredResourceDescriptor, + proto.MESSAGE, + number=1, + message=monitored_resource_pb2.MonitoredResourceDescriptor, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetMonitoredResourceDescriptorRequest(proto.Message): r"""The ``GetMonitoredResourceDescriptor`` request. - Attributes: name (str): Required. The monitored resource descriptor to get. The @@ -130,12 +122,11 @@ class GetMonitoredResourceDescriptorRequest(proto.Message): ``cloudsql_database``. """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class ListMetricDescriptorsRequest(proto.Message): r"""The ``ListMetricDescriptors`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -165,18 +156,14 @@ class ListMetricDescriptorsRequest(proto.Message): additional results from the previous method call. """ - name = proto.Field(proto.STRING, number=5) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=5,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListMetricDescriptorsResponse(proto.Message): r"""The ``ListMetricDescriptors`` response. - Attributes: metric_descriptors (Sequence[google.api.metric_pb2.MetricDescriptor]): The metric descriptors that are available to the project and @@ -193,15 +180,13 @@ def raw_page(self): return self metric_descriptors = proto.RepeatedField( - proto.MESSAGE, number=1, message=ga_metric.MetricDescriptor, + proto.MESSAGE, number=1, message=metric_pb2.MetricDescriptor, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetMetricDescriptorRequest(proto.Message): r"""The ``GetMetricDescriptor`` request. - Attributes: name (str): Required. The metric descriptor on which to execute the @@ -215,12 +200,11 @@ class GetMetricDescriptorRequest(proto.Message): ``"compute.googleapis.com/instance/disk/read_bytes_count"``. """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class CreateMetricDescriptorRequest(proto.Message): r"""The ``CreateMetricDescriptor`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -235,16 +219,14 @@ class CreateMetricDescriptorRequest(proto.Message): descriptor. """ - name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=3,) metric_descriptor = proto.Field( - proto.MESSAGE, number=2, message=ga_metric.MetricDescriptor, + proto.MESSAGE, number=2, message=metric_pb2.MetricDescriptor, ) class DeleteMetricDescriptorRequest(proto.Message): r"""The ``DeleteMetricDescriptor`` request. - Attributes: name (str): Required. The metric descriptor on which to execute the @@ -258,12 +240,11 @@ class DeleteMetricDescriptorRequest(proto.Message): ``"custom.googleapis.com/my_test_metric"``. """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class ListTimeSeriesRequest(proto.Message): r"""The ``ListTimeSeries`` request. - Attributes: name (str): Required. The project, organization or folder on which to @@ -327,30 +308,21 @@ class TimeSeriesView(proto.Enum): FULL = 0 HEADERS = 1 - name = proto.Field(proto.STRING, number=10) - - filter = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=10,) + filter = proto.Field(proto.STRING, number=2,) interval = proto.Field(proto.MESSAGE, number=4, message=common.TimeInterval,) - aggregation = proto.Field(proto.MESSAGE, number=5, message=common.Aggregation,) - secondary_aggregation = proto.Field( proto.MESSAGE, number=11, message=common.Aggregation, ) - - order_by = proto.Field(proto.STRING, number=6) - + order_by = proto.Field(proto.STRING, number=6,) view = proto.Field(proto.ENUM, number=7, enum=TimeSeriesView,) - - page_size = proto.Field(proto.INT32, number=8) - - page_token = proto.Field(proto.STRING, number=9) + page_size = proto.Field(proto.INT32, number=8,) + page_token = proto.Field(proto.STRING, number=9,) class ListTimeSeriesResponse(proto.Message): r"""The ``ListTimeSeries`` response. - Attributes: time_series (Sequence[google.cloud.monitoring_v3.types.TimeSeries]): One or more time series that match the filter @@ -379,19 +351,15 @@ def raw_page(self): time_series = proto.RepeatedField( proto.MESSAGE, number=1, message=gm_metric.TimeSeries, ) - - next_page_token = proto.Field(proto.STRING, number=2) - + next_page_token = proto.Field(proto.STRING, number=2,) execution_errors = proto.RepeatedField( - proto.MESSAGE, number=3, message=gr_status.Status, + proto.MESSAGE, number=3, message=status_pb2.Status, ) - - unit = proto.Field(proto.STRING, number=5) + unit = proto.Field(proto.STRING, number=5,) class CreateTimeSeriesRequest(proto.Message): r"""The ``CreateTimeSeries`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -412,8 +380,7 @@ class CreateTimeSeriesRequest(proto.Message): request is 200. """ - name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=3,) time_series = proto.RepeatedField( proto.MESSAGE, number=2, message=gm_metric.TimeSeries, ) @@ -421,7 +388,6 @@ class CreateTimeSeriesRequest(proto.Message): class CreateTimeSeriesError(proto.Message): r"""DEPRECATED. Used to hold per-time-series error status. - Attributes: time_series (google.cloud.monitoring_v3.types.TimeSeries): DEPRECATED. Time series ID that resulted in the ``status`` @@ -432,8 +398,7 @@ class CreateTimeSeriesError(proto.Message): """ time_series = proto.Field(proto.MESSAGE, number=1, message=gm_metric.TimeSeries,) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) class CreateTimeSeriesSummary(proto.Message): @@ -453,7 +418,6 @@ class CreateTimeSeriesSummary(proto.Message): class Error(proto.Message): r"""Detailed information about an error category. - Attributes: status (google.rpc.status_pb2.Status): The status of the requested write operation. @@ -462,20 +426,16 @@ class Error(proto.Message): ``status``. """ - status = proto.Field(proto.MESSAGE, number=1, message=gr_status.Status,) - - point_count = proto.Field(proto.INT32, number=2) - - total_point_count = proto.Field(proto.INT32, number=1) - - success_point_count = proto.Field(proto.INT32, number=2) + status = proto.Field(proto.MESSAGE, number=1, message=status_pb2.Status,) + point_count = proto.Field(proto.INT32, number=2,) + total_point_count = proto.Field(proto.INT32, number=1,) + success_point_count = proto.Field(proto.INT32, number=2,) errors = proto.RepeatedField(proto.MESSAGE, number=3, message=Error,) class QueryTimeSeriesRequest(proto.Message): r"""The ``QueryTimeSeries`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -498,18 +458,14 @@ class QueryTimeSeriesRequest(proto.Message): additional results from the previous method call. """ - name = proto.Field(proto.STRING, number=1) - - query = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=9) - - page_token = proto.Field(proto.STRING, number=10) + name = proto.Field(proto.STRING, number=1,) + query = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=9,) + page_token = proto.Field(proto.STRING, number=10,) class QueryTimeSeriesResponse(proto.Message): r"""The ``QueryTimeSeries`` response. - Attributes: time_series_descriptor (google.cloud.monitoring_v3.types.TimeSeriesDescriptor): The descriptor for the time series data. @@ -534,15 +490,12 @@ def raw_page(self): time_series_descriptor = proto.Field( proto.MESSAGE, number=8, message=gm_metric.TimeSeriesDescriptor, ) - time_series_data = proto.RepeatedField( proto.MESSAGE, number=9, message=gm_metric.TimeSeriesData, ) - - next_page_token = proto.Field(proto.STRING, number=10) - + next_page_token = proto.Field(proto.STRING, number=10,) partial_errors = proto.RepeatedField( - proto.MESSAGE, number=11, message=gr_status.Status, + proto.MESSAGE, number=11, message=status_pb2.Status, ) @@ -560,8 +513,7 @@ class QueryErrorList(proto.Message): """ errors = proto.RepeatedField(proto.MESSAGE, number=1, message=gm_metric.QueryError,) - - error_summary = proto.Field(proto.STRING, number=2) + error_summary = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/mutation_record.py b/google/cloud/monitoring_v3/types/mutation_record.py index 053a2a0c..fbbe735a 100644 --- a/google/cloud/monitoring_v3/types/mutation_record.py +++ b/google/cloud/monitoring_v3/types/mutation_record.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( @@ -28,7 +25,6 @@ class MutationRecord(proto.Message): r"""Describes a change made to a configuration. - Attributes: mutate_time (google.protobuf.timestamp_pb2.Timestamp): When the change occurred. @@ -37,9 +33,8 @@ class MutationRecord(proto.Message): change. """ - mutate_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - mutated_by = proto.Field(proto.STRING, number=2) + mutate_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) + mutated_by = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/notification.py b/google/cloud/monitoring_v3/types/notification.py index 97ee957e..b1da8ada 100644 --- a/google/cloud/monitoring_v3/types/notification.py +++ b/google/cloud/monitoring_v3/types/notification.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.api import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as ga_launch_stage # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record -from google.protobuf import wrappers_pb2 as wrappers # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore __protobuf__ = proto.module( @@ -75,23 +72,17 @@ class NotificationChannelDescriptor(proto.Message): type. """ - name = proto.Field(proto.STRING, number=6) - - type_ = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=6,) + type_ = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) labels = proto.RepeatedField( - proto.MESSAGE, number=4, message=label.LabelDescriptor, + proto.MESSAGE, number=4, message=label_pb2.LabelDescriptor, ) - supported_tiers = proto.RepeatedField( proto.ENUM, number=5, enum=common.ServiceTier, ) - - launch_stage = proto.Field(proto.ENUM, number=7, enum=ga_launch_stage.LaunchStage,) + launch_stage = proto.Field(proto.ENUM, number=7, enum=launch_stage_pb2.LaunchStage,) class NotificationChannel(proto.Message): @@ -201,26 +192,17 @@ class VerificationStatus(proto.Enum): UNVERIFIED = 1 VERIFIED = 2 - type_ = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=6) - - display_name = proto.Field(proto.STRING, number=3) - - description = proto.Field(proto.STRING, number=4) - - labels = proto.MapField(proto.STRING, proto.STRING, number=5) - - user_labels = proto.MapField(proto.STRING, proto.STRING, number=8) - + type_ = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=6,) + display_name = proto.Field(proto.STRING, number=3,) + description = proto.Field(proto.STRING, number=4,) + labels = proto.MapField(proto.STRING, proto.STRING, number=5,) + user_labels = proto.MapField(proto.STRING, proto.STRING, number=8,) verification_status = proto.Field(proto.ENUM, number=9, enum=VerificationStatus,) - - enabled = proto.Field(proto.MESSAGE, number=11, message=wrappers.BoolValue,) - + enabled = proto.Field(proto.MESSAGE, number=11, message=wrappers_pb2.BoolValue,) creation_record = proto.Field( proto.MESSAGE, number=12, message=mutation_record.MutationRecord, ) - mutation_records = proto.RepeatedField( proto.MESSAGE, number=13, message=mutation_record.MutationRecord, ) diff --git a/google/cloud/monitoring_v3/types/notification_service.py b/google/cloud/monitoring_v3/types/notification_service.py index e34ccab0..58886166 100644 --- a/google/cloud/monitoring_v3/types/notification_service.py +++ b/google/cloud/monitoring_v3/types/notification_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.monitoring_v3.types import notification -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 __protobuf__ = proto.module( @@ -45,7 +42,6 @@ class ListNotificationChannelDescriptorsRequest(proto.Message): r"""The ``ListNotificationChannelDescriptors`` request. - Attributes: name (str): Required. The REST resource name of the parent from which to @@ -72,16 +68,13 @@ class ListNotificationChannelDescriptorsRequest(proto.Message): the next set of results. """ - name = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListNotificationChannelDescriptorsResponse(proto.Message): r"""The ``ListNotificationChannelDescriptors`` response. - Attributes: channel_descriptors (Sequence[google.cloud.monitoring_v3.types.NotificationChannelDescriptor]): The monitored resource descriptors supported @@ -100,13 +93,11 @@ def raw_page(self): channel_descriptors = proto.RepeatedField( proto.MESSAGE, number=1, message=notification.NotificationChannelDescriptor, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetNotificationChannelDescriptorRequest(proto.Message): r"""The ``GetNotificationChannelDescriptor`` response. - Attributes: name (str): Required. The channel type for which to execute the request. @@ -117,12 +108,11 @@ class GetNotificationChannelDescriptorRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[CHANNEL_TYPE] """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class CreateNotificationChannelRequest(proto.Message): r"""The ``CreateNotificationChannel`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -143,8 +133,7 @@ class CreateNotificationChannelRequest(proto.Message): create. """ - name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=3,) notification_channel = proto.Field( proto.MESSAGE, number=2, message=notification.NotificationChannel, ) @@ -152,7 +141,6 @@ class CreateNotificationChannelRequest(proto.Message): class ListNotificationChannelsRequest(proto.Message): r"""The ``ListNotificationChannels`` request. - Attributes: name (str): Required. The project on which to execute the request. The @@ -192,20 +180,15 @@ class ListNotificationChannelsRequest(proto.Message): the next set of results. """ - name = proto.Field(proto.STRING, number=5) - - filter = proto.Field(proto.STRING, number=6) - - order_by = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=5,) + filter = proto.Field(proto.STRING, number=6,) + order_by = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListNotificationChannelsResponse(proto.Message): r"""The ``ListNotificationChannels`` response. - Attributes: notification_channels (Sequence[google.cloud.monitoring_v3.types.NotificationChannel]): The notification channels defined for the @@ -229,15 +212,12 @@ def raw_page(self): notification_channels = proto.RepeatedField( proto.MESSAGE, number=3, message=notification.NotificationChannel, ) - - next_page_token = proto.Field(proto.STRING, number=2) - - total_size = proto.Field(proto.INT32, number=4) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=4,) class GetNotificationChannelRequest(proto.Message): r"""The ``GetNotificationChannel`` request. - Attributes: name (str): Required. The channel for which to execute the request. The @@ -248,12 +228,11 @@ class GetNotificationChannelRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] """ - name = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=3,) class UpdateNotificationChannelRequest(proto.Message): r"""The ``UpdateNotificationChannel`` request. - Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): The fields to update. @@ -264,8 +243,9 @@ class UpdateNotificationChannelRequest(proto.Message): fields should also be included in the ``update_mask``. """ - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) notification_channel = proto.Field( proto.MESSAGE, number=3, message=notification.NotificationChannel, ) @@ -273,7 +253,6 @@ class UpdateNotificationChannelRequest(proto.Message): class DeleteNotificationChannelRequest(proto.Message): r"""The ``DeleteNotificationChannel`` request. - Attributes: name (str): Required. The channel for which to execute the request. The @@ -291,26 +270,23 @@ class DeleteNotificationChannelRequest(proto.Message): fail to be deleted in a delete operation. """ - name = proto.Field(proto.STRING, number=3) - - force = proto.Field(proto.BOOL, number=5) + name = proto.Field(proto.STRING, number=3,) + force = proto.Field(proto.BOOL, number=5,) class SendNotificationChannelVerificationCodeRequest(proto.Message): r"""The ``SendNotificationChannelVerificationCode`` request. - Attributes: name (str): Required. The notification channel to which to send a verification code. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetNotificationChannelVerificationCodeRequest(proto.Message): r"""The ``GetNotificationChannelVerificationCode`` request. - Attributes: name (str): Required. The notification channel for which @@ -335,14 +311,12 @@ class GetNotificationChannelVerificationCodeRequest(proto.Message): that is permitted). """ - name = proto.Field(proto.STRING, number=1) - - expire_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + name = proto.Field(proto.STRING, number=1,) + expire_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class GetNotificationChannelVerificationCodeResponse(proto.Message): r"""The ``GetNotificationChannelVerificationCode`` request. - Attributes: code (str): The verification code, which may be used to @@ -359,14 +333,12 @@ class GetNotificationChannelVerificationCodeResponse(proto.Message): permitted expiration. """ - code = proto.Field(proto.STRING, number=1) - - expire_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + code = proto.Field(proto.STRING, number=1,) + expire_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class VerifyNotificationChannelRequest(proto.Message): r"""The ``VerifyNotificationChannel`` request. - Attributes: name (str): Required. The notification channel to verify. @@ -382,9 +354,8 @@ class VerifyNotificationChannelRequest(proto.Message): structure or format of the code). """ - name = proto.Field(proto.STRING, number=1) - - code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + code = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/query_service.py b/google/cloud/monitoring_v3/types/query_service.py index 15c9849d..1fc586e1 100644 --- a/google/cloud/monitoring_v3/types/query_service.py +++ b/google/cloud/monitoring_v3/types/query_service.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/google/cloud/monitoring_v3/types/service.py b/google/cloud/monitoring_v3/types/service.py index 88b892e0..e6c71d51 100644 --- a/google/cloud/monitoring_v3/types/service.py +++ b/google/cloud/monitoring_v3/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,12 +13,10 @@ # 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.type import calendar_period_pb2 as gt_calendar_period # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.type import calendar_period_pb2 # type: ignore __protobuf__ = proto.module( @@ -79,7 +76,7 @@ class Service(proto.Message): class Custom(proto.Message): r"""Custom view of service telemetry. Currently a place-holder pending final design. - """ + """ class AppEngine(proto.Message): r"""App Engine service. Learn more at @@ -93,7 +90,7 @@ class AppEngine(proto.Message): https://cloud.google.com/monitoring/api/resources#tag_gae_app """ - module_id = proto.Field(proto.STRING, number=1) + module_id = proto.Field(proto.STRING, number=1,) class CloudEndpoints(proto.Message): r"""Cloud Endpoints service. Learn more at @@ -107,7 +104,7 @@ class CloudEndpoints(proto.Message): https://cloud.google.com/monitoring/api/resources#tag_api """ - service = proto.Field(proto.STRING, number=1) + service = proto.Field(proto.STRING, number=1,) class ClusterIstio(proto.Message): r"""Istio service scoped to a single Kubernetes cluster. Learn @@ -133,13 +130,10 @@ class ClusterIstio(proto.Message): in Istio metrics. """ - location = proto.Field(proto.STRING, number=1) - - cluster_name = proto.Field(proto.STRING, number=2) - - service_namespace = proto.Field(proto.STRING, number=3) - - service_name = proto.Field(proto.STRING, number=4) + location = proto.Field(proto.STRING, number=1,) + cluster_name = proto.Field(proto.STRING, number=2,) + service_namespace = proto.Field(proto.STRING, number=3,) + service_name = proto.Field(proto.STRING, number=4,) class MeshIstio(proto.Message): r"""Istio service scoped to an Istio mesh. Anthos clusters @@ -161,11 +155,9 @@ class MeshIstio(proto.Message): in Istio metrics. """ - mesh_uid = proto.Field(proto.STRING, number=1) - - service_namespace = proto.Field(proto.STRING, number=3) - - service_name = proto.Field(proto.STRING, number=4) + mesh_uid = proto.Field(proto.STRING, number=1,) + service_namespace = proto.Field(proto.STRING, number=3,) + service_name = proto.Field(proto.STRING, number=4,) class IstioCanonicalService(proto.Message): r"""Canonical service scoped to an Istio mesh. Anthos clusters @@ -191,15 +183,12 @@ class IstioCanonicalService(proto.Message): metrics `__. """ - mesh_uid = proto.Field(proto.STRING, number=1) - - canonical_service_namespace = proto.Field(proto.STRING, number=3) - - canonical_service = proto.Field(proto.STRING, number=4) + mesh_uid = proto.Field(proto.STRING, number=1,) + canonical_service_namespace = proto.Field(proto.STRING, number=3,) + canonical_service = proto.Field(proto.STRING, number=4,) class Telemetry(proto.Message): r"""Configuration for how to query telemetry on a Service. - Attributes: resource_name (str): The full name of the resource that defines this service. @@ -207,34 +196,26 @@ class Telemetry(proto.Message): https://cloud.google.com/apis/design/resource_names. """ - resource_name = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + resource_name = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) custom = proto.Field(proto.MESSAGE, number=6, oneof="identifier", message=Custom,) - app_engine = proto.Field( proto.MESSAGE, number=7, oneof="identifier", message=AppEngine, ) - cloud_endpoints = proto.Field( proto.MESSAGE, number=8, oneof="identifier", message=CloudEndpoints, ) - cluster_istio = proto.Field( proto.MESSAGE, number=9, oneof="identifier", message=ClusterIstio, ) - mesh_istio = proto.Field( proto.MESSAGE, number=10, oneof="identifier", message=MeshIstio, ) - istio_canonical_service = proto.Field( proto.MESSAGE, number=11, oneof="identifier", message=IstioCanonicalService, ) - telemetry = proto.Field(proto.MESSAGE, number=13, message=Telemetry,) @@ -285,22 +266,17 @@ class View(proto.Enum): FULL = 2 EXPLICIT = 1 - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=11) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=11,) service_level_indicator = proto.Field( proto.MESSAGE, number=3, message="ServiceLevelIndicator", ) - - goal = proto.Field(proto.DOUBLE, number=4) - + goal = proto.Field(proto.DOUBLE, number=4,) rolling_period = proto.Field( - proto.MESSAGE, number=5, oneof="period", message=duration.Duration, + proto.MESSAGE, number=5, oneof="period", message=duration_pb2.Duration, ) - calendar_period = proto.Field( - proto.ENUM, number=6, oneof="period", enum=gt_calendar_period.CalendarPeriod, + proto.ENUM, number=6, oneof="period", enum=calendar_period_pb2.CalendarPeriod, ) @@ -331,11 +307,9 @@ class ServiceLevelIndicator(proto.Message): """ basic_sli = proto.Field(proto.MESSAGE, number=4, oneof="type", message="BasicSli",) - request_based = proto.Field( proto.MESSAGE, number=1, oneof="type", message="RequestBasedSli", ) - windows_based = proto.Field( proto.MESSAGE, number=2, oneof="type", message="WindowsBasedSli", ) @@ -386,29 +360,24 @@ class BasicSli(proto.Message): """ class AvailabilityCriteria(proto.Message): - r"""Future parameters for the availability SLI.""" + r"""Future parameters for the availability SLI. """ class LatencyCriteria(proto.Message): r"""Parameters for a latency threshold SLI. - Attributes: threshold (google.protobuf.duration_pb2.Duration): Good service is defined to be the count of requests made to this service that return in no more than ``threshold``. """ - threshold = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,) - - method = proto.RepeatedField(proto.STRING, number=7) - - location = proto.RepeatedField(proto.STRING, number=8) - - version = proto.RepeatedField(proto.STRING, number=9) + threshold = proto.Field(proto.MESSAGE, number=3, message=duration_pb2.Duration,) + method = proto.RepeatedField(proto.STRING, number=7,) + location = proto.RepeatedField(proto.STRING, number=8,) + version = proto.RepeatedField(proto.STRING, number=9,) availability = proto.Field( proto.MESSAGE, number=2, oneof="sli_criteria", message=AvailabilityCriteria, ) - latency = proto.Field( proto.MESSAGE, number=3, oneof="sli_criteria", message=LatencyCriteria, ) @@ -427,9 +396,8 @@ class Range(proto.Message): Range maximum. """ - min_ = proto.Field(proto.DOUBLE, number=1) - - max_ = proto.Field(proto.DOUBLE, number=2) + min_ = proto.Field(proto.DOUBLE, number=1,) + max_ = proto.Field(proto.DOUBLE, number=2,) class RequestBasedSli(proto.Message): @@ -451,7 +419,6 @@ class RequestBasedSli(proto.Message): good_total_ratio = proto.Field( proto.MESSAGE, number=1, oneof="method", message="TimeSeriesRatio", ) - distribution_cut = proto.Field( proto.MESSAGE, number=3, oneof="method", message="DistributionCut", ) @@ -491,11 +458,9 @@ class TimeSeriesRatio(proto.Message): or ``MetricKind = CUMULATIVE``. """ - good_service_filter = proto.Field(proto.STRING, number=4) - - bad_service_filter = proto.Field(proto.STRING, number=5) - - total_service_filter = proto.Field(proto.STRING, number=6) + good_service_filter = proto.Field(proto.STRING, number=4,) + bad_service_filter = proto.Field(proto.STRING, number=5,) + total_service_filter = proto.Field(proto.STRING, number=6,) class DistributionCut(proto.Message): @@ -518,8 +483,7 @@ class DistributionCut(proto.Message): ided range, set one bound to an infinite value. """ - distribution_filter = proto.Field(proto.STRING, number=4) - + distribution_filter = proto.Field(proto.STRING, number=4,) range_ = proto.Field(proto.MESSAGE, number=5, message="Range",) @@ -565,12 +529,10 @@ class PerformanceThreshold(proto.Message): performance = proto.Field( proto.MESSAGE, number=1, oneof="type", message="RequestBasedSli", ) - basic_sli_performance = proto.Field( proto.MESSAGE, number=3, oneof="type", message="BasicSli", ) - - threshold = proto.Field(proto.DOUBLE, number=2) + threshold = proto.Field(proto.DOUBLE, number=2,) class MetricRange(proto.Message): r"""A ``MetricRange`` is used when each window is good when the value x @@ -589,27 +551,22 @@ class MetricRange(proto.Message): ided range, set one bound to an infinite value. """ - time_series = proto.Field(proto.STRING, number=1) - + time_series = proto.Field(proto.STRING, number=1,) range_ = proto.Field(proto.MESSAGE, number=4, message="Range",) good_bad_metric_filter = proto.Field( - proto.STRING, number=5, oneof="window_criterion" + proto.STRING, number=5, oneof="window_criterion", ) - good_total_ratio_threshold = proto.Field( proto.MESSAGE, number=2, oneof="window_criterion", message=PerformanceThreshold, ) - metric_mean_in_range = proto.Field( proto.MESSAGE, number=6, oneof="window_criterion", message=MetricRange, ) - metric_sum_in_range = proto.Field( proto.MESSAGE, number=7, oneof="window_criterion", message=MetricRange, ) - - window_period = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) + window_period = proto.Field(proto.MESSAGE, number=4, message=duration_pb2.Duration,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/service_service.py b/google/cloud/monitoring_v3/types/service_service.py index c747744d..2b7db781 100644 --- a/google/cloud/monitoring_v3/types/service_service.py +++ b/google/cloud/monitoring_v3/types/service_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.monitoring_v3.types import service as gm_service -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -43,7 +40,6 @@ class CreateServiceRequest(proto.Message): r"""The ``CreateService`` request. - Attributes: parent (str): Required. Resource name of the parent workspace. The format @@ -60,16 +56,13 @@ class CreateServiceRequest(proto.Message): Required. The ``Service`` to create. """ - parent = proto.Field(proto.STRING, number=1) - - service_id = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + service_id = proto.Field(proto.STRING, number=3,) service = proto.Field(proto.MESSAGE, number=2, message=gm_service.Service,) class GetServiceRequest(proto.Message): r"""The ``GetService`` request. - Attributes: name (str): Required. Resource name of the ``Service``. The format is: @@ -79,12 +72,11 @@ class GetServiceRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListServicesRequest(proto.Message): r"""The ``ListServices`` request. - Attributes: parent (str): Required. Resource name of the parent containing the listed @@ -130,18 +122,14 @@ class ListServicesRequest(proto.Message): additional results from the previous method call. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListServicesResponse(proto.Message): r"""The ``ListServices`` response. - Attributes: services (Sequence[google.cloud.monitoring_v3.types.Service]): The ``Service``\ s matching the specified filter. @@ -157,13 +145,11 @@ def raw_page(self): return self services = proto.RepeatedField(proto.MESSAGE, number=1, message=gm_service.Service,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateServiceRequest(proto.Message): r"""The ``UpdateService`` request. - Attributes: service (google.cloud.monitoring_v3.types.Service): Required. The ``Service`` to draw updates from. The given @@ -174,13 +160,13 @@ class UpdateServiceRequest(proto.Message): """ service = proto.Field(proto.MESSAGE, number=1, message=gm_service.Service,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteServiceRequest(proto.Message): r"""The ``DeleteService`` request. - Attributes: name (str): Required. Resource name of the ``Service`` to delete. The @@ -191,12 +177,11 @@ class DeleteServiceRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateServiceLevelObjectiveRequest(proto.Message): r"""The ``CreateServiceLevelObjective`` request. - Attributes: parent (str): Required. Resource name of the parent ``Service``. The @@ -215,10 +200,8 @@ class CreateServiceLevelObjectiveRequest(proto.Message): ``ServiceLevelObjective`` exists with this name. """ - parent = proto.Field(proto.STRING, number=1) - - service_level_objective_id = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + service_level_objective_id = proto.Field(proto.STRING, number=3,) service_level_objective = proto.Field( proto.MESSAGE, number=2, message=gm_service.ServiceLevelObjective, ) @@ -226,7 +209,6 @@ class CreateServiceLevelObjectiveRequest(proto.Message): class GetServiceLevelObjectiveRequest(proto.Message): r"""The ``GetServiceLevelObjective`` request. - Attributes: name (str): Required. Resource name of the ``ServiceLevelObjective`` to @@ -244,8 +226,7 @@ class GetServiceLevelObjectiveRequest(proto.Message): ``RequestBasedSli`` spelling out how the SLI is computed. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) view = proto.Field( proto.ENUM, number=2, enum=gm_service.ServiceLevelObjective.View, ) @@ -253,7 +234,6 @@ class GetServiceLevelObjectiveRequest(proto.Message): class ListServiceLevelObjectivesRequest(proto.Message): r"""The ``ListServiceLevelObjectives`` request. - Attributes: parent (str): Required. Resource name of the parent containing the listed @@ -285,14 +265,10 @@ class ListServiceLevelObjectivesRequest(proto.Message): ``RequestBasedSli`` spelling out how the SLI is computed. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) - + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) view = proto.Field( proto.ENUM, number=5, enum=gm_service.ServiceLevelObjective.View, ) @@ -300,7 +276,6 @@ class ListServiceLevelObjectivesRequest(proto.Message): class ListServiceLevelObjectivesResponse(proto.Message): r"""The ``ListServiceLevelObjectives`` response. - Attributes: service_level_objectives (Sequence[google.cloud.monitoring_v3.types.ServiceLevelObjective]): The ``ServiceLevelObjective``\ s matching the specified @@ -319,13 +294,11 @@ def raw_page(self): service_level_objectives = proto.RepeatedField( proto.MESSAGE, number=1, message=gm_service.ServiceLevelObjective, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateServiceLevelObjectiveRequest(proto.Message): r"""The ``UpdateServiceLevelObjective`` request. - Attributes: service_level_objective (google.cloud.monitoring_v3.types.ServiceLevelObjective): Required. The ``ServiceLevelObjective`` to draw updates @@ -338,13 +311,13 @@ class UpdateServiceLevelObjectiveRequest(proto.Message): service_level_objective = proto.Field( proto.MESSAGE, number=1, message=gm_service.ServiceLevelObjective, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteServiceLevelObjectiveRequest(proto.Message): r"""The ``DeleteServiceLevelObjective`` request. - Attributes: name (str): Required. Resource name of the ``ServiceLevelObjective`` to @@ -355,7 +328,7 @@ class DeleteServiceLevelObjectiveRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/span_context.py b/google/cloud/monitoring_v3/types/span_context.py index dc7891b8..5689065b 100644 --- a/google/cloud/monitoring_v3/types/span_context.py +++ b/google/cloud/monitoring_v3/types/span_context.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 @@ -49,7 +47,7 @@ class SpanContext(proto.Message): 8-byte array. """ - span_name = proto.Field(proto.STRING, number=1) + span_name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/uptime.py b/google/cloud/monitoring_v3/types/uptime.py index 9576dff4..9a6fa92b 100644 --- a/google/cloud/monitoring_v3/types/uptime.py +++ b/google/cloud/monitoring_v3/types/uptime.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.api import monitored_resource_pb2 as ga_monitored_resource # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore +from google.api import monitored_resource_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -100,16 +97,11 @@ class State(proto.Enum): CREATING = 1 RUNNING = 2 - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - network = proto.Field(proto.STRING, number=3) - - gcp_zone = proto.Field(proto.STRING, number=4) - - peer_project_id = proto.Field(proto.STRING, number=6) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + network = proto.Field(proto.STRING, number=3,) + gcp_zone = proto.Field(proto.STRING, number=4,) + peer_project_id = proto.Field(proto.STRING, number=6,) state = proto.Field(proto.ENUM, number=7, enum=State,) @@ -206,13 +198,11 @@ class ResourceGroup(proto.Message): The resource type of the group members. """ - group_id = proto.Field(proto.STRING, number=1) - + group_id = proto.Field(proto.STRING, number=1,) resource_type = proto.Field(proto.ENUM, number=2, enum="GroupResourceType",) class HttpCheck(proto.Message): r"""Information involved in an HTTP/HTTPS Uptime check request. - Attributes: request_method (google.cloud.monitoring_v3.types.UptimeCheckConfig.HttpCheck.RequestMethod): The HTTP request method to use for the check. If set to @@ -315,41 +305,30 @@ class BasicAuthentication(proto.Message): the HTTP server. """ - username = proto.Field(proto.STRING, number=1) - - password = proto.Field(proto.STRING, number=2) + username = proto.Field(proto.STRING, number=1,) + password = proto.Field(proto.STRING, number=2,) request_method = proto.Field( proto.ENUM, number=8, enum="UptimeCheckConfig.HttpCheck.RequestMethod", ) - - use_ssl = proto.Field(proto.BOOL, number=1) - - path = proto.Field(proto.STRING, number=2) - - port = proto.Field(proto.INT32, number=3) - + use_ssl = proto.Field(proto.BOOL, number=1,) + path = proto.Field(proto.STRING, number=2,) + port = proto.Field(proto.INT32, number=3,) auth_info = proto.Field( proto.MESSAGE, number=4, message="UptimeCheckConfig.HttpCheck.BasicAuthentication", ) - - mask_headers = proto.Field(proto.BOOL, number=5) - - headers = proto.MapField(proto.STRING, proto.STRING, number=6) - + mask_headers = proto.Field(proto.BOOL, number=5,) + headers = proto.MapField(proto.STRING, proto.STRING, number=6,) content_type = proto.Field( proto.ENUM, number=9, enum="UptimeCheckConfig.HttpCheck.ContentType", ) - - validate_ssl = proto.Field(proto.BOOL, number=7) - - body = proto.Field(proto.BYTES, number=10) + validate_ssl = proto.Field(proto.BOOL, number=7,) + body = proto.Field(proto.BYTES, number=10,) class TcpCheck(proto.Message): r"""Information required for a TCP Uptime check request. - Attributes: port (int): The TCP port on the server against which to run the check. @@ -357,7 +336,7 @@ class TcpCheck(proto.Message): ``monitored_resource``) to construct the full URL. Required. """ - port = proto.Field(proto.INT32, number=1) + port = proto.Field(proto.INT32, number=1,) class ContentMatcher(proto.Message): r"""Optional. Used to perform content matching. This allows @@ -385,51 +364,39 @@ class ContentMatcherOption(proto.Enum): MATCHES_REGEX = 3 NOT_MATCHES_REGEX = 4 - content = proto.Field(proto.STRING, number=1) - + content = proto.Field(proto.STRING, number=1,) matcher = proto.Field( proto.ENUM, number=2, enum="UptimeCheckConfig.ContentMatcher.ContentMatcherOption", ) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) monitored_resource = proto.Field( proto.MESSAGE, number=3, oneof="resource", - message=ga_monitored_resource.MonitoredResource, + message=monitored_resource_pb2.MonitoredResource, ) - resource_group = proto.Field( proto.MESSAGE, number=4, oneof="resource", message=ResourceGroup, ) - http_check = proto.Field( proto.MESSAGE, number=5, oneof="check_request_type", message=HttpCheck, ) - tcp_check = proto.Field( proto.MESSAGE, number=6, oneof="check_request_type", message=TcpCheck, ) - - period = proto.Field(proto.MESSAGE, number=7, message=duration.Duration,) - - timeout = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) - + period = proto.Field(proto.MESSAGE, number=7, message=duration_pb2.Duration,) + timeout = proto.Field(proto.MESSAGE, number=8, message=duration_pb2.Duration,) content_matchers = proto.RepeatedField( proto.MESSAGE, number=9, message=ContentMatcher, ) - selected_regions = proto.RepeatedField( proto.ENUM, number=10, enum="UptimeCheckRegion", ) - - is_internal = proto.Field(proto.BOOL, number=15) - + is_internal = proto.Field(proto.BOOL, number=15,) internal_checkers = proto.RepeatedField( proto.MESSAGE, number=14, message="InternalChecker", ) @@ -461,10 +428,8 @@ class UptimeCheckIp(proto.Message): """ region = proto.Field(proto.ENUM, number=1, enum="UptimeCheckRegion",) - - location = proto.Field(proto.STRING, number=2) - - ip_address = proto.Field(proto.STRING, number=3) + location = proto.Field(proto.STRING, number=2,) + ip_address = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/monitoring_v3/types/uptime_service.py b/google/cloud/monitoring_v3/types/uptime_service.py index c5b53b1d..b7780564 100644 --- a/google/cloud/monitoring_v3/types/uptime_service.py +++ b/google/cloud/monitoring_v3/types/uptime_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.monitoring_v3.types import uptime -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -39,7 +36,6 @@ class ListUptimeCheckConfigsRequest(proto.Message): r"""The protocol for the ``ListUptimeCheckConfigs`` request. - Attributes: parent (str): Required. The project whose Uptime check configurations are @@ -61,16 +57,13 @@ class ListUptimeCheckConfigsRequest(proto.Message): results from the previous method call. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListUptimeCheckConfigsResponse(proto.Message): r"""The protocol for the ``ListUptimeCheckConfigs`` response. - Attributes: uptime_check_configs (Sequence[google.cloud.monitoring_v3.types.UptimeCheckConfig]): The returned Uptime check configurations. @@ -94,15 +87,12 @@ def raw_page(self): uptime_check_configs = proto.RepeatedField( proto.MESSAGE, number=1, message=uptime.UptimeCheckConfig, ) - - next_page_token = proto.Field(proto.STRING, number=2) - - total_size = proto.Field(proto.INT32, number=3) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=3,) class GetUptimeCheckConfigRequest(proto.Message): r"""The protocol for the ``GetUptimeCheckConfig`` request. - Attributes: name (str): Required. The Uptime check configuration to retrieve. The @@ -113,12 +103,11 @@ class GetUptimeCheckConfigRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateUptimeCheckConfigRequest(proto.Message): r"""The protocol for the ``CreateUptimeCheckConfig`` request. - Attributes: parent (str): Required. The project in which to create the Uptime check. @@ -131,8 +120,7 @@ class CreateUptimeCheckConfigRequest(proto.Message): Required. The new Uptime check configuration. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) uptime_check_config = proto.Field( proto.MESSAGE, number=2, message=uptime.UptimeCheckConfig, ) @@ -140,7 +128,6 @@ class CreateUptimeCheckConfigRequest(proto.Message): class UpdateUptimeCheckConfigRequest(proto.Message): r"""The protocol for the ``UpdateUptimeCheckConfig`` request. - Attributes: update_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. If present, only the listed fields @@ -164,8 +151,9 @@ class UpdateUptimeCheckConfigRequest(proto.Message): ``content_matchers``, and ``selected_regions``. """ - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) uptime_check_config = proto.Field( proto.MESSAGE, number=3, message=uptime.UptimeCheckConfig, ) @@ -173,7 +161,6 @@ class UpdateUptimeCheckConfigRequest(proto.Message): class DeleteUptimeCheckConfigRequest(proto.Message): r"""The protocol for the ``DeleteUptimeCheckConfig`` request. - Attributes: name (str): Required. The Uptime check configuration to delete. The @@ -184,12 +171,11 @@ class DeleteUptimeCheckConfigRequest(proto.Message): projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListUptimeCheckIpsRequest(proto.Message): r"""The protocol for the ``ListUptimeCheckIps`` request. - Attributes: page_size (int): The maximum number of results to return in a single @@ -206,14 +192,12 @@ class ListUptimeCheckIpsRequest(proto.Message): not yet implemented """ - 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 ListUptimeCheckIpsResponse(proto.Message): r"""The protocol for the ``ListUptimeCheckIps`` response. - Attributes: uptime_check_ips (Sequence[google.cloud.monitoring_v3.types.UptimeCheckIp]): The returned list of IP addresses (including @@ -234,8 +218,7 @@ def raw_page(self): uptime_check_ips = proto.RepeatedField( proto.MESSAGE, number=1, message=uptime.UptimeCheckIp, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owlbot.py b/owlbot.py index 82b20b43..84031cc1 100644 --- a/owlbot.py +++ b/owlbot.py @@ -33,8 +33,8 @@ for pattern in [ "monitored_resource_types=\['monitored_resource_types_value'\],", "assert response.monitored_resource_types == \['monitored_resource_types_value'\]", - "launch_stage=launch_stage.LaunchStage.UNIMPLEMENTED,", - "assert response.launch_stage == launch_stage.LaunchStage.UNIMPLEMENTED", + "launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED,", + "assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED", ]: s.replace(library / "tests/unit/gapic/monitoring_v3/test_*.py", pattern, diff --git a/scripts/fixup_monitoring_v3_keywords.py b/scripts/fixup_monitoring_v3_keywords.py index 3ed5bc4a..e2608d8a 100644 --- a/scripts/fixup_monitoring_v3_keywords.py +++ b/scripts/fixup_monitoring_v3_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,53 +39,52 @@ def partition( class monitoringCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_alert_policy': ('name', 'alert_policy', ), - 'create_group': ('name', 'group', 'validate_only', ), - 'create_metric_descriptor': ('name', 'metric_descriptor', ), - 'create_notification_channel': ('name', 'notification_channel', ), - 'create_service': ('parent', 'service', 'service_id', ), - 'create_service_level_objective': ('parent', 'service_level_objective', 'service_level_objective_id', ), - 'create_time_series': ('name', 'time_series', ), - 'create_uptime_check_config': ('parent', 'uptime_check_config', ), - 'delete_alert_policy': ('name', ), - 'delete_group': ('name', 'recursive', ), - 'delete_metric_descriptor': ('name', ), - 'delete_notification_channel': ('name', 'force', ), - 'delete_service': ('name', ), - 'delete_service_level_objective': ('name', ), - 'delete_uptime_check_config': ('name', ), - 'get_alert_policy': ('name', ), - 'get_group': ('name', ), - 'get_metric_descriptor': ('name', ), - 'get_monitored_resource_descriptor': ('name', ), - 'get_notification_channel': ('name', ), - 'get_notification_channel_descriptor': ('name', ), - 'get_notification_channel_verification_code': ('name', 'expire_time', ), - 'get_service': ('name', ), - 'get_service_level_objective': ('name', 'view', ), - 'get_uptime_check_config': ('name', ), - 'list_alert_policies': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), - 'list_group_members': ('name', 'page_size', 'page_token', 'filter', 'interval', ), - 'list_groups': ('name', 'children_of_group', 'ancestors_of_group', 'descendants_of_group', 'page_size', 'page_token', ), - 'list_metric_descriptors': ('name', 'filter', 'page_size', 'page_token', ), - 'list_monitored_resource_descriptors': ('name', 'filter', 'page_size', 'page_token', ), - 'list_notification_channel_descriptors': ('name', 'page_size', 'page_token', ), - 'list_notification_channels': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), - 'list_service_level_objectives': ('parent', 'filter', 'page_size', 'page_token', 'view', ), - 'list_services': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_time_series': ('name', 'filter', 'interval', 'view', 'aggregation', 'secondary_aggregation', 'order_by', 'page_size', 'page_token', ), - 'list_uptime_check_configs': ('parent', 'page_size', 'page_token', ), - 'list_uptime_check_ips': ('page_size', 'page_token', ), - 'query_time_series': ('name', 'query', 'page_size', 'page_token', ), - 'send_notification_channel_verification_code': ('name', ), - 'update_alert_policy': ('alert_policy', 'update_mask', ), - 'update_group': ('group', 'validate_only', ), - 'update_notification_channel': ('notification_channel', 'update_mask', ), - 'update_service': ('service', 'update_mask', ), - 'update_service_level_objective': ('service_level_objective', 'update_mask', ), - 'update_uptime_check_config': ('uptime_check_config', 'update_mask', ), - 'verify_notification_channel': ('name', 'code', ), - + 'create_alert_policy': ('name', 'alert_policy', ), + 'create_group': ('name', 'group', 'validate_only', ), + 'create_metric_descriptor': ('name', 'metric_descriptor', ), + 'create_notification_channel': ('name', 'notification_channel', ), + 'create_service': ('parent', 'service', 'service_id', ), + 'create_service_level_objective': ('parent', 'service_level_objective', 'service_level_objective_id', ), + 'create_time_series': ('name', 'time_series', ), + 'create_uptime_check_config': ('parent', 'uptime_check_config', ), + 'delete_alert_policy': ('name', ), + 'delete_group': ('name', 'recursive', ), + 'delete_metric_descriptor': ('name', ), + 'delete_notification_channel': ('name', 'force', ), + 'delete_service': ('name', ), + 'delete_service_level_objective': ('name', ), + 'delete_uptime_check_config': ('name', ), + 'get_alert_policy': ('name', ), + 'get_group': ('name', ), + 'get_metric_descriptor': ('name', ), + 'get_monitored_resource_descriptor': ('name', ), + 'get_notification_channel': ('name', ), + 'get_notification_channel_descriptor': ('name', ), + 'get_notification_channel_verification_code': ('name', 'expire_time', ), + 'get_service': ('name', ), + 'get_service_level_objective': ('name', 'view', ), + 'get_uptime_check_config': ('name', ), + 'list_alert_policies': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), + 'list_group_members': ('name', 'page_size', 'page_token', 'filter', 'interval', ), + 'list_groups': ('name', 'children_of_group', 'ancestors_of_group', 'descendants_of_group', 'page_size', 'page_token', ), + 'list_metric_descriptors': ('name', 'filter', 'page_size', 'page_token', ), + 'list_monitored_resource_descriptors': ('name', 'filter', 'page_size', 'page_token', ), + 'list_notification_channel_descriptors': ('name', 'page_size', 'page_token', ), + 'list_notification_channels': ('name', 'filter', 'order_by', 'page_size', 'page_token', ), + 'list_service_level_objectives': ('parent', 'filter', 'page_size', 'page_token', 'view', ), + 'list_services': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_time_series': ('name', 'filter', 'interval', 'view', 'aggregation', 'secondary_aggregation', 'order_by', 'page_size', 'page_token', ), + 'list_uptime_check_configs': ('parent', 'page_size', 'page_token', ), + 'list_uptime_check_ips': ('page_size', 'page_token', ), + 'query_time_series': ('name', 'query', 'page_size', 'page_token', ), + 'send_notification_channel_verification_code': ('name', ), + 'update_alert_policy': ('alert_policy', 'update_mask', ), + 'update_group': ('group', 'validate_only', ), + 'update_notification_channel': ('notification_channel', 'update_mask', ), + 'update_service': ('service', 'update_mask', ), + 'update_service_level_objective': ('service_level_objective', 'update_mask', ), + 'update_uptime_check_config': ('uptime_check_config', 'update_mask', ), + 'verify_notification_channel': ('name', 'code', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -118,7 +115,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/setup.py b/setup.py index ee96d185..5fa74050 100644 --- a/setup.py +++ b/setup.py @@ -31,6 +31,7 @@ dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.15.0", + "packaging >= 14.3", ] extras = {"pandas": "pandas >= 0.17.1"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 4421999f..0500442f 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -8,3 +8,5 @@ google-api-core==1.22.2 proto-plus==1.15.0 pandas==0.23.0 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is required through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/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/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/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/tests/unit/gapic/monitoring_v3/__init__.py b/tests/unit/gapic/monitoring_v3/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/monitoring_v3/__init__.py +++ b/tests/unit/gapic/monitoring_v3/__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/tests/unit/gapic/monitoring_v3/test_alert_policy_service.py b/tests/unit/gapic/monitoring_v3/test_alert_policy_service.py index 6a273388..c0454c19 100644 --- a/tests/unit/gapic/monitoring_v3/test_alert_policy_service.py +++ b/tests/unit/gapic/monitoring_v3/test_alert_policy_service.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.monitoring_v3.services.alert_policy_service import ( AlertPolicyServiceAsyncClient, @@ -40,17 +39,47 @@ ) from google.cloud.monitoring_v3.services.alert_policy_service import pagers from google.cloud.monitoring_v3.services.alert_policy_service import transports +from google.cloud.monitoring_v3.services.alert_policy_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.alert_policy_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import alert from google.cloud.monitoring_v3.types import alert_service from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -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 wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # 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 +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_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(): @@ -102,7 +131,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AlertPolicyServiceClient, AlertPolicyServiceAsyncClient,] ) def test_alert_policy_service_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: @@ -119,7 +148,7 @@ def test_alert_policy_service_client_from_service_account_info(client_class): "client_class", [AlertPolicyServiceClient, AlertPolicyServiceAsyncClient,] ) def test_alert_policy_service_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: @@ -172,7 +201,7 @@ def test_alert_policy_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AlertPolicyServiceClient, "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() @@ -470,7 +499,7 @@ def test_list_alert_policies( transport: str = "grpc", request_type=alert_service.ListAlertPoliciesRequest ): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,21 +514,16 @@ def test_list_alert_policies( call.return_value = alert_service.ListAlertPoliciesResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_alert_policies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.ListAlertPoliciesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAlertPoliciesPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -511,7 +535,7 @@ def test_list_alert_policies_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 = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -521,7 +545,6 @@ def test_list_alert_policies_empty_call(): client.list_alert_policies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.ListAlertPoliciesRequest() @@ -530,7 +553,7 @@ async def test_list_alert_policies_async( transport: str = "grpc_asyncio", request_type=alert_service.ListAlertPoliciesRequest ): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -547,20 +570,16 @@ async def test_list_alert_policies_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_alert_policies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.ListAlertPoliciesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAlertPoliciesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -570,11 +589,14 @@ async def test_list_alert_policies_async_from_dict(): def test_list_alert_policies_field_headers(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + 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 = alert_service.ListAlertPoliciesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -582,7 +604,6 @@ def test_list_alert_policies_field_headers(): type(client.transport.list_alert_policies), "__call__" ) as call: call.return_value = alert_service.ListAlertPoliciesResponse() - client.list_alert_policies(request) # Establish that the underlying gRPC stub method was called. @@ -598,12 +619,13 @@ def test_list_alert_policies_field_headers(): @pytest.mark.asyncio async def test_list_alert_policies_field_headers_async(): client = AlertPolicyServiceAsyncClient( - 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 = alert_service.ListAlertPoliciesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -613,7 +635,6 @@ async def test_list_alert_policies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( alert_service.ListAlertPoliciesResponse() ) - await client.list_alert_policies(request) # Establish that the underlying gRPC stub method was called. @@ -627,7 +648,9 @@ async def test_list_alert_policies_field_headers_async(): def test_list_alert_policies_flattened(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -635,7 +658,6 @@ def test_list_alert_policies_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = alert_service.ListAlertPoliciesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_alert_policies(name="name_value",) @@ -644,12 +666,13 @@ def test_list_alert_policies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_alert_policies_flattened_error(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -662,7 +685,7 @@ def test_list_alert_policies_flattened_error(): @pytest.mark.asyncio async def test_list_alert_policies_flattened_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -683,14 +706,13 @@ async def test_list_alert_policies_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_alert_policies_flattened_error_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -702,7 +724,7 @@ async def test_list_alert_policies_flattened_error_async(): def test_list_alert_policies_pager(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials,) + client = AlertPolicyServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +766,7 @@ def test_list_alert_policies_pager(): def test_list_alert_policies_pages(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials,) + client = AlertPolicyServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -779,7 +801,7 @@ def test_list_alert_policies_pages(): @pytest.mark.asyncio async def test_list_alert_policies_async_pager(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -822,7 +844,7 @@ async def test_list_alert_policies_async_pager(): @pytest.mark.asyncio async def test_list_alert_policies_async_pages(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -863,7 +885,7 @@ def test_get_alert_policy( transport: str = "grpc", request_type=alert_service.GetAlertPolicyRequest ): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -879,25 +901,18 @@ def test_get_alert_policy( combiner=alert.AlertPolicy.ConditionCombinerType.AND, notification_channels=["notification_channels_value"], ) - response = client.get_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.GetAlertPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -909,7 +924,7 @@ def test_get_alert_policy_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 = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -917,7 +932,6 @@ def test_get_alert_policy_empty_call(): client.get_alert_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.GetAlertPolicyRequest() @@ -926,7 +940,7 @@ async def test_get_alert_policy_async( transport: str = "grpc_asyncio", request_type=alert_service.GetAlertPolicyRequest ): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -944,24 +958,18 @@ async def test_get_alert_policy_async( notification_channels=["notification_channels_value"], ) ) - response = await client.get_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.GetAlertPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -971,17 +979,19 @@ async def test_get_alert_policy_async_from_dict(): def test_get_alert_policy_field_headers(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + 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 = alert_service.GetAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_alert_policy), "__call__") as call: call.return_value = alert.AlertPolicy() - client.get_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -997,18 +1007,18 @@ def test_get_alert_policy_field_headers(): @pytest.mark.asyncio async def test_get_alert_policy_field_headers_async(): client = AlertPolicyServiceAsyncClient( - 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 = alert_service.GetAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_alert_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(alert.AlertPolicy()) - await client.get_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1022,13 +1032,14 @@ async def test_get_alert_policy_field_headers_async(): def test_get_alert_policy_flattened(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_alert_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = alert.AlertPolicy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_alert_policy(name="name_value",) @@ -1037,12 +1048,13 @@ def test_get_alert_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_alert_policy_flattened_error(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1055,7 +1067,7 @@ def test_get_alert_policy_flattened_error(): @pytest.mark.asyncio async def test_get_alert_policy_flattened_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1072,14 +1084,13 @@ async def test_get_alert_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_alert_policy_flattened_error_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1094,7 +1105,7 @@ def test_create_alert_policy( transport: str = "grpc", request_type=alert_service.CreateAlertPolicyRequest ): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1112,25 +1123,18 @@ def test_create_alert_policy( combiner=alert.AlertPolicy.ConditionCombinerType.AND, notification_channels=["notification_channels_value"], ) - response = client.create_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.CreateAlertPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -1142,7 +1146,7 @@ def test_create_alert_policy_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 = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1152,7 +1156,6 @@ def test_create_alert_policy_empty_call(): client.create_alert_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.CreateAlertPolicyRequest() @@ -1161,7 +1164,7 @@ async def test_create_alert_policy_async( transport: str = "grpc_asyncio", request_type=alert_service.CreateAlertPolicyRequest ): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1181,24 +1184,18 @@ async def test_create_alert_policy_async( notification_channels=["notification_channels_value"], ) ) - response = await client.create_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.CreateAlertPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -1208,11 +1205,14 @@ async def test_create_alert_policy_async_from_dict(): def test_create_alert_policy_field_headers(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + 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 = alert_service.CreateAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1220,6 @@ def test_create_alert_policy_field_headers(): type(client.transport.create_alert_policy), "__call__" ) as call: call.return_value = alert.AlertPolicy() - client.create_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1236,12 +1235,13 @@ def test_create_alert_policy_field_headers(): @pytest.mark.asyncio async def test_create_alert_policy_field_headers_async(): client = AlertPolicyServiceAsyncClient( - 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 = alert_service.CreateAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1249,7 +1249,6 @@ async def test_create_alert_policy_field_headers_async(): type(client.transport.create_alert_policy), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(alert.AlertPolicy()) - await client.create_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1263,7 +1262,9 @@ async def test_create_alert_policy_field_headers_async(): def test_create_alert_policy_flattened(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1271,7 +1272,6 @@ def test_create_alert_policy_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = alert.AlertPolicy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_alert_policy( @@ -1282,14 +1282,14 @@ def test_create_alert_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].alert_policy == alert.AlertPolicy(name="name_value") def test_create_alert_policy_flattened_error(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1304,7 +1304,7 @@ def test_create_alert_policy_flattened_error(): @pytest.mark.asyncio async def test_create_alert_policy_flattened_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1325,16 +1325,14 @@ async def test_create_alert_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].alert_policy == alert.AlertPolicy(name="name_value") @pytest.mark.asyncio async def test_create_alert_policy_flattened_error_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1351,7 +1349,7 @@ def test_delete_alert_policy( transport: str = "grpc", request_type=alert_service.DeleteAlertPolicyRequest ): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1364,13 +1362,11 @@ def test_delete_alert_policy( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.DeleteAlertPolicyRequest() # Establish that the response is the type that we expect. @@ -1385,7 +1381,7 @@ def test_delete_alert_policy_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 = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1395,7 +1391,6 @@ def test_delete_alert_policy_empty_call(): client.delete_alert_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.DeleteAlertPolicyRequest() @@ -1404,7 +1399,7 @@ async def test_delete_alert_policy_async( transport: str = "grpc_asyncio", request_type=alert_service.DeleteAlertPolicyRequest ): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1417,13 +1412,11 @@ async def test_delete_alert_policy_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.DeleteAlertPolicyRequest() # Establish that the response is the type that we expect. @@ -1436,11 +1429,14 @@ async def test_delete_alert_policy_async_from_dict(): def test_delete_alert_policy_field_headers(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + 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 = alert_service.DeleteAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1448,7 +1444,6 @@ def test_delete_alert_policy_field_headers(): type(client.transport.delete_alert_policy), "__call__" ) as call: call.return_value = None - client.delete_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1464,12 +1459,13 @@ def test_delete_alert_policy_field_headers(): @pytest.mark.asyncio async def test_delete_alert_policy_field_headers_async(): client = AlertPolicyServiceAsyncClient( - 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 = alert_service.DeleteAlertPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1477,7 +1473,6 @@ async def test_delete_alert_policy_field_headers_async(): type(client.transport.delete_alert_policy), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1491,7 +1486,9 @@ async def test_delete_alert_policy_field_headers_async(): def test_delete_alert_policy_flattened(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1499,7 +1496,6 @@ def test_delete_alert_policy_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_alert_policy(name="name_value",) @@ -1508,12 +1504,13 @@ def test_delete_alert_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_alert_policy_flattened_error(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1526,7 +1523,7 @@ def test_delete_alert_policy_flattened_error(): @pytest.mark.asyncio async def test_delete_alert_policy_flattened_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1545,14 +1542,13 @@ async def test_delete_alert_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_alert_policy_flattened_error_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1567,7 +1563,7 @@ def test_update_alert_policy( transport: str = "grpc", request_type=alert_service.UpdateAlertPolicyRequest ): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1585,25 +1581,18 @@ def test_update_alert_policy( combiner=alert.AlertPolicy.ConditionCombinerType.AND, notification_channels=["notification_channels_value"], ) - response = client.update_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.UpdateAlertPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -1615,7 +1604,7 @@ def test_update_alert_policy_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 = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1625,7 +1614,6 @@ def test_update_alert_policy_empty_call(): client.update_alert_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.UpdateAlertPolicyRequest() @@ -1634,7 +1622,7 @@ async def test_update_alert_policy_async( transport: str = "grpc_asyncio", request_type=alert_service.UpdateAlertPolicyRequest ): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1654,24 +1642,18 @@ async def test_update_alert_policy_async( notification_channels=["notification_channels_value"], ) ) - response = await client.update_alert_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == alert_service.UpdateAlertPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, alert.AlertPolicy) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.combiner == alert.AlertPolicy.ConditionCombinerType.AND - assert response.notification_channels == ["notification_channels_value"] @@ -1681,11 +1663,14 @@ async def test_update_alert_policy_async_from_dict(): def test_update_alert_policy_field_headers(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + 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 = alert_service.UpdateAlertPolicyRequest() + request.alert_policy.name = "alert_policy.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1678,6 @@ def test_update_alert_policy_field_headers(): type(client.transport.update_alert_policy), "__call__" ) as call: call.return_value = alert.AlertPolicy() - client.update_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1712,12 +1696,13 @@ def test_update_alert_policy_field_headers(): @pytest.mark.asyncio async def test_update_alert_policy_field_headers_async(): client = AlertPolicyServiceAsyncClient( - 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 = alert_service.UpdateAlertPolicyRequest() + request.alert_policy.name = "alert_policy.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1725,7 +1710,6 @@ async def test_update_alert_policy_field_headers_async(): type(client.transport.update_alert_policy), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(alert.AlertPolicy()) - await client.update_alert_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1742,7 +1726,9 @@ async def test_update_alert_policy_field_headers_async(): def test_update_alert_policy_flattened(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1750,11 +1736,10 @@ def test_update_alert_policy_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = alert.AlertPolicy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_alert_policy( - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), alert_policy=alert.AlertPolicy(name="name_value"), ) @@ -1762,21 +1747,21 @@ def test_update_alert_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].alert_policy == alert.AlertPolicy(name="name_value") def test_update_alert_policy_flattened_error(): - client = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.update_alert_policy( alert_service.UpdateAlertPolicyRequest(), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), alert_policy=alert.AlertPolicy(name="name_value"), ) @@ -1784,7 +1769,7 @@ def test_update_alert_policy_flattened_error(): @pytest.mark.asyncio async def test_update_alert_policy_flattened_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1798,7 +1783,7 @@ async def test_update_alert_policy_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_alert_policy( - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), alert_policy=alert.AlertPolicy(name="name_value"), ) @@ -1806,16 +1791,14 @@ async def test_update_alert_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].alert_policy == alert.AlertPolicy(name="name_value") @pytest.mark.asyncio async def test_update_alert_policy_flattened_error_async(): client = AlertPolicyServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1823,7 +1806,7 @@ async def test_update_alert_policy_flattened_error_async(): with pytest.raises(ValueError): await client.update_alert_policy( alert_service.UpdateAlertPolicyRequest(), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), alert_policy=alert.AlertPolicy(name="name_value"), ) @@ -1831,16 +1814,16 @@ async def test_update_alert_policy_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AlertPolicyServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AlertPolicyServiceClient( - 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.AlertPolicyServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AlertPolicyServiceClient( @@ -1850,7 +1833,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AlertPolicyServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AlertPolicyServiceClient( @@ -1861,7 +1844,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AlertPolicyServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AlertPolicyServiceClient(transport=transport) assert client.transport is transport @@ -1870,13 +1853,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AlertPolicyServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AlertPolicyServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1891,23 +1874,25 @@ 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 = AlertPolicyServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AlertPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.AlertPolicyServiceGrpcTransport,) def test_alert_policy_service_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.AlertPolicyServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1919,7 +1904,7 @@ def test_alert_policy_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AlertPolicyServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1936,15 +1921,41 @@ def test_alert_policy_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_alert_policy_service_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.monitoring_v3.services.alert_policy_service.transports.AlertPolicyServiceTransport._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.AlertPolicyServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_alert_policy_service_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.monitoring_v3.services.alert_policy_service.transports.AlertPolicyServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AlertPolicyServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1961,19 +1972,37 @@ def test_alert_policy_service_base_transport_with_credentials_file(): def test_alert_policy_service_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.monitoring_v3.services.alert_policy_service.transports.AlertPolicyServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AlertPolicyServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_alert_policy_service_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) + AlertPolicyServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_alert_policy_service_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) AlertPolicyServiceClient() adc.assert_called_once_with( scopes=( @@ -1985,14 +2014,45 @@ def test_alert_policy_service_auth_adc(): ) -def test_alert_policy_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AlertPolicyServiceGrpcTransport, + transports.AlertPolicyServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_alert_policy_service_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.AlertPolicyServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AlertPolicyServiceGrpcTransport, + transports.AlertPolicyServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_alert_policy_service_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/cloud-platform", @@ -2003,6 +2063,123 @@ def test_alert_policy_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AlertPolicyServiceGrpcTransport, grpc_helpers), + (transports.AlertPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_alert_policy_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.AlertPolicyServiceGrpcTransport, grpc_helpers), + (transports.AlertPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_alert_policy_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AlertPolicyServiceGrpcTransport, grpc_helpers), + (transports.AlertPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_alert_policy_service_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( + "monitoring.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", [ @@ -2013,7 +2190,7 @@ def test_alert_policy_service_transport_auth_adc(): def test_alert_policy_service_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: @@ -2056,7 +2233,7 @@ def test_alert_policy_service_grpc_transport_client_cert_source_for_mtls( def test_alert_policy_service_host_no_port(): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -2066,7 +2243,7 @@ def test_alert_policy_service_host_no_port(): def test_alert_policy_service_host_with_port(): client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -2122,9 +2299,9 @@ def test_alert_policy_service_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", @@ -2209,7 +2386,6 @@ def test_alert_policy_service_transport_channel_mtls_with_adc(transport_class): def test_alert_policy_path(): project = "squid" alert_policy = "clam" - expected = "projects/{project}/alertPolicies/{alert_policy}".format( project=project, alert_policy=alert_policy, ) @@ -2233,7 +2409,6 @@ def test_alert_policy_condition_path(): project = "oyster" alert_policy = "nudibranch" condition = "cuttlefish" - expected = "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}".format( project=project, alert_policy=alert_policy, condition=condition, ) @@ -2258,7 +2433,6 @@ def test_parse_alert_policy_condition_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2279,7 +2453,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = AlertPolicyServiceClient.common_folder_path(folder) assert expected == actual @@ -2298,7 +2471,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = AlertPolicyServiceClient.common_organization_path(organization) assert expected == actual @@ -2317,7 +2489,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = AlertPolicyServiceClient.common_project_path(project) assert expected == actual @@ -2337,7 +2508,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2364,7 +2534,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AlertPolicyServiceTransport, "_prep_wrapped_messages" ) as prep: client = AlertPolicyServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2373,6 +2543,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AlertPolicyServiceClient.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/tests/unit/gapic/monitoring_v3/test_group_service.py b/tests/unit/gapic/monitoring_v3/test_group_service.py index b4025200..02e010ad 100644 --- a/tests/unit/gapic/monitoring_v3/test_group_service.py +++ b/tests/unit/gapic/monitoring_v3/test_group_service.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,25 +23,55 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore + +from google.api import monitored_resource_pb2 # type: ignore 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.monitoring_v3.services.group_service import GroupServiceAsyncClient from google.cloud.monitoring_v3.services.group_service import GroupServiceClient from google.cloud.monitoring_v3.services.group_service import pagers from google.cloud.monitoring_v3.services.group_service import transports +from google.cloud.monitoring_v3.services.group_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.group_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import group from google.cloud.monitoring_v3.types import group as gm_group from google.cloud.monitoring_v3.types import group_service 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", [GroupServiceClient, GroupServiceAsyncClient,]) def test_group_service_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_group_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [GroupServiceClient, GroupServiceAsyncClient,]) def test_group_service_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: @@ -154,7 +183,7 @@ def test_group_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(GroupServiceClient, "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() @@ -438,7 +467,7 @@ def test_list_groups( transport: str = "grpc", request_type=group_service.ListGroupsRequest ): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -451,19 +480,15 @@ def test_list_groups( call.return_value = group_service.ListGroupsResponse( next_page_token="next_page_token_value", ) - response = client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGroupsPager) - assert response.next_page_token == "next_page_token_value" @@ -475,7 +500,7 @@ def test_list_groups_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -483,7 +508,6 @@ def test_list_groups_empty_call(): client.list_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupsRequest() @@ -492,7 +516,7 @@ async def test_list_groups_async( transport: str = "grpc_asyncio", request_type=group_service.ListGroupsRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -505,18 +529,15 @@ async def test_list_groups_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( group_service.ListGroupsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGroupsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -526,17 +547,17 @@ async def test_list_groups_async_from_dict(): def test_list_groups_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.ListGroupsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_groups), "__call__") as call: call.return_value = group_service.ListGroupsResponse() - client.list_groups(request) # Establish that the underlying gRPC stub method was called. @@ -551,11 +572,12 @@ def test_list_groups_field_headers(): @pytest.mark.asyncio async def test_list_groups_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.ListGroupsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -563,7 +585,6 @@ async def test_list_groups_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( group_service.ListGroupsResponse() ) - await client.list_groups(request) # Establish that the underlying gRPC stub method was called. @@ -577,13 +598,12 @@ async def test_list_groups_field_headers_async(): def test_list_groups_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_groups), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = group_service.ListGroupsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_groups(name="name_value",) @@ -592,12 +612,11 @@ def test_list_groups_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_groups_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -609,7 +628,7 @@ def test_list_groups_flattened_error(): @pytest.mark.asyncio async def test_list_groups_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_groups), "__call__") as call: @@ -627,13 +646,12 @@ async def test_list_groups_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_groups_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -644,7 +662,7 @@ async def test_list_groups_flattened_error_async(): def test_list_groups_pager(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_groups), "__call__") as call: @@ -676,7 +694,7 @@ def test_list_groups_pager(): def test_list_groups_pages(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_groups), "__call__") as call: @@ -700,7 +718,7 @@ def test_list_groups_pages(): @pytest.mark.asyncio async def test_list_groups_async_pager(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -731,7 +749,7 @@ async def test_list_groups_async_pager(): @pytest.mark.asyncio async def test_list_groups_async_pages(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -759,7 +777,7 @@ async def test_list_groups_async_pages(): def test_get_group(transport: str = "grpc", request_type=group_service.GetGroupRequest): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -776,27 +794,19 @@ def test_get_group(transport: str = "grpc", request_type=group_service.GetGroupR filter="filter_value", is_cluster=True, ) - response = client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.GetGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -808,7 +818,7 @@ def test_get_group_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -816,7 +826,6 @@ def test_get_group_empty_call(): client.get_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.GetGroupRequest() @@ -825,7 +834,7 @@ async def test_get_group_async( transport: str = "grpc_asyncio", request_type=group_service.GetGroupRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -844,26 +853,19 @@ async def test_get_group_async( is_cluster=True, ) ) - response = await client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.GetGroupRequest() # Establish that the response is the type that we expect. assert isinstance(response, group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -873,17 +875,17 @@ async def test_get_group_async_from_dict(): def test_get_group_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.GetGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_group), "__call__") as call: call.return_value = group.Group() - client.get_group(request) # Establish that the underlying gRPC stub method was called. @@ -898,17 +900,17 @@ def test_get_group_field_headers(): @pytest.mark.asyncio async def test_get_group_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.GetGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_group), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(group.Group()) - await client.get_group(request) # Establish that the underlying gRPC stub method was called. @@ -922,13 +924,12 @@ async def test_get_group_field_headers_async(): def test_get_group_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = group.Group() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_group(name="name_value",) @@ -937,12 +938,11 @@ def test_get_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_group_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -954,7 +954,7 @@ def test_get_group_flattened_error(): @pytest.mark.asyncio async def test_get_group_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_group), "__call__") as call: @@ -970,13 +970,12 @@ async def test_get_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_group_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -990,7 +989,7 @@ def test_create_group( transport: str = "grpc", request_type=group_service.CreateGroupRequest ): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1007,27 +1006,19 @@ def test_create_group( filter="filter_value", is_cluster=True, ) - response = client.create_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.CreateGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gm_group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -1039,7 +1030,7 @@ def test_create_group_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1047,7 +1038,6 @@ def test_create_group_empty_call(): client.create_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.CreateGroupRequest() @@ -1056,7 +1046,7 @@ async def test_create_group_async( transport: str = "grpc_asyncio", request_type=group_service.CreateGroupRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1075,26 +1065,19 @@ async def test_create_group_async( is_cluster=True, ) ) - response = await client.create_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.CreateGroupRequest() # Establish that the response is the type that we expect. assert isinstance(response, gm_group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -1104,17 +1087,17 @@ async def test_create_group_async_from_dict(): def test_create_group_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.CreateGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_group), "__call__") as call: call.return_value = gm_group.Group() - client.create_group(request) # Establish that the underlying gRPC stub method was called. @@ -1129,17 +1112,17 @@ def test_create_group_field_headers(): @pytest.mark.asyncio async def test_create_group_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.CreateGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_group), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_group.Group()) - await client.create_group(request) # Establish that the underlying gRPC stub method was called. @@ -1153,13 +1136,12 @@ async def test_create_group_field_headers_async(): def test_create_group_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gm_group.Group() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_group( @@ -1170,14 +1152,12 @@ def test_create_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].group == gm_group.Group(name="name_value") def test_create_group_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1191,7 +1171,7 @@ def test_create_group_flattened_error(): @pytest.mark.asyncio async def test_create_group_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_group), "__call__") as call: @@ -1209,15 +1189,13 @@ async def test_create_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].group == gm_group.Group(name="name_value") @pytest.mark.asyncio async def test_create_group_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1233,7 +1211,7 @@ def test_update_group( transport: str = "grpc", request_type=group_service.UpdateGroupRequest ): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1250,27 +1228,19 @@ def test_update_group( filter="filter_value", is_cluster=True, ) - response = client.update_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.UpdateGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gm_group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -1282,7 +1252,7 @@ def test_update_group_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1290,7 +1260,6 @@ def test_update_group_empty_call(): client.update_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.UpdateGroupRequest() @@ -1299,7 +1268,7 @@ async def test_update_group_async( transport: str = "grpc_asyncio", request_type=group_service.UpdateGroupRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1318,26 +1287,19 @@ async def test_update_group_async( is_cluster=True, ) ) - response = await client.update_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.UpdateGroupRequest() # Establish that the response is the type that we expect. assert isinstance(response, gm_group.Group) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.parent_name == "parent_name_value" - assert response.filter == "filter_value" - assert response.is_cluster is True @@ -1347,17 +1309,17 @@ async def test_update_group_async_from_dict(): def test_update_group_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.UpdateGroupRequest() + request.group.name = "group.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_group), "__call__") as call: call.return_value = gm_group.Group() - client.update_group(request) # Establish that the underlying gRPC stub method was called. @@ -1372,17 +1334,17 @@ def test_update_group_field_headers(): @pytest.mark.asyncio async def test_update_group_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.UpdateGroupRequest() + request.group.name = "group.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_group), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_group.Group()) - await client.update_group(request) # Establish that the underlying gRPC stub method was called. @@ -1396,13 +1358,12 @@ async def test_update_group_field_headers_async(): def test_update_group_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gm_group.Group() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_group(group=gm_group.Group(name="name_value"),) @@ -1411,12 +1372,11 @@ def test_update_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].group == gm_group.Group(name="name_value") def test_update_group_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1428,7 +1388,7 @@ def test_update_group_flattened_error(): @pytest.mark.asyncio async def test_update_group_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_group), "__call__") as call: @@ -1444,13 +1404,12 @@ async def test_update_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].group == gm_group.Group(name="name_value") @pytest.mark.asyncio async def test_update_group_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1464,7 +1423,7 @@ def test_delete_group( transport: str = "grpc", request_type=group_service.DeleteGroupRequest ): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1475,13 +1434,11 @@ def test_delete_group( with mock.patch.object(type(client.transport.delete_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.DeleteGroupRequest() # Establish that the response is the type that we expect. @@ -1496,7 +1453,7 @@ def test_delete_group_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1504,7 +1461,6 @@ def test_delete_group_empty_call(): client.delete_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.DeleteGroupRequest() @@ -1513,7 +1469,7 @@ async def test_delete_group_async( transport: str = "grpc_asyncio", request_type=group_service.DeleteGroupRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1524,13 +1480,11 @@ async def test_delete_group_async( with mock.patch.object(type(client.transport.delete_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.DeleteGroupRequest() # Establish that the response is the type that we expect. @@ -1543,17 +1497,17 @@ async def test_delete_group_async_from_dict(): def test_delete_group_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.DeleteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_group), "__call__") as call: call.return_value = None - client.delete_group(request) # Establish that the underlying gRPC stub method was called. @@ -1568,17 +1522,17 @@ def test_delete_group_field_headers(): @pytest.mark.asyncio async def test_delete_group_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.DeleteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_group), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_group(request) # Establish that the underlying gRPC stub method was called. @@ -1592,13 +1546,12 @@ async def test_delete_group_field_headers_async(): def test_delete_group_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_group(name="name_value",) @@ -1607,12 +1560,11 @@ def test_delete_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_group_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1624,7 +1576,7 @@ def test_delete_group_flattened_error(): @pytest.mark.asyncio async def test_delete_group_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_group), "__call__") as call: @@ -1640,13 +1592,12 @@ async def test_delete_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_group_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1660,7 +1611,7 @@ def test_list_group_members( transport: str = "grpc", request_type=group_service.ListGroupMembersRequest ): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1675,21 +1626,16 @@ def test_list_group_members( call.return_value = group_service.ListGroupMembersResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_group_members(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupMembersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGroupMembersPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -1701,7 +1647,7 @@ def test_list_group_members_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 = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1711,7 +1657,6 @@ def test_list_group_members_empty_call(): client.list_group_members() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupMembersRequest() @@ -1720,7 +1665,7 @@ async def test_list_group_members_async( transport: str = "grpc_asyncio", request_type=group_service.ListGroupMembersRequest ): client = GroupServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1737,20 +1682,16 @@ async def test_list_group_members_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_group_members(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == group_service.ListGroupMembersRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGroupMembersAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -1760,11 +1701,12 @@ async def test_list_group_members_async_from_dict(): def test_list_group_members_field_headers(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(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 = group_service.ListGroupMembersRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1772,7 +1714,6 @@ def test_list_group_members_field_headers(): type(client.transport.list_group_members), "__call__" ) as call: call.return_value = group_service.ListGroupMembersResponse() - client.list_group_members(request) # Establish that the underlying gRPC stub method was called. @@ -1787,11 +1728,12 @@ def test_list_group_members_field_headers(): @pytest.mark.asyncio async def test_list_group_members_field_headers_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(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 = group_service.ListGroupMembersRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1801,7 +1743,6 @@ async def test_list_group_members_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( group_service.ListGroupMembersResponse() ) - await client.list_group_members(request) # Establish that the underlying gRPC stub method was called. @@ -1815,7 +1756,7 @@ async def test_list_group_members_field_headers_async(): def test_list_group_members_flattened(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1823,7 +1764,6 @@ def test_list_group_members_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = group_service.ListGroupMembersResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_group_members(name="name_value",) @@ -1832,12 +1772,11 @@ def test_list_group_members_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_group_members_flattened_error(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1849,7 +1788,7 @@ def test_list_group_members_flattened_error(): @pytest.mark.asyncio async def test_list_group_members_flattened_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1869,13 +1808,12 @@ async def test_list_group_members_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_group_members_flattened_error_async(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1886,7 +1824,7 @@ async def test_list_group_members_flattened_error_async(): def test_list_group_members_pager(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1896,21 +1834,21 @@ def test_list_group_members_pager(): call.side_effect = ( group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], next_page_token="abc", ), group_service.ListGroupMembersResponse(members=[], next_page_token="def",), group_service.ListGroupMembersResponse( - members=[monitored_resource.MonitoredResource(),], + members=[monitored_resource_pb2.MonitoredResource(),], next_page_token="ghi", ), group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], ), RuntimeError, @@ -1926,11 +1864,13 @@ def test_list_group_members_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, monitored_resource.MonitoredResource) for i in results) + assert all( + isinstance(i, monitored_resource_pb2.MonitoredResource) for i in results + ) def test_list_group_members_pages(): - client = GroupServiceClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1940,21 +1880,21 @@ def test_list_group_members_pages(): call.side_effect = ( group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], next_page_token="abc", ), group_service.ListGroupMembersResponse(members=[], next_page_token="def",), group_service.ListGroupMembersResponse( - members=[monitored_resource.MonitoredResource(),], + members=[monitored_resource_pb2.MonitoredResource(),], next_page_token="ghi", ), group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], ), RuntimeError, @@ -1966,7 +1906,7 @@ def test_list_group_members_pages(): @pytest.mark.asyncio async def test_list_group_members_async_pager(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1978,21 +1918,21 @@ async def test_list_group_members_async_pager(): call.side_effect = ( group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], next_page_token="abc", ), group_service.ListGroupMembersResponse(members=[], next_page_token="def",), group_service.ListGroupMembersResponse( - members=[monitored_resource.MonitoredResource(),], + members=[monitored_resource_pb2.MonitoredResource(),], next_page_token="ghi", ), group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], ), RuntimeError, @@ -2005,13 +1945,13 @@ async def test_list_group_members_async_pager(): assert len(responses) == 6 assert all( - isinstance(i, monitored_resource.MonitoredResource) for i in responses + isinstance(i, monitored_resource_pb2.MonitoredResource) for i in responses ) @pytest.mark.asyncio async def test_list_group_members_async_pages(): - client = GroupServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = GroupServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2023,21 +1963,21 @@ async def test_list_group_members_async_pages(): call.side_effect = ( group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], next_page_token="abc", ), group_service.ListGroupMembersResponse(members=[], next_page_token="def",), group_service.ListGroupMembersResponse( - members=[monitored_resource.MonitoredResource(),], + members=[monitored_resource_pb2.MonitoredResource(),], next_page_token="ghi", ), group_service.ListGroupMembersResponse( members=[ - monitored_resource.MonitoredResource(), - monitored_resource.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), + monitored_resource_pb2.MonitoredResource(), ], ), RuntimeError, @@ -2052,16 +1992,16 @@ async def test_list_group_members_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.GroupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GroupServiceClient( - 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.GroupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GroupServiceClient( @@ -2071,7 +2011,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.GroupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = GroupServiceClient( @@ -2082,7 +2022,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.GroupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = GroupServiceClient(transport=transport) assert client.transport is transport @@ -2091,13 +2031,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.GroupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.GroupServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2112,23 +2052,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 = GroupServiceClient(credentials=credentials.AnonymousCredentials(),) + client = GroupServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.GroupServiceGrpcTransport,) def test_group_service_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.GroupServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2140,7 +2080,7 @@ def test_group_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.GroupServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2158,15 +2098,41 @@ def test_group_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_group_service_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.monitoring_v3.services.group_service.transports.GroupServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GroupServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_group_service_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.monitoring_v3.services.group_service.transports.GroupServiceTransport._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.GroupServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2183,19 +2149,37 @@ def test_group_service_base_transport_with_credentials_file(): def test_group_service_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.monitoring_v3.services.group_service.transports.GroupServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GroupServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_group_service_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) + GroupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_group_service_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) GroupServiceClient() adc.assert_called_once_with( scopes=( @@ -2207,14 +2191,45 @@ def test_group_service_auth_adc(): ) -def test_group_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.GroupServiceGrpcTransport, + transports.GroupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_group_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.GroupServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GroupServiceGrpcTransport, + transports.GroupServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_group_service_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/cloud-platform", @@ -2225,12 +2240,129 @@ def test_group_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.GroupServiceGrpcTransport, grpc_helpers), + (transports.GroupServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_group_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.GroupServiceGrpcTransport, grpc_helpers), + (transports.GroupServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_group_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.GroupServiceGrpcTransport, grpc_helpers), + (transports.GroupServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_group_service_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( + "monitoring.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.GroupServiceGrpcTransport, transports.GroupServiceGrpcAsyncIOTransport], ) def test_group_service_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: @@ -2273,7 +2405,7 @@ def test_group_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_group_service_host_no_port(): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -2283,7 +2415,7 @@ def test_group_service_host_no_port(): def test_group_service_host_with_port(): client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -2334,9 +2466,9 @@ def test_group_service_transport_channel_mtls_with_client_cert_source(transport_ 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", @@ -2418,7 +2550,6 @@ def test_group_service_transport_channel_mtls_with_adc(transport_class): def test_group_path(): project = "squid" group = "clam" - expected = "projects/{project}/groups/{group}".format(project=project, group=group,) actual = GroupServiceClient.group_path(project, group) assert expected == actual @@ -2438,7 +2569,6 @@ def test_parse_group_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2459,7 +2589,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = GroupServiceClient.common_folder_path(folder) assert expected == actual @@ -2478,7 +2607,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = GroupServiceClient.common_organization_path(organization) assert expected == actual @@ -2497,7 +2625,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = GroupServiceClient.common_project_path(project) assert expected == actual @@ -2517,7 +2644,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2544,7 +2670,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.GroupServiceTransport, "_prep_wrapped_messages" ) as prep: client = GroupServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2553,6 +2679,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = GroupServiceClient.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/tests/unit/gapic/monitoring_v3/test_metric_service.py b/tests/unit/gapic/monitoring_v3/test_metric_service.py index 4ed4f946..0a97404b 100644 --- a/tests/unit/gapic/monitoring_v3/test_metric_service.py +++ b/tests/unit/gapic/monitoring_v3/test_metric_service.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,31 +23,61 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth -from google.api import distribution_pb2 as distribution # type: ignore -from google.api import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore -from google.api import metric_pb2 as ga_metric # type: ignore -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore + +from google.api import distribution_pb2 # type: ignore +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore +from google.api import metric_pb2 # type: ignore +from google.api import monitored_resource_pb2 # type: ignore 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.monitoring_v3.services.metric_service import MetricServiceAsyncClient from google.cloud.monitoring_v3.services.metric_service import MetricServiceClient from google.cloud.monitoring_v3.services.metric_service import pagers from google.cloud.monitoring_v3.services.metric_service import transports +from google.cloud.monitoring_v3.services.metric_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.metric_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import metric as gm_metric from google.cloud.monitoring_v3.types import metric_service from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_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(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [MetricServiceClient, MetricServiceAsyncClient,] ) def test_metric_service_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_metric_service_client_from_service_account_info(client_class): "client_class", [MetricServiceClient, MetricServiceAsyncClient,] ) def test_metric_service_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_metric_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(MetricServiceClient, "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() @@ -458,7 +487,7 @@ def test_list_monitored_resource_descriptors( request_type=metric_service.ListMonitoredResourceDescriptorsRequest, ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -473,19 +502,15 @@ def test_list_monitored_resource_descriptors( call.return_value = metric_service.ListMonitoredResourceDescriptorsResponse( next_page_token="next_page_token_value", ) - response = client.list_monitored_resource_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMonitoredResourceDescriptorsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMonitoredResourceDescriptorsPager) - assert response.next_page_token == "next_page_token_value" @@ -497,7 +522,7 @@ def test_list_monitored_resource_descriptors_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -507,7 +532,6 @@ def test_list_monitored_resource_descriptors_empty_call(): client.list_monitored_resource_descriptors() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMonitoredResourceDescriptorsRequest() @@ -517,7 +541,7 @@ async def test_list_monitored_resource_descriptors_async( request_type=metric_service.ListMonitoredResourceDescriptorsRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -534,18 +558,15 @@ async def test_list_monitored_resource_descriptors_async( next_page_token="next_page_token_value", ) ) - response = await client.list_monitored_resource_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMonitoredResourceDescriptorsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMonitoredResourceDescriptorsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -555,11 +576,12 @@ async def test_list_monitored_resource_descriptors_async_from_dict(): def test_list_monitored_resource_descriptors_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.ListMonitoredResourceDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -567,7 +589,6 @@ def test_list_monitored_resource_descriptors_field_headers(): type(client.transport.list_monitored_resource_descriptors), "__call__" ) as call: call.return_value = metric_service.ListMonitoredResourceDescriptorsResponse() - client.list_monitored_resource_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -582,11 +603,14 @@ def test_list_monitored_resource_descriptors_field_headers(): @pytest.mark.asyncio async def test_list_monitored_resource_descriptors_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.ListMonitoredResourceDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -596,7 +620,6 @@ async def test_list_monitored_resource_descriptors_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( metric_service.ListMonitoredResourceDescriptorsResponse() ) - await client.list_monitored_resource_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -610,7 +633,7 @@ async def test_list_monitored_resource_descriptors_field_headers_async(): def test_list_monitored_resource_descriptors_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -618,7 +641,6 @@ def test_list_monitored_resource_descriptors_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = metric_service.ListMonitoredResourceDescriptorsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_monitored_resource_descriptors(name="name_value",) @@ -627,12 +649,11 @@ def test_list_monitored_resource_descriptors_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_monitored_resource_descriptors_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -644,7 +665,9 @@ def test_list_monitored_resource_descriptors_flattened_error(): @pytest.mark.asyncio async def test_list_monitored_resource_descriptors_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -664,13 +687,14 @@ async def test_list_monitored_resource_descriptors_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_monitored_resource_descriptors_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -681,7 +705,7 @@ async def test_list_monitored_resource_descriptors_flattened_error_async(): def test_list_monitored_resource_descriptors_pager(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -691,9 +715,9 @@ def test_list_monitored_resource_descriptors_pager(): call.side_effect = ( metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="abc", ), @@ -702,14 +726,14 @@ def test_list_monitored_resource_descriptors_pager(): ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="ghi", ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], ), RuntimeError, @@ -726,13 +750,13 @@ def test_list_monitored_resource_descriptors_pager(): results = [i for i in pager] assert len(results) == 6 assert all( - isinstance(i, monitored_resource.MonitoredResourceDescriptor) + isinstance(i, monitored_resource_pb2.MonitoredResourceDescriptor) for i in results ) def test_list_monitored_resource_descriptors_pages(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -742,9 +766,9 @@ def test_list_monitored_resource_descriptors_pages(): call.side_effect = ( metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="abc", ), @@ -753,14 +777,14 @@ def test_list_monitored_resource_descriptors_pages(): ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="ghi", ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], ), RuntimeError, @@ -772,7 +796,7 @@ def test_list_monitored_resource_descriptors_pages(): @pytest.mark.asyncio async def test_list_monitored_resource_descriptors_async_pager(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -784,9 +808,9 @@ async def test_list_monitored_resource_descriptors_async_pager(): call.side_effect = ( metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="abc", ), @@ -795,14 +819,14 @@ async def test_list_monitored_resource_descriptors_async_pager(): ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="ghi", ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], ), RuntimeError, @@ -815,14 +839,14 @@ async def test_list_monitored_resource_descriptors_async_pager(): assert len(responses) == 6 assert all( - isinstance(i, monitored_resource.MonitoredResourceDescriptor) + isinstance(i, monitored_resource_pb2.MonitoredResourceDescriptor) for i in responses ) @pytest.mark.asyncio async def test_list_monitored_resource_descriptors_async_pages(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -834,9 +858,9 @@ async def test_list_monitored_resource_descriptors_async_pages(): call.side_effect = ( metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="abc", ), @@ -845,14 +869,14 @@ async def test_list_monitored_resource_descriptors_async_pages(): ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], next_page_token="ghi", ), metric_service.ListMonitoredResourceDescriptorsResponse( resource_descriptors=[ - monitored_resource.MonitoredResourceDescriptor(), - monitored_resource.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), + monitored_resource_pb2.MonitoredResourceDescriptor(), ], ), RuntimeError, @@ -871,7 +895,7 @@ def test_get_monitored_resource_descriptor( request_type=metric_service.GetMonitoredResourceDescriptorRequest, ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -883,31 +907,24 @@ def test_get_monitored_resource_descriptor( type(client.transport.get_monitored_resource_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = monitored_resource.MonitoredResourceDescriptor( + call.return_value = monitored_resource_pb2.MonitoredResourceDescriptor( name="name_value", type="type_value", display_name="display_name_value", description="description_value", ) - response = client.get_monitored_resource_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMonitoredResourceDescriptorRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, monitored_resource.MonitoredResourceDescriptor) - + assert isinstance(response, monitored_resource_pb2.MonitoredResourceDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -919,7 +936,7 @@ def test_get_monitored_resource_descriptor_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -929,7 +946,6 @@ def test_get_monitored_resource_descriptor_empty_call(): client.get_monitored_resource_descriptor() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMonitoredResourceDescriptorRequest() @@ -939,7 +955,7 @@ async def test_get_monitored_resource_descriptor_async( request_type=metric_service.GetMonitoredResourceDescriptorRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -952,31 +968,25 @@ async def test_get_monitored_resource_descriptor_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - monitored_resource.MonitoredResourceDescriptor( + monitored_resource_pb2.MonitoredResourceDescriptor( name="name_value", type="type_value", display_name="display_name_value", description="description_value", ) ) - response = await client.get_monitored_resource_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMonitoredResourceDescriptorRequest() # Establish that the response is the type that we expect. - assert isinstance(response, monitored_resource.MonitoredResourceDescriptor) - + assert isinstance(response, monitored_resource_pb2.MonitoredResourceDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -986,19 +996,19 @@ async def test_get_monitored_resource_descriptor_async_from_dict(): def test_get_monitored_resource_descriptor_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.GetMonitoredResourceDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_monitored_resource_descriptor), "__call__" ) as call: - call.return_value = monitored_resource.MonitoredResourceDescriptor() - + call.return_value = monitored_resource_pb2.MonitoredResourceDescriptor() client.get_monitored_resource_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1013,11 +1023,14 @@ def test_get_monitored_resource_descriptor_field_headers(): @pytest.mark.asyncio async def test_get_monitored_resource_descriptor_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.GetMonitoredResourceDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1025,9 +1038,8 @@ async def test_get_monitored_resource_descriptor_field_headers_async(): type(client.transport.get_monitored_resource_descriptor), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - monitored_resource.MonitoredResourceDescriptor() + monitored_resource_pb2.MonitoredResourceDescriptor() ) - await client.get_monitored_resource_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1041,15 +1053,14 @@ async def test_get_monitored_resource_descriptor_field_headers_async(): def test_get_monitored_resource_descriptor_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_monitored_resource_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = monitored_resource.MonitoredResourceDescriptor() - + call.return_value = monitored_resource_pb2.MonitoredResourceDescriptor() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_monitored_resource_descriptor(name="name_value",) @@ -1058,12 +1069,11 @@ def test_get_monitored_resource_descriptor_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_monitored_resource_descriptor_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1075,17 +1085,19 @@ def test_get_monitored_resource_descriptor_flattened_error(): @pytest.mark.asyncio async def test_get_monitored_resource_descriptor_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_monitored_resource_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = monitored_resource.MonitoredResourceDescriptor() + call.return_value = monitored_resource_pb2.MonitoredResourceDescriptor() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - monitored_resource.MonitoredResourceDescriptor() + monitored_resource_pb2.MonitoredResourceDescriptor() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -1095,13 +1107,14 @@ async def test_get_monitored_resource_descriptor_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_monitored_resource_descriptor_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1115,7 +1128,7 @@ def test_list_metric_descriptors( transport: str = "grpc", request_type=metric_service.ListMetricDescriptorsRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1130,19 +1143,15 @@ def test_list_metric_descriptors( call.return_value = metric_service.ListMetricDescriptorsResponse( next_page_token="next_page_token_value", ) - response = client.list_metric_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMetricDescriptorsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMetricDescriptorsPager) - assert response.next_page_token == "next_page_token_value" @@ -1154,7 +1163,7 @@ def test_list_metric_descriptors_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1164,7 +1173,6 @@ def test_list_metric_descriptors_empty_call(): client.list_metric_descriptors() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMetricDescriptorsRequest() @@ -1174,7 +1182,7 @@ async def test_list_metric_descriptors_async( request_type=metric_service.ListMetricDescriptorsRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1191,18 +1199,15 @@ async def test_list_metric_descriptors_async( next_page_token="next_page_token_value", ) ) - response = await client.list_metric_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListMetricDescriptorsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMetricDescriptorsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1212,11 +1217,12 @@ async def test_list_metric_descriptors_async_from_dict(): def test_list_metric_descriptors_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.ListMetricDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1224,7 +1230,6 @@ def test_list_metric_descriptors_field_headers(): type(client.transport.list_metric_descriptors), "__call__" ) as call: call.return_value = metric_service.ListMetricDescriptorsResponse() - client.list_metric_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -1239,11 +1244,14 @@ def test_list_metric_descriptors_field_headers(): @pytest.mark.asyncio async def test_list_metric_descriptors_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.ListMetricDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1253,7 +1261,6 @@ async def test_list_metric_descriptors_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( metric_service.ListMetricDescriptorsResponse() ) - await client.list_metric_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -1267,7 +1274,7 @@ async def test_list_metric_descriptors_field_headers_async(): def test_list_metric_descriptors_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1275,7 +1282,6 @@ def test_list_metric_descriptors_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = metric_service.ListMetricDescriptorsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_metric_descriptors(name="name_value",) @@ -1284,12 +1290,11 @@ def test_list_metric_descriptors_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_metric_descriptors_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1301,7 +1306,9 @@ def test_list_metric_descriptors_flattened_error(): @pytest.mark.asyncio async def test_list_metric_descriptors_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1321,13 +1328,14 @@ async def test_list_metric_descriptors_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_metric_descriptors_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1338,7 +1346,7 @@ async def test_list_metric_descriptors_flattened_error_async(): def test_list_metric_descriptors_pager(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1348,9 +1356,9 @@ def test_list_metric_descriptors_pager(): call.side_effect = ( metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], next_page_token="abc", ), @@ -1358,13 +1366,13 @@ def test_list_metric_descriptors_pager(): metric_descriptors=[], next_page_token="def", ), metric_service.ListMetricDescriptorsResponse( - metric_descriptors=[ga_metric.MetricDescriptor(),], + metric_descriptors=[metric_pb2.MetricDescriptor(),], next_page_token="ghi", ), metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], ), RuntimeError, @@ -1380,11 +1388,11 @@ def test_list_metric_descriptors_pager(): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, ga_metric.MetricDescriptor) for i in results) + assert all(isinstance(i, metric_pb2.MetricDescriptor) for i in results) def test_list_metric_descriptors_pages(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1394,9 +1402,9 @@ def test_list_metric_descriptors_pages(): call.side_effect = ( metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], next_page_token="abc", ), @@ -1404,13 +1412,13 @@ def test_list_metric_descriptors_pages(): metric_descriptors=[], next_page_token="def", ), metric_service.ListMetricDescriptorsResponse( - metric_descriptors=[ga_metric.MetricDescriptor(),], + metric_descriptors=[metric_pb2.MetricDescriptor(),], next_page_token="ghi", ), metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], ), RuntimeError, @@ -1422,7 +1430,7 @@ def test_list_metric_descriptors_pages(): @pytest.mark.asyncio async def test_list_metric_descriptors_async_pager(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1434,9 +1442,9 @@ async def test_list_metric_descriptors_async_pager(): call.side_effect = ( metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], next_page_token="abc", ), @@ -1444,13 +1452,13 @@ async def test_list_metric_descriptors_async_pager(): metric_descriptors=[], next_page_token="def", ), metric_service.ListMetricDescriptorsResponse( - metric_descriptors=[ga_metric.MetricDescriptor(),], + metric_descriptors=[metric_pb2.MetricDescriptor(),], next_page_token="ghi", ), metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], ), RuntimeError, @@ -1462,12 +1470,12 @@ async def test_list_metric_descriptors_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, ga_metric.MetricDescriptor) for i in responses) + assert all(isinstance(i, metric_pb2.MetricDescriptor) for i in responses) @pytest.mark.asyncio async def test_list_metric_descriptors_async_pages(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1479,9 +1487,9 @@ async def test_list_metric_descriptors_async_pages(): call.side_effect = ( metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], next_page_token="abc", ), @@ -1489,13 +1497,13 @@ async def test_list_metric_descriptors_async_pages(): metric_descriptors=[], next_page_token="def", ), metric_service.ListMetricDescriptorsResponse( - metric_descriptors=[ga_metric.MetricDescriptor(),], + metric_descriptors=[metric_pb2.MetricDescriptor(),], next_page_token="ghi", ), metric_service.ListMetricDescriptorsResponse( metric_descriptors=[ - ga_metric.MetricDescriptor(), - ga_metric.MetricDescriptor(), + metric_pb2.MetricDescriptor(), + metric_pb2.MetricDescriptor(), ], ), RuntimeError, @@ -1511,7 +1519,7 @@ def test_get_metric_descriptor( transport: str = "grpc", request_type=metric_service.GetMetricDescriptorRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1523,40 +1531,30 @@ def test_get_metric_descriptor( type(client.transport.get_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor( + call.return_value = metric_pb2.MetricDescriptor( name="name_value", type="type_value", - metric_kind=ga_metric.MetricDescriptor.MetricKind.GAUGE, - value_type=ga_metric.MetricDescriptor.ValueType.BOOL, + metric_kind=metric_pb2.MetricDescriptor.MetricKind.GAUGE, + value_type=metric_pb2.MetricDescriptor.ValueType.BOOL, unit="unit_value", description="description_value", display_name="display_name_value", ) - response = client.get_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMetricDescriptorRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, ga_metric.MetricDescriptor) - + assert isinstance(response, metric_pb2.MetricDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - - assert response.metric_kind == ga_metric.MetricDescriptor.MetricKind.GAUGE - - assert response.value_type == ga_metric.MetricDescriptor.ValueType.BOOL - + assert response.metric_kind == metric_pb2.MetricDescriptor.MetricKind.GAUGE + assert response.value_type == metric_pb2.MetricDescriptor.ValueType.BOOL assert response.unit == "unit_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" @@ -1568,7 +1566,7 @@ def test_get_metric_descriptor_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1578,7 +1576,6 @@ def test_get_metric_descriptor_empty_call(): client.get_metric_descriptor() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMetricDescriptorRequest() @@ -1588,7 +1585,7 @@ async def test_get_metric_descriptor_async( request_type=metric_service.GetMetricDescriptorRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1601,40 +1598,31 @@ async def test_get_metric_descriptor_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor( + metric_pb2.MetricDescriptor( name="name_value", type="type_value", - metric_kind=ga_metric.MetricDescriptor.MetricKind.GAUGE, - value_type=ga_metric.MetricDescriptor.ValueType.BOOL, + metric_kind=metric_pb2.MetricDescriptor.MetricKind.GAUGE, + value_type=metric_pb2.MetricDescriptor.ValueType.BOOL, unit="unit_value", description="description_value", display_name="display_name_value", ) ) - response = await client.get_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.GetMetricDescriptorRequest() # Establish that the response is the type that we expect. - assert isinstance(response, ga_metric.MetricDescriptor) - + assert isinstance(response, metric_pb2.MetricDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - - assert response.metric_kind == ga_metric.MetricDescriptor.MetricKind.GAUGE - - assert response.value_type == ga_metric.MetricDescriptor.ValueType.BOOL - + assert response.metric_kind == metric_pb2.MetricDescriptor.MetricKind.GAUGE + assert response.value_type == metric_pb2.MetricDescriptor.ValueType.BOOL assert response.unit == "unit_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" @@ -1644,19 +1632,19 @@ async def test_get_metric_descriptor_async_from_dict(): def test_get_metric_descriptor_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.GetMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_metric_descriptor), "__call__" ) as call: - call.return_value = ga_metric.MetricDescriptor() - + call.return_value = metric_pb2.MetricDescriptor() client.get_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1671,11 +1659,14 @@ def test_get_metric_descriptor_field_headers(): @pytest.mark.asyncio async def test_get_metric_descriptor_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.GetMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1683,9 +1674,8 @@ async def test_get_metric_descriptor_field_headers_async(): type(client.transport.get_metric_descriptor), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor() + metric_pb2.MetricDescriptor() ) - await client.get_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1699,15 +1689,14 @@ async def test_get_metric_descriptor_field_headers_async(): def test_get_metric_descriptor_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor() - + call.return_value = metric_pb2.MetricDescriptor() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_metric_descriptor(name="name_value",) @@ -1716,12 +1705,11 @@ def test_get_metric_descriptor_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_metric_descriptor_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1733,17 +1721,19 @@ def test_get_metric_descriptor_flattened_error(): @pytest.mark.asyncio async def test_get_metric_descriptor_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.get_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor() + call.return_value = metric_pb2.MetricDescriptor() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor() + metric_pb2.MetricDescriptor() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -1753,13 +1743,14 @@ async def test_get_metric_descriptor_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_metric_descriptor_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1773,7 +1764,7 @@ def test_create_metric_descriptor( transport: str = "grpc", request_type=metric_service.CreateMetricDescriptorRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1785,40 +1776,30 @@ def test_create_metric_descriptor( type(client.transport.create_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor( + call.return_value = metric_pb2.MetricDescriptor( name="name_value", type="type_value", - metric_kind=ga_metric.MetricDescriptor.MetricKind.GAUGE, - value_type=ga_metric.MetricDescriptor.ValueType.BOOL, + metric_kind=metric_pb2.MetricDescriptor.MetricKind.GAUGE, + value_type=metric_pb2.MetricDescriptor.ValueType.BOOL, unit="unit_value", description="description_value", display_name="display_name_value", ) - response = client.create_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateMetricDescriptorRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, ga_metric.MetricDescriptor) - + assert isinstance(response, metric_pb2.MetricDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - - assert response.metric_kind == ga_metric.MetricDescriptor.MetricKind.GAUGE - - assert response.value_type == ga_metric.MetricDescriptor.ValueType.BOOL - + assert response.metric_kind == metric_pb2.MetricDescriptor.MetricKind.GAUGE + assert response.value_type == metric_pb2.MetricDescriptor.ValueType.BOOL assert response.unit == "unit_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" @@ -1830,7 +1811,7 @@ def test_create_metric_descriptor_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1840,7 +1821,6 @@ def test_create_metric_descriptor_empty_call(): client.create_metric_descriptor() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateMetricDescriptorRequest() @@ -1850,7 +1830,7 @@ async def test_create_metric_descriptor_async( request_type=metric_service.CreateMetricDescriptorRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1863,40 +1843,31 @@ async def test_create_metric_descriptor_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor( + metric_pb2.MetricDescriptor( name="name_value", type="type_value", - metric_kind=ga_metric.MetricDescriptor.MetricKind.GAUGE, - value_type=ga_metric.MetricDescriptor.ValueType.BOOL, + metric_kind=metric_pb2.MetricDescriptor.MetricKind.GAUGE, + value_type=metric_pb2.MetricDescriptor.ValueType.BOOL, unit="unit_value", description="description_value", display_name="display_name_value", ) ) - response = await client.create_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateMetricDescriptorRequest() # Establish that the response is the type that we expect. - assert isinstance(response, ga_metric.MetricDescriptor) - + assert isinstance(response, metric_pb2.MetricDescriptor) assert response.name == "name_value" - assert response.type == "type_value" - - assert response.metric_kind == ga_metric.MetricDescriptor.MetricKind.GAUGE - - assert response.value_type == ga_metric.MetricDescriptor.ValueType.BOOL - + assert response.metric_kind == metric_pb2.MetricDescriptor.MetricKind.GAUGE + assert response.value_type == metric_pb2.MetricDescriptor.ValueType.BOOL assert response.unit == "unit_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" @@ -1906,19 +1877,19 @@ async def test_create_metric_descriptor_async_from_dict(): def test_create_metric_descriptor_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.CreateMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.create_metric_descriptor), "__call__" ) as call: - call.return_value = ga_metric.MetricDescriptor() - + call.return_value = metric_pb2.MetricDescriptor() client.create_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1933,11 +1904,14 @@ def test_create_metric_descriptor_field_headers(): @pytest.mark.asyncio async def test_create_metric_descriptor_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.CreateMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1945,9 +1919,8 @@ async def test_create_metric_descriptor_field_headers_async(): type(client.transport.create_metric_descriptor), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor() + metric_pb2.MetricDescriptor() ) - await client.create_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1961,36 +1934,33 @@ async def test_create_metric_descriptor_field_headers_async(): def test_create_metric_descriptor_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.create_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor() - + call.return_value = metric_pb2.MetricDescriptor() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_metric_descriptor( name="name_value", - metric_descriptor=ga_metric.MetricDescriptor(name="name_value"), + metric_descriptor=metric_pb2.MetricDescriptor(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - assert args[0].metric_descriptor == ga_metric.MetricDescriptor( + assert args[0].metric_descriptor == metric_pb2.MetricDescriptor( name="name_value" ) def test_create_metric_descriptor_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1998,46 +1968,48 @@ def test_create_metric_descriptor_flattened_error(): client.create_metric_descriptor( metric_service.CreateMetricDescriptorRequest(), name="name_value", - metric_descriptor=ga_metric.MetricDescriptor(name="name_value"), + metric_descriptor=metric_pb2.MetricDescriptor(name="name_value"), ) @pytest.mark.asyncio async def test_create_metric_descriptor_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.create_metric_descriptor), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ga_metric.MetricDescriptor() + call.return_value = metric_pb2.MetricDescriptor() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - ga_metric.MetricDescriptor() + metric_pb2.MetricDescriptor() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_metric_descriptor( name="name_value", - metric_descriptor=ga_metric.MetricDescriptor(name="name_value"), + metric_descriptor=metric_pb2.MetricDescriptor(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - assert args[0].metric_descriptor == ga_metric.MetricDescriptor( + assert args[0].metric_descriptor == metric_pb2.MetricDescriptor( name="name_value" ) @pytest.mark.asyncio async def test_create_metric_descriptor_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2045,7 +2017,7 @@ async def test_create_metric_descriptor_flattened_error_async(): await client.create_metric_descriptor( metric_service.CreateMetricDescriptorRequest(), name="name_value", - metric_descriptor=ga_metric.MetricDescriptor(name="name_value"), + metric_descriptor=metric_pb2.MetricDescriptor(name="name_value"), ) @@ -2053,7 +2025,7 @@ def test_delete_metric_descriptor( transport: str = "grpc", request_type=metric_service.DeleteMetricDescriptorRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2066,13 +2038,11 @@ def test_delete_metric_descriptor( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.DeleteMetricDescriptorRequest() # Establish that the response is the type that we expect. @@ -2087,7 +2057,7 @@ def test_delete_metric_descriptor_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2097,7 +2067,6 @@ def test_delete_metric_descriptor_empty_call(): client.delete_metric_descriptor() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.DeleteMetricDescriptorRequest() @@ -2107,7 +2076,7 @@ async def test_delete_metric_descriptor_async( request_type=metric_service.DeleteMetricDescriptorRequest, ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2120,13 +2089,11 @@ async def test_delete_metric_descriptor_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.DeleteMetricDescriptorRequest() # Establish that the response is the type that we expect. @@ -2139,11 +2106,12 @@ async def test_delete_metric_descriptor_async_from_dict(): def test_delete_metric_descriptor_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.DeleteMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2151,7 +2119,6 @@ def test_delete_metric_descriptor_field_headers(): type(client.transport.delete_metric_descriptor), "__call__" ) as call: call.return_value = None - client.delete_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -2166,11 +2133,14 @@ def test_delete_metric_descriptor_field_headers(): @pytest.mark.asyncio async def test_delete_metric_descriptor_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.DeleteMetricDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2178,7 +2148,6 @@ async def test_delete_metric_descriptor_field_headers_async(): type(client.transport.delete_metric_descriptor), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_metric_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -2192,7 +2161,7 @@ async def test_delete_metric_descriptor_field_headers_async(): def test_delete_metric_descriptor_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2200,7 +2169,6 @@ def test_delete_metric_descriptor_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_metric_descriptor(name="name_value",) @@ -2209,12 +2177,11 @@ def test_delete_metric_descriptor_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_metric_descriptor_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2226,7 +2193,9 @@ def test_delete_metric_descriptor_flattened_error(): @pytest.mark.asyncio async def test_delete_metric_descriptor_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2244,13 +2213,14 @@ async def test_delete_metric_descriptor_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_metric_descriptor_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2264,7 +2234,7 @@ def test_list_time_series( transport: str = "grpc", request_type=metric_service.ListTimeSeriesRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2277,21 +2247,16 @@ def test_list_time_series( call.return_value = metric_service.ListTimeSeriesResponse( next_page_token="next_page_token_value", unit="unit_value", ) - response = client.list_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListTimeSeriesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTimeSeriesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unit == "unit_value" @@ -2303,7 +2268,7 @@ def test_list_time_series_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2311,7 +2276,6 @@ def test_list_time_series_empty_call(): client.list_time_series() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListTimeSeriesRequest() @@ -2320,7 +2284,7 @@ async def test_list_time_series_async( transport: str = "grpc_asyncio", request_type=metric_service.ListTimeSeriesRequest ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2335,20 +2299,16 @@ async def test_list_time_series_async( next_page_token="next_page_token_value", unit="unit_value", ) ) - response = await client.list_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.ListTimeSeriesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTimeSeriesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unit == "unit_value" @@ -2358,17 +2318,17 @@ async def test_list_time_series_async_from_dict(): def test_list_time_series_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.ListTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_time_series), "__call__") as call: call.return_value = metric_service.ListTimeSeriesResponse() - client.list_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -2383,11 +2343,14 @@ def test_list_time_series_field_headers(): @pytest.mark.asyncio async def test_list_time_series_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.ListTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2395,7 +2358,6 @@ async def test_list_time_series_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( metric_service.ListTimeSeriesResponse() ) - await client.list_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -2409,19 +2371,18 @@ async def test_list_time_series_field_headers_async(): def test_list_time_series_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_time_series), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = metric_service.ListTimeSeriesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_time_series( name="name_value", filter="filter_value", - interval=common.TimeInterval(end_time=timestamp.Timestamp(seconds=751)), + interval=common.TimeInterval(end_time=timestamp_pb2.Timestamp(seconds=751)), view=metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS, ) @@ -2429,22 +2390,18 @@ def test_list_time_series_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].filter == "filter_value" - assert args[0].interval == common.TimeInterval( - end_time=timestamp.Timestamp(seconds=751) + end_time=timestamp_pb2.Timestamp(seconds=751) ) - assert ( args[0].view == metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS ) def test_list_time_series_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2453,14 +2410,16 @@ def test_list_time_series_flattened_error(): metric_service.ListTimeSeriesRequest(), name="name_value", filter="filter_value", - interval=common.TimeInterval(end_time=timestamp.Timestamp(seconds=751)), + interval=common.TimeInterval(end_time=timestamp_pb2.Timestamp(seconds=751)), view=metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS, ) @pytest.mark.asyncio async def test_list_time_series_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_time_series), "__call__") as call: @@ -2475,7 +2434,7 @@ async def test_list_time_series_flattened_async(): response = await client.list_time_series( name="name_value", filter="filter_value", - interval=common.TimeInterval(end_time=timestamp.Timestamp(seconds=751)), + interval=common.TimeInterval(end_time=timestamp_pb2.Timestamp(seconds=751)), view=metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS, ) @@ -2483,15 +2442,11 @@ async def test_list_time_series_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].filter == "filter_value" - assert args[0].interval == common.TimeInterval( - end_time=timestamp.Timestamp(seconds=751) + end_time=timestamp_pb2.Timestamp(seconds=751) ) - assert ( args[0].view == metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS ) @@ -2499,7 +2454,9 @@ async def test_list_time_series_flattened_async(): @pytest.mark.asyncio async def test_list_time_series_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2508,13 +2465,13 @@ async def test_list_time_series_flattened_error_async(): metric_service.ListTimeSeriesRequest(), name="name_value", filter="filter_value", - interval=common.TimeInterval(end_time=timestamp.Timestamp(seconds=751)), + interval=common.TimeInterval(end_time=timestamp_pb2.Timestamp(seconds=751)), view=metric_service.ListTimeSeriesRequest.TimeSeriesView.HEADERS, ) def test_list_time_series_pager(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_time_series), "__call__") as call: @@ -2554,7 +2511,7 @@ def test_list_time_series_pager(): def test_list_time_series_pages(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_time_series), "__call__") as call: @@ -2586,7 +2543,7 @@ def test_list_time_series_pages(): @pytest.mark.asyncio async def test_list_time_series_async_pager(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2625,7 +2582,7 @@ async def test_list_time_series_async_pager(): @pytest.mark.asyncio async def test_list_time_series_async_pages(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = MetricServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2663,7 +2620,7 @@ def test_create_time_series( transport: str = "grpc", request_type=metric_service.CreateTimeSeriesRequest ): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2676,13 +2633,11 @@ def test_create_time_series( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.create_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateTimeSeriesRequest() # Establish that the response is the type that we expect. @@ -2697,7 +2652,7 @@ def test_create_time_series_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 = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2707,7 +2662,6 @@ def test_create_time_series_empty_call(): client.create_time_series() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateTimeSeriesRequest() @@ -2716,7 +2670,7 @@ async def test_create_time_series_async( transport: str = "grpc_asyncio", request_type=metric_service.CreateTimeSeriesRequest ): client = MetricServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2729,13 +2683,11 @@ async def test_create_time_series_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.create_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.CreateTimeSeriesRequest() # Establish that the response is the type that we expect. @@ -2748,11 +2700,12 @@ async def test_create_time_series_async_from_dict(): def test_create_time_series_field_headers(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(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 = metric_service.CreateTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2760,7 +2713,6 @@ def test_create_time_series_field_headers(): type(client.transport.create_time_series), "__call__" ) as call: call.return_value = None - client.create_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -2775,11 +2727,14 @@ def test_create_time_series_field_headers(): @pytest.mark.asyncio async def test_create_time_series_field_headers_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + 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 = metric_service.CreateTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2787,7 +2742,6 @@ async def test_create_time_series_field_headers_async(): type(client.transport.create_time_series), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.create_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -2801,7 +2755,7 @@ async def test_create_time_series_field_headers_async(): def test_create_time_series_flattened(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2809,13 +2763,12 @@ def test_create_time_series_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_time_series( name="name_value", time_series=[ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ], ) @@ -2823,16 +2776,14 @@ def test_create_time_series_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].time_series == [ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ] def test_create_time_series_flattened_error(): - client = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2841,14 +2792,16 @@ def test_create_time_series_flattened_error(): metric_service.CreateTimeSeriesRequest(), name="name_value", time_series=[ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ], ) @pytest.mark.asyncio async def test_create_time_series_flattened_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2863,7 +2816,7 @@ async def test_create_time_series_flattened_async(): response = await client.create_time_series( name="name_value", time_series=[ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ], ) @@ -2871,17 +2824,17 @@ async def test_create_time_series_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].time_series == [ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ] @pytest.mark.asyncio async def test_create_time_series_flattened_error_async(): - client = MetricServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2890,7 +2843,7 @@ async def test_create_time_series_flattened_error_async(): metric_service.CreateTimeSeriesRequest(), name="name_value", time_series=[ - gm_metric.TimeSeries(metric=ga_metric.Metric(type="type_value")) + gm_metric.TimeSeries(metric=metric_pb2.Metric(type="type_value")) ], ) @@ -2898,16 +2851,16 @@ async def test_create_time_series_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.MetricServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MetricServiceClient( - 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.MetricServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MetricServiceClient( @@ -2917,7 +2870,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.MetricServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = MetricServiceClient( @@ -2928,7 +2881,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.MetricServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = MetricServiceClient(transport=transport) assert client.transport is transport @@ -2937,13 +2890,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.MetricServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.MetricServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2958,23 +2911,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 = MetricServiceClient(credentials=credentials.AnonymousCredentials(),) + client = MetricServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.MetricServiceGrpcTransport,) def test_metric_service_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.MetricServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2986,7 +2939,7 @@ def test_metric_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.MetricServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3006,15 +2959,42 @@ def test_metric_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_metric_service_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.monitoring_v3.services.metric_service.transports.MetricServiceTransport._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.MetricServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_metric_service_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.monitoring_v3.services.metric_service.transports.MetricServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.MetricServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3032,19 +3012,38 @@ def test_metric_service_base_transport_with_credentials_file(): def test_metric_service_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.monitoring_v3.services.metric_service.transports.MetricServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.MetricServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_metric_service_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) + MetricServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_metric_service_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) MetricServiceClient() adc.assert_called_once_with( scopes=( @@ -3057,14 +3056,46 @@ def test_metric_service_auth_adc(): ) -def test_metric_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.MetricServiceGrpcTransport, + transports.MetricServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_metric_service_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.MetricServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MetricServiceGrpcTransport, + transports.MetricServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_metric_service_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/cloud-platform", @@ -3076,6 +3107,125 @@ def test_metric_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.MetricServiceGrpcTransport, grpc_helpers), + (transports.MetricServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_metric_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + scopes=["1", "2"], + default_host="monitoring.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.MetricServiceGrpcTransport, grpc_helpers), + (transports.MetricServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_metric_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + "https://www.googleapis.com/auth/monitoring.write", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.MetricServiceGrpcTransport, grpc_helpers), + (transports.MetricServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_metric_service_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( + "monitoring.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", [ @@ -3084,7 +3234,7 @@ def test_metric_service_transport_auth_adc(): ], ) def test_metric_service_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: @@ -3128,7 +3278,7 @@ def test_metric_service_grpc_transport_client_cert_source_for_mtls(transport_cla def test_metric_service_host_no_port(): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -3138,7 +3288,7 @@ def test_metric_service_host_no_port(): def test_metric_service_host_with_port(): client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -3192,9 +3342,9 @@ def test_metric_service_transport_channel_mtls_with_client_cert_source(transport 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", @@ -3280,7 +3430,6 @@ def test_metric_service_transport_channel_mtls_with_adc(transport_class): """def test_metric_descriptor_path(): project = "squid" - expected = "projects/{project}/metricDescriptors/{metric_descriptor=**}".format(project=project, ) actual = MetricServiceClient.metric_descriptor_path(project) assert expected == actual @@ -3288,8 +3437,7 @@ def test_metric_service_transport_channel_mtls_with_adc(transport_class): def test_parse_metric_descriptor_path(): expected = { - "project": "clam", - + "project": "clam", } path = MetricServiceClient.metric_descriptor_path(**expected) @@ -3303,7 +3451,6 @@ def test_parse_metric_descriptor_path(): def test_monitored_resource_descriptor_path(): project = "whelk" monitored_resource_descriptor = "octopus" - expected = "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}".format( project=project, monitored_resource_descriptor=monitored_resource_descriptor, ) @@ -3328,7 +3475,6 @@ def test_parse_monitored_resource_descriptor_path(): def test_time_series_path(): project = "cuttlefish" time_series = "mussel" - expected = "projects/{project}/timeSeries/{time_series}".format( project=project, time_series=time_series, ) @@ -3350,7 +3496,6 @@ def test_parse_time_series_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3371,7 +3516,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = MetricServiceClient.common_folder_path(folder) assert expected == actual @@ -3390,7 +3534,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = MetricServiceClient.common_organization_path(organization) assert expected == actual @@ -3409,7 +3552,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = MetricServiceClient.common_project_path(project) assert expected == actual @@ -3429,7 +3571,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3456,7 +3597,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.MetricServiceTransport, "_prep_wrapped_messages" ) as prep: client = MetricServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3465,6 +3606,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = MetricServiceClient.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/tests/unit/gapic/monitoring_v3/test_notification_channel_service.py b/tests/unit/gapic/monitoring_v3/test_notification_channel_service.py index a2fd1808..3fc0885b 100644 --- a/tests/unit/gapic/monitoring_v3/test_notification_channel_service.py +++ b/tests/unit/gapic/monitoring_v3/test_notification_channel_service.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,15 +23,15 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth -from google.api import label_pb2 as label # type: ignore -from google.api import launch_stage_pb2 as launch_stage # type: ignore + +from google.api import label_pb2 # type: ignore +from google.api import launch_stage_pb2 # type: ignore 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.monitoring_v3.services.notification_channel_service import ( NotificationChannelServiceAsyncClient, @@ -42,14 +41,44 @@ ) from google.cloud.monitoring_v3.services.notification_channel_service import pagers from google.cloud.monitoring_v3.services.notification_channel_service import transports +from google.cloud.monitoring_v3.services.notification_channel_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.notification_channel_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import common from google.cloud.monitoring_v3.types import mutation_record from google.cloud.monitoring_v3.types import notification from google.cloud.monitoring_v3.types import notification_service 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 wrappers_pb2 as wrappers # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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(): @@ -104,7 +133,7 @@ def test__get_default_mtls_endpoint(): [NotificationChannelServiceClient, NotificationChannelServiceAsyncClient,], ) def test_notification_channel_service_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: @@ -122,7 +151,7 @@ def test_notification_channel_service_client_from_service_account_info(client_cl [NotificationChannelServiceClient, NotificationChannelServiceAsyncClient,], ) def test_notification_channel_service_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: @@ -181,7 +210,7 @@ def test_notification_channel_service_client_client_options( with mock.patch.object( NotificationChannelServiceClient, "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() @@ -490,7 +519,7 @@ def test_list_notification_channel_descriptors( request_type=notification_service.ListNotificationChannelDescriptorsRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -505,21 +534,17 @@ def test_list_notification_channel_descriptors( call.return_value = notification_service.ListNotificationChannelDescriptorsResponse( next_page_token="next_page_token_value", ) - response = client.list_notification_channel_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.ListNotificationChannelDescriptorsRequest() ) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationChannelDescriptorsPager) - assert response.next_page_token == "next_page_token_value" @@ -531,7 +556,7 @@ def test_list_notification_channel_descriptors_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -541,7 +566,6 @@ def test_list_notification_channel_descriptors_empty_call(): client.list_notification_channel_descriptors() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.ListNotificationChannelDescriptorsRequest() ) @@ -553,7 +577,7 @@ async def test_list_notification_channel_descriptors_async( request_type=notification_service.ListNotificationChannelDescriptorsRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -570,20 +594,17 @@ async def test_list_notification_channel_descriptors_async( next_page_token="next_page_token_value", ) ) - response = await client.list_notification_channel_descriptors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.ListNotificationChannelDescriptorsRequest() ) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListNotificationChannelDescriptorsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -594,12 +615,13 @@ async def test_list_notification_channel_descriptors_async_from_dict(): def test_list_notification_channel_descriptors_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.ListNotificationChannelDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -609,7 +631,6 @@ def test_list_notification_channel_descriptors_field_headers(): call.return_value = ( notification_service.ListNotificationChannelDescriptorsResponse() ) - client.list_notification_channel_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -625,12 +646,13 @@ def test_list_notification_channel_descriptors_field_headers(): @pytest.mark.asyncio async def test_list_notification_channel_descriptors_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.ListNotificationChannelDescriptorsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -640,7 +662,6 @@ async def test_list_notification_channel_descriptors_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification_service.ListNotificationChannelDescriptorsResponse() ) - await client.list_notification_channel_descriptors(request) # Establish that the underlying gRPC stub method was called. @@ -655,7 +676,7 @@ async def test_list_notification_channel_descriptors_field_headers_async(): def test_list_notification_channel_descriptors_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -666,7 +687,6 @@ def test_list_notification_channel_descriptors_flattened(): call.return_value = ( notification_service.ListNotificationChannelDescriptorsResponse() ) - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_notification_channel_descriptors(name="name_value",) @@ -675,13 +695,12 @@ def test_list_notification_channel_descriptors_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_notification_channel_descriptors_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -696,7 +715,7 @@ def test_list_notification_channel_descriptors_flattened_error(): @pytest.mark.asyncio async def test_list_notification_channel_descriptors_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -721,14 +740,13 @@ async def test_list_notification_channel_descriptors_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_notification_channel_descriptors_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -742,7 +760,7 @@ async def test_list_notification_channel_descriptors_flattened_error_async(): def test_list_notification_channel_descriptors_pager(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -792,7 +810,7 @@ def test_list_notification_channel_descriptors_pager(): def test_list_notification_channel_descriptors_pages(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +850,7 @@ def test_list_notification_channel_descriptors_pages(): @pytest.mark.asyncio async def test_list_notification_channel_descriptors_async_pager(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -881,7 +899,7 @@ async def test_list_notification_channel_descriptors_async_pager(): @pytest.mark.asyncio async def test_list_notification_channel_descriptors_async_pages(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -929,7 +947,7 @@ def test_get_notification_channel_descriptor( request_type=notification_service.GetNotificationChannelDescriptorRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -948,27 +966,19 @@ def test_get_notification_channel_descriptor( description="description_value", supported_tiers=[common.ServiceTier.SERVICE_TIER_BASIC], ) - response = client.get_notification_channel_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelDescriptorRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification.NotificationChannelDescriptor) - assert response.name == "name_value" - assert response.type_ == "type__value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.supported_tiers == [common.ServiceTier.SERVICE_TIER_BASIC] @@ -980,7 +990,7 @@ def test_get_notification_channel_descriptor_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -990,7 +1000,6 @@ def test_get_notification_channel_descriptor_empty_call(): client.get_notification_channel_descriptor() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelDescriptorRequest() @@ -1000,7 +1009,7 @@ async def test_get_notification_channel_descriptor_async( request_type=notification_service.GetNotificationChannelDescriptorRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1021,26 +1030,19 @@ async def test_get_notification_channel_descriptor_async( supported_tiers=[common.ServiceTier.SERVICE_TIER_BASIC], ) ) - response = await client.get_notification_channel_descriptor(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelDescriptorRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification.NotificationChannelDescriptor) - assert response.name == "name_value" - assert response.type_ == "type__value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.supported_tiers == [common.ServiceTier.SERVICE_TIER_BASIC] @@ -1051,12 +1053,13 @@ async def test_get_notification_channel_descriptor_async_from_dict(): def test_get_notification_channel_descriptor_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.GetNotificationChannelDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1067,6 @@ def test_get_notification_channel_descriptor_field_headers(): type(client.transport.get_notification_channel_descriptor), "__call__" ) as call: call.return_value = notification.NotificationChannelDescriptor() - client.get_notification_channel_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1080,12 +1082,13 @@ def test_get_notification_channel_descriptor_field_headers(): @pytest.mark.asyncio async def test_get_notification_channel_descriptor_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.GetNotificationChannelDescriptorRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1095,7 +1098,6 @@ async def test_get_notification_channel_descriptor_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification.NotificationChannelDescriptor() ) - await client.get_notification_channel_descriptor(request) # Establish that the underlying gRPC stub method was called. @@ -1110,7 +1112,7 @@ async def test_get_notification_channel_descriptor_field_headers_async(): def test_get_notification_channel_descriptor_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1119,7 +1121,6 @@ def test_get_notification_channel_descriptor_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification.NotificationChannelDescriptor() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_notification_channel_descriptor(name="name_value",) @@ -1128,13 +1129,12 @@ def test_get_notification_channel_descriptor_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_notification_channel_descriptor_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1149,7 +1149,7 @@ def test_get_notification_channel_descriptor_flattened_error(): @pytest.mark.asyncio async def test_get_notification_channel_descriptor_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1170,14 +1170,13 @@ async def test_get_notification_channel_descriptor_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_notification_channel_descriptor_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1194,7 +1193,7 @@ def test_list_notification_channels( request_type=notification_service.ListNotificationChannelsRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1209,21 +1208,16 @@ def test_list_notification_channels( call.return_value = notification_service.ListNotificationChannelsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_notification_channels(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.ListNotificationChannelsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationChannelsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -1235,7 +1229,7 @@ def test_list_notification_channels_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1245,7 +1239,6 @@ def test_list_notification_channels_empty_call(): client.list_notification_channels() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.ListNotificationChannelsRequest() @@ -1255,7 +1248,7 @@ async def test_list_notification_channels_async( request_type=notification_service.ListNotificationChannelsRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1272,20 +1265,16 @@ async def test_list_notification_channels_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_notification_channels(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.ListNotificationChannelsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListNotificationChannelsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -1296,12 +1285,13 @@ async def test_list_notification_channels_async_from_dict(): def test_list_notification_channels_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.ListNotificationChannelsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1309,7 +1299,6 @@ def test_list_notification_channels_field_headers(): type(client.transport.list_notification_channels), "__call__" ) as call: call.return_value = notification_service.ListNotificationChannelsResponse() - client.list_notification_channels(request) # Establish that the underlying gRPC stub method was called. @@ -1325,12 +1314,13 @@ def test_list_notification_channels_field_headers(): @pytest.mark.asyncio async def test_list_notification_channels_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.ListNotificationChannelsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1340,7 +1330,6 @@ async def test_list_notification_channels_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification_service.ListNotificationChannelsResponse() ) - await client.list_notification_channels(request) # Establish that the underlying gRPC stub method was called. @@ -1355,7 +1344,7 @@ async def test_list_notification_channels_field_headers_async(): def test_list_notification_channels_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1364,7 +1353,6 @@ def test_list_notification_channels_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification_service.ListNotificationChannelsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_notification_channels(name="name_value",) @@ -1373,13 +1361,12 @@ def test_list_notification_channels_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_notification_channels_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1393,7 +1380,7 @@ def test_list_notification_channels_flattened_error(): @pytest.mark.asyncio async def test_list_notification_channels_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1414,14 +1401,13 @@ async def test_list_notification_channels_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_list_notification_channels_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1434,7 +1420,7 @@ async def test_list_notification_channels_flattened_error_async(): def test_list_notification_channels_pager(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1482,7 +1468,7 @@ def test_list_notification_channels_pager(): def test_list_notification_channels_pages(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1522,7 +1508,7 @@ def test_list_notification_channels_pages(): @pytest.mark.asyncio async def test_list_notification_channels_async_pager(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1569,7 +1555,7 @@ async def test_list_notification_channels_async_pager(): @pytest.mark.asyncio async def test_list_notification_channels_async_pages(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1615,7 +1601,7 @@ def test_get_notification_channel( request_type=notification_service.GetNotificationChannelRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1634,27 +1620,19 @@ def test_get_notification_channel( description="description_value", verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) - response = client.get_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -1669,7 +1647,7 @@ def test_get_notification_channel_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1679,7 +1657,6 @@ def test_get_notification_channel_empty_call(): client.get_notification_channel() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelRequest() @@ -1689,7 +1666,7 @@ async def test_get_notification_channel_async( request_type=notification_service.GetNotificationChannelRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1710,26 +1687,19 @@ async def test_get_notification_channel_async( verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) ) - response = await client.get_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.GetNotificationChannelRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -1743,12 +1713,13 @@ async def test_get_notification_channel_async_from_dict(): def test_get_notification_channel_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.GetNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1756,7 +1727,6 @@ def test_get_notification_channel_field_headers(): type(client.transport.get_notification_channel), "__call__" ) as call: call.return_value = notification.NotificationChannel() - client.get_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -1772,12 +1742,13 @@ def test_get_notification_channel_field_headers(): @pytest.mark.asyncio async def test_get_notification_channel_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.GetNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1787,7 +1758,6 @@ async def test_get_notification_channel_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification.NotificationChannel() ) - await client.get_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -1802,7 +1772,7 @@ async def test_get_notification_channel_field_headers_async(): def test_get_notification_channel_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1811,7 +1781,6 @@ def test_get_notification_channel_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification.NotificationChannel() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_notification_channel(name="name_value",) @@ -1820,13 +1789,12 @@ def test_get_notification_channel_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_notification_channel_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1840,7 +1808,7 @@ def test_get_notification_channel_flattened_error(): @pytest.mark.asyncio async def test_get_notification_channel_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1861,14 +1829,13 @@ async def test_get_notification_channel_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_notification_channel_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1884,7 +1851,7 @@ def test_create_notification_channel( request_type=notification_service.CreateNotificationChannelRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1903,27 +1870,19 @@ def test_create_notification_channel( description="description_value", verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) - response = client.create_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.CreateNotificationChannelRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -1938,7 +1897,7 @@ def test_create_notification_channel_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1948,7 +1907,6 @@ def test_create_notification_channel_empty_call(): client.create_notification_channel() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.CreateNotificationChannelRequest() @@ -1958,7 +1916,7 @@ async def test_create_notification_channel_async( request_type=notification_service.CreateNotificationChannelRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1979,26 +1937,19 @@ async def test_create_notification_channel_async( verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) ) - response = await client.create_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.CreateNotificationChannelRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -2012,12 +1963,13 @@ async def test_create_notification_channel_async_from_dict(): def test_create_notification_channel_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.CreateNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2025,7 +1977,6 @@ def test_create_notification_channel_field_headers(): type(client.transport.create_notification_channel), "__call__" ) as call: call.return_value = notification.NotificationChannel() - client.create_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2041,12 +1992,13 @@ def test_create_notification_channel_field_headers(): @pytest.mark.asyncio async def test_create_notification_channel_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.CreateNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2056,7 +2008,6 @@ async def test_create_notification_channel_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification.NotificationChannel() ) - await client.create_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2071,7 +2022,7 @@ async def test_create_notification_channel_field_headers_async(): def test_create_notification_channel_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2080,7 +2031,6 @@ def test_create_notification_channel_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification.NotificationChannel() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_notification_channel( @@ -2092,9 +2042,7 @@ def test_create_notification_channel_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].notification_channel == notification.NotificationChannel( type_="type__value" ) @@ -2102,7 +2050,7 @@ def test_create_notification_channel_flattened(): def test_create_notification_channel_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2118,7 +2066,7 @@ def test_create_notification_channel_flattened_error(): @pytest.mark.asyncio async def test_create_notification_channel_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2142,9 +2090,7 @@ async def test_create_notification_channel_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].notification_channel == notification.NotificationChannel( type_="type__value" ) @@ -2153,7 +2099,7 @@ async def test_create_notification_channel_flattened_async(): @pytest.mark.asyncio async def test_create_notification_channel_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2171,7 +2117,7 @@ def test_update_notification_channel( request_type=notification_service.UpdateNotificationChannelRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2190,27 +2136,19 @@ def test_update_notification_channel( description="description_value", verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) - response = client.update_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.UpdateNotificationChannelRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -2225,7 +2163,7 @@ def test_update_notification_channel_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2235,7 +2173,6 @@ def test_update_notification_channel_empty_call(): client.update_notification_channel() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.UpdateNotificationChannelRequest() @@ -2245,7 +2182,7 @@ async def test_update_notification_channel_async( request_type=notification_service.UpdateNotificationChannelRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2266,26 +2203,19 @@ async def test_update_notification_channel_async( verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) ) - response = await client.update_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.UpdateNotificationChannelRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -2299,12 +2229,13 @@ async def test_update_notification_channel_async_from_dict(): def test_update_notification_channel_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.UpdateNotificationChannelRequest() + request.notification_channel.name = "notification_channel.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2312,7 +2243,6 @@ def test_update_notification_channel_field_headers(): type(client.transport.update_notification_channel), "__call__" ) as call: call.return_value = notification.NotificationChannel() - client.update_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2331,12 +2261,13 @@ def test_update_notification_channel_field_headers(): @pytest.mark.asyncio async def test_update_notification_channel_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.UpdateNotificationChannelRequest() + request.notification_channel.name = "notification_channel.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2346,7 +2277,6 @@ async def test_update_notification_channel_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification.NotificationChannel() ) - await client.update_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2364,7 +2294,7 @@ async def test_update_notification_channel_field_headers_async(): def test_update_notification_channel_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2373,11 +2303,10 @@ def test_update_notification_channel_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification.NotificationChannel() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_notification_channel( - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), notification_channel=notification.NotificationChannel(type_="type__value"), ) @@ -2385,9 +2314,7 @@ def test_update_notification_channel_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].notification_channel == notification.NotificationChannel( type_="type__value" ) @@ -2395,7 +2322,7 @@ def test_update_notification_channel_flattened(): def test_update_notification_channel_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2403,7 +2330,7 @@ def test_update_notification_channel_flattened_error(): with pytest.raises(ValueError): client.update_notification_channel( notification_service.UpdateNotificationChannelRequest(), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), notification_channel=notification.NotificationChannel(type_="type__value"), ) @@ -2411,7 +2338,7 @@ def test_update_notification_channel_flattened_error(): @pytest.mark.asyncio async def test_update_notification_channel_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2427,7 +2354,7 @@ async def test_update_notification_channel_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_notification_channel( - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), notification_channel=notification.NotificationChannel(type_="type__value"), ) @@ -2435,9 +2362,7 @@ async def test_update_notification_channel_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) assert args[0].notification_channel == notification.NotificationChannel( type_="type__value" ) @@ -2446,7 +2371,7 @@ async def test_update_notification_channel_flattened_async(): @pytest.mark.asyncio async def test_update_notification_channel_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2454,7 +2379,7 @@ async def test_update_notification_channel_flattened_error_async(): with pytest.raises(ValueError): await client.update_notification_channel( notification_service.UpdateNotificationChannelRequest(), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), notification_channel=notification.NotificationChannel(type_="type__value"), ) @@ -2464,7 +2389,7 @@ def test_delete_notification_channel( request_type=notification_service.DeleteNotificationChannelRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2477,13 +2402,11 @@ def test_delete_notification_channel( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.DeleteNotificationChannelRequest() # Establish that the response is the type that we expect. @@ -2498,7 +2421,7 @@ def test_delete_notification_channel_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2508,7 +2431,6 @@ def test_delete_notification_channel_empty_call(): client.delete_notification_channel() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.DeleteNotificationChannelRequest() @@ -2518,7 +2440,7 @@ async def test_delete_notification_channel_async( request_type=notification_service.DeleteNotificationChannelRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2531,13 +2453,11 @@ async def test_delete_notification_channel_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.DeleteNotificationChannelRequest() # Establish that the response is the type that we expect. @@ -2551,12 +2471,13 @@ async def test_delete_notification_channel_async_from_dict(): def test_delete_notification_channel_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.DeleteNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2564,7 +2485,6 @@ def test_delete_notification_channel_field_headers(): type(client.transport.delete_notification_channel), "__call__" ) as call: call.return_value = None - client.delete_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2580,12 +2500,13 @@ def test_delete_notification_channel_field_headers(): @pytest.mark.asyncio async def test_delete_notification_channel_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.DeleteNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2593,7 +2514,6 @@ async def test_delete_notification_channel_field_headers_async(): type(client.transport.delete_notification_channel), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -2608,7 +2528,7 @@ async def test_delete_notification_channel_field_headers_async(): def test_delete_notification_channel_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2617,7 +2537,6 @@ def test_delete_notification_channel_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_notification_channel( @@ -2628,15 +2547,13 @@ def test_delete_notification_channel_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].force == True def test_delete_notification_channel_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2652,7 +2569,7 @@ def test_delete_notification_channel_flattened_error(): @pytest.mark.asyncio async def test_delete_notification_channel_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2673,16 +2590,14 @@ async def test_delete_notification_channel_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].force == True @pytest.mark.asyncio async def test_delete_notification_channel_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2700,7 +2615,7 @@ def test_send_notification_channel_verification_code( request_type=notification_service.SendNotificationChannelVerificationCodeRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2713,13 +2628,11 @@ def test_send_notification_channel_verification_code( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.send_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.SendNotificationChannelVerificationCodeRequest() @@ -2737,7 +2650,7 @@ def test_send_notification_channel_verification_code_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2747,7 +2660,6 @@ def test_send_notification_channel_verification_code_empty_call(): client.send_notification_channel_verification_code() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.SendNotificationChannelVerificationCodeRequest() @@ -2760,7 +2672,7 @@ async def test_send_notification_channel_verification_code_async( request_type=notification_service.SendNotificationChannelVerificationCodeRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2773,13 +2685,11 @@ async def test_send_notification_channel_verification_code_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.send_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.SendNotificationChannelVerificationCodeRequest() @@ -2796,12 +2706,13 @@ async def test_send_notification_channel_verification_code_async_from_dict(): def test_send_notification_channel_verification_code_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.SendNotificationChannelVerificationCodeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2809,7 +2720,6 @@ def test_send_notification_channel_verification_code_field_headers(): type(client.transport.send_notification_channel_verification_code), "__call__" ) as call: call.return_value = None - client.send_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. @@ -2825,12 +2735,13 @@ def test_send_notification_channel_verification_code_field_headers(): @pytest.mark.asyncio async def test_send_notification_channel_verification_code_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.SendNotificationChannelVerificationCodeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2838,7 +2749,6 @@ async def test_send_notification_channel_verification_code_field_headers_async() type(client.transport.send_notification_channel_verification_code), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.send_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. @@ -2853,7 +2763,7 @@ async def test_send_notification_channel_verification_code_field_headers_async() def test_send_notification_channel_verification_code_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2862,7 +2772,6 @@ def test_send_notification_channel_verification_code_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.send_notification_channel_verification_code(name="name_value",) @@ -2871,13 +2780,12 @@ def test_send_notification_channel_verification_code_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_send_notification_channel_verification_code_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2892,7 +2800,7 @@ def test_send_notification_channel_verification_code_flattened_error(): @pytest.mark.asyncio async def test_send_notification_channel_verification_code_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2913,14 +2821,13 @@ async def test_send_notification_channel_verification_code_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_send_notification_channel_verification_code_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2937,7 +2844,7 @@ def test_get_notification_channel_verification_code( request_type=notification_service.GetNotificationChannelVerificationCodeRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2952,24 +2859,20 @@ def test_get_notification_channel_verification_code( call.return_value = notification_service.GetNotificationChannelVerificationCodeResponse( code="code_value", ) - response = client.get_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.GetNotificationChannelVerificationCodeRequest() ) # Establish that the response is the type that we expect. - assert isinstance( response, notification_service.GetNotificationChannelVerificationCodeResponse ) - assert response.code == "code_value" @@ -2981,7 +2884,7 @@ def test_get_notification_channel_verification_code_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2991,7 +2894,6 @@ def test_get_notification_channel_verification_code_empty_call(): client.get_notification_channel_verification_code() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.GetNotificationChannelVerificationCodeRequest() @@ -3004,7 +2906,7 @@ async def test_get_notification_channel_verification_code_async( request_type=notification_service.GetNotificationChannelVerificationCodeRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3021,13 +2923,11 @@ async def test_get_notification_channel_verification_code_async( code="code_value", ) ) - response = await client.get_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == notification_service.GetNotificationChannelVerificationCodeRequest() @@ -3037,7 +2937,6 @@ async def test_get_notification_channel_verification_code_async( assert isinstance( response, notification_service.GetNotificationChannelVerificationCodeResponse ) - assert response.code == "code_value" @@ -3048,12 +2947,13 @@ async def test_get_notification_channel_verification_code_async_from_dict(): def test_get_notification_channel_verification_code_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.GetNotificationChannelVerificationCodeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3063,7 +2963,6 @@ def test_get_notification_channel_verification_code_field_headers(): call.return_value = ( notification_service.GetNotificationChannelVerificationCodeResponse() ) - client.get_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. @@ -3079,12 +2978,13 @@ def test_get_notification_channel_verification_code_field_headers(): @pytest.mark.asyncio async def test_get_notification_channel_verification_code_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.GetNotificationChannelVerificationCodeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3094,7 +2994,6 @@ async def test_get_notification_channel_verification_code_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification_service.GetNotificationChannelVerificationCodeResponse() ) - await client.get_notification_channel_verification_code(request) # Establish that the underlying gRPC stub method was called. @@ -3109,7 +3008,7 @@ async def test_get_notification_channel_verification_code_field_headers_async(): def test_get_notification_channel_verification_code_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3120,7 +3019,6 @@ def test_get_notification_channel_verification_code_flattened(): call.return_value = ( notification_service.GetNotificationChannelVerificationCodeResponse() ) - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_notification_channel_verification_code(name="name_value",) @@ -3129,13 +3027,12 @@ def test_get_notification_channel_verification_code_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_notification_channel_verification_code_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3150,7 +3047,7 @@ def test_get_notification_channel_verification_code_flattened_error(): @pytest.mark.asyncio async def test_get_notification_channel_verification_code_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3175,14 +3072,13 @@ async def test_get_notification_channel_verification_code_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_notification_channel_verification_code_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3199,7 +3095,7 @@ def test_verify_notification_channel( request_type=notification_service.VerifyNotificationChannelRequest, ): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3218,27 +3114,19 @@ def test_verify_notification_channel( description="description_value", verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) - response = client.verify_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.VerifyNotificationChannelRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -3253,7 +3141,7 @@ def test_verify_notification_channel_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 = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3263,7 +3151,6 @@ def test_verify_notification_channel_empty_call(): client.verify_notification_channel() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.VerifyNotificationChannelRequest() @@ -3273,7 +3160,7 @@ async def test_verify_notification_channel_async( request_type=notification_service.VerifyNotificationChannelRequest, ): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3294,26 +3181,19 @@ async def test_verify_notification_channel_async( verification_status=notification.NotificationChannel.VerificationStatus.UNVERIFIED, ) ) - response = await client.verify_notification_channel(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == notification_service.VerifyNotificationChannelRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification.NotificationChannel) - assert response.type_ == "type__value" - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert ( response.verification_status == notification.NotificationChannel.VerificationStatus.UNVERIFIED @@ -3327,12 +3207,13 @@ async def test_verify_notification_channel_async_from_dict(): def test_verify_notification_channel_field_headers(): client = NotificationChannelServiceClient( - 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 = notification_service.VerifyNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3340,7 +3221,6 @@ def test_verify_notification_channel_field_headers(): type(client.transport.verify_notification_channel), "__call__" ) as call: call.return_value = notification.NotificationChannel() - client.verify_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -3356,12 +3236,13 @@ def test_verify_notification_channel_field_headers(): @pytest.mark.asyncio async def test_verify_notification_channel_field_headers_async(): client = NotificationChannelServiceAsyncClient( - 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 = notification_service.VerifyNotificationChannelRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3371,7 +3252,6 @@ async def test_verify_notification_channel_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification.NotificationChannel() ) - await client.verify_notification_channel(request) # Establish that the underlying gRPC stub method was called. @@ -3386,7 +3266,7 @@ async def test_verify_notification_channel_field_headers_async(): def test_verify_notification_channel_flattened(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3395,7 +3275,6 @@ def test_verify_notification_channel_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification.NotificationChannel() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.verify_notification_channel( @@ -3406,15 +3285,13 @@ def test_verify_notification_channel_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].code == "code_value" def test_verify_notification_channel_flattened_error(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3430,7 +3307,7 @@ def test_verify_notification_channel_flattened_error(): @pytest.mark.asyncio async def test_verify_notification_channel_flattened_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3453,16 +3330,14 @@ async def test_verify_notification_channel_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].code == "code_value" @pytest.mark.asyncio async def test_verify_notification_channel_flattened_error_async(): client = NotificationChannelServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3478,16 +3353,16 @@ async def test_verify_notification_channel_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.NotificationChannelServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NotificationChannelServiceClient( - 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.NotificationChannelServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NotificationChannelServiceClient( @@ -3497,7 +3372,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.NotificationChannelServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = NotificationChannelServiceClient( @@ -3508,7 +3383,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.NotificationChannelServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = NotificationChannelServiceClient(transport=transport) assert client.transport is transport @@ -3517,13 +3392,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.NotificationChannelServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.NotificationChannelServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3538,8 +3413,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() @@ -3547,7 +3422,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.NotificationChannelServiceGrpcTransport, @@ -3556,9 +3431,9 @@ def test_transport_grpc_default(): def test_notification_channel_service_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.NotificationChannelServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3570,7 +3445,7 @@ def test_notification_channel_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.NotificationChannelServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3592,15 +3467,41 @@ def test_notification_channel_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_notification_channel_service_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.monitoring_v3.services.notification_channel_service.transports.NotificationChannelServiceTransport._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.NotificationChannelServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_notification_channel_service_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.monitoring_v3.services.notification_channel_service.transports.NotificationChannelServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NotificationChannelServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3617,19 +3518,37 @@ def test_notification_channel_service_base_transport_with_credentials_file(): def test_notification_channel_service_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.monitoring_v3.services.notification_channel_service.transports.NotificationChannelServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.NotificationChannelServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_notification_channel_service_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) + NotificationChannelServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_notification_channel_service_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) NotificationChannelServiceClient() adc.assert_called_once_with( scopes=( @@ -3641,14 +3560,47 @@ def test_notification_channel_service_auth_adc(): ) -def test_notification_channel_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.NotificationChannelServiceGrpcTransport, + transports.NotificationChannelServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_notification_channel_service_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.NotificationChannelServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NotificationChannelServiceGrpcTransport, + transports.NotificationChannelServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_notification_channel_service_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/cloud-platform", @@ -3659,6 +3611,125 @@ def test_notification_channel_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NotificationChannelServiceGrpcTransport, grpc_helpers), + (transports.NotificationChannelServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_notification_channel_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.NotificationChannelServiceGrpcTransport, grpc_helpers), + (transports.NotificationChannelServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_notification_channel_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NotificationChannelServiceGrpcTransport, grpc_helpers), + (transports.NotificationChannelServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_notification_channel_service_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( + "monitoring.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", [ @@ -3669,7 +3740,7 @@ def test_notification_channel_service_transport_auth_adc(): def test_notification_channel_service_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: @@ -3712,7 +3783,7 @@ def test_notification_channel_service_grpc_transport_client_cert_source_for_mtls def test_notification_channel_service_host_no_port(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -3722,7 +3793,7 @@ def test_notification_channel_service_host_no_port(): def test_notification_channel_service_host_with_port(): client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -3778,9 +3849,9 @@ def test_notification_channel_service_transport_channel_mtls_with_client_cert_so 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", @@ -3865,7 +3936,6 @@ def test_notification_channel_service_transport_channel_mtls_with_adc(transport_ def test_notification_channel_path(): project = "squid" notification_channel = "clam" - expected = "projects/{project}/notificationChannels/{notification_channel}".format( project=project, notification_channel=notification_channel, ) @@ -3890,7 +3960,6 @@ def test_parse_notification_channel_path(): def test_notification_channel_descriptor_path(): project = "oyster" channel_descriptor = "nudibranch" - expected = "projects/{project}/notificationChannelDescriptors/{channel_descriptor}".format( project=project, channel_descriptor=channel_descriptor, ) @@ -3918,7 +3987,6 @@ def test_parse_notification_channel_descriptor_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3941,7 +4009,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = NotificationChannelServiceClient.common_folder_path(folder) assert expected == actual @@ -3960,7 +4027,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = NotificationChannelServiceClient.common_organization_path(organization) assert expected == actual @@ -3979,7 +4045,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = NotificationChannelServiceClient.common_project_path(project) assert expected == actual @@ -3999,7 +4064,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, ) @@ -4026,7 +4090,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.NotificationChannelServiceTransport, "_prep_wrapped_messages" ) as prep: client = NotificationChannelServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -4035,6 +4099,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = NotificationChannelServiceClient.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/tests/unit/gapic/monitoring_v3/test_query_service.py b/tests/unit/gapic/monitoring_v3/test_query_service.py index a7b86044..169d45cb 100644 --- a/tests/unit/gapic/monitoring_v3/test_query_service.py +++ b/tests/unit/gapic/monitoring_v3/test_query_service.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,51 @@ 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.monitoring_v3.services.query_service import QueryServiceAsyncClient from google.cloud.monitoring_v3.services.query_service import QueryServiceClient from google.cloud.monitoring_v3.services.query_service import pagers from google.cloud.monitoring_v3.services.query_service import transports +from google.cloud.monitoring_v3.services.query_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.query_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import metric from google.cloud.monitoring_v3.types import metric_service 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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [QueryServiceClient, QueryServiceAsyncClient,]) def test_query_service_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: @@ -99,7 +128,7 @@ def test_query_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [QueryServiceClient, QueryServiceAsyncClient,]) def test_query_service_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: @@ -150,7 +179,7 @@ def test_query_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(QueryServiceClient, "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() @@ -434,7 +463,7 @@ def test_query_time_series( transport: str = "grpc", request_type=metric_service.QueryTimeSeriesRequest ): client = QueryServiceClient( - 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_query_time_series( call.return_value = metric_service.QueryTimeSeriesResponse( next_page_token="next_page_token_value", ) - response = client.query_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.QueryTimeSeriesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.QueryTimeSeriesPager) - assert response.next_page_token == "next_page_token_value" @@ -473,7 +498,7 @@ def test_query_time_series_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 = QueryServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -483,7 +508,6 @@ def test_query_time_series_empty_call(): client.query_time_series() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.QueryTimeSeriesRequest() @@ -492,7 +516,7 @@ async def test_query_time_series_async( transport: str = "grpc_asyncio", request_type=metric_service.QueryTimeSeriesRequest ): client = QueryServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -509,18 +533,15 @@ async def test_query_time_series_async( next_page_token="next_page_token_value", ) ) - response = await client.query_time_series(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == metric_service.QueryTimeSeriesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.QueryTimeSeriesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -530,11 +551,12 @@ async def test_query_time_series_async_from_dict(): def test_query_time_series_field_headers(): - client = QueryServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QueryServiceClient(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 = metric_service.QueryTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -542,7 +564,6 @@ def test_query_time_series_field_headers(): type(client.transport.query_time_series), "__call__" ) as call: call.return_value = metric_service.QueryTimeSeriesResponse() - client.query_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -557,11 +578,12 @@ def test_query_time_series_field_headers(): @pytest.mark.asyncio async def test_query_time_series_field_headers_async(): - client = QueryServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = QueryServiceAsyncClient(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 = metric_service.QueryTimeSeriesRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -571,7 +593,6 @@ async def test_query_time_series_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( metric_service.QueryTimeSeriesResponse() ) - await client.query_time_series(request) # Establish that the underlying gRPC stub method was called. @@ -585,7 +606,7 @@ async def test_query_time_series_field_headers_async(): def test_query_time_series_pager(): - client = QueryServiceClient(credentials=credentials.AnonymousCredentials,) + client = QueryServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -627,7 +648,7 @@ def test_query_time_series_pager(): def test_query_time_series_pages(): - client = QueryServiceClient(credentials=credentials.AnonymousCredentials,) + client = QueryServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -661,7 +682,7 @@ def test_query_time_series_pages(): @pytest.mark.asyncio async def test_query_time_series_async_pager(): - client = QueryServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = QueryServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -702,7 +723,7 @@ async def test_query_time_series_async_pager(): @pytest.mark.asyncio async def test_query_time_series_async_pages(): - client = QueryServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = QueryServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -741,16 +762,16 @@ async def test_query_time_series_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.QueryServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QueryServiceClient( - 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.QueryServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QueryServiceClient( @@ -760,7 +781,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.QueryServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = QueryServiceClient( @@ -771,7 +792,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.QueryServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = QueryServiceClient(transport=transport) assert client.transport is transport @@ -780,13 +801,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.QueryServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.QueryServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -801,23 +822,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 = QueryServiceClient(credentials=credentials.AnonymousCredentials(),) + client = QueryServiceClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.QueryServiceGrpcTransport,) def test_query_service_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.QueryServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -829,7 +850,7 @@ def test_query_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.QueryServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -840,15 +861,41 @@ def test_query_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_query_service_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.monitoring_v3.services.query_service.transports.QueryServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.QueryServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_query_service_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.monitoring_v3.services.query_service.transports.QueryServiceTransport._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.QueryServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -865,19 +912,37 @@ def test_query_service_base_transport_with_credentials_file(): def test_query_service_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.monitoring_v3.services.query_service.transports.QueryServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.QueryServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_query_service_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) + QueryServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_query_service_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) QueryServiceClient() adc.assert_called_once_with( scopes=( @@ -889,14 +954,45 @@ def test_query_service_auth_adc(): ) -def test_query_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.QueryServiceGrpcTransport, + transports.QueryServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_query_service_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.QueryServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.QueryServiceGrpcTransport, + transports.QueryServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_query_service_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/cloud-platform", @@ -907,12 +1003,129 @@ def test_query_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QueryServiceGrpcTransport, grpc_helpers), + (transports.QueryServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_query_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.QueryServiceGrpcTransport, grpc_helpers), + (transports.QueryServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_query_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.QueryServiceGrpcTransport, grpc_helpers), + (transports.QueryServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_query_service_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( + "monitoring.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.QueryServiceGrpcTransport, transports.QueryServiceGrpcAsyncIOTransport], ) def test_query_service_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: @@ -955,7 +1168,7 @@ def test_query_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_query_service_host_no_port(): client = QueryServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -965,7 +1178,7 @@ def test_query_service_host_no_port(): def test_query_service_host_with_port(): client = QueryServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -1016,9 +1229,9 @@ def test_query_service_transport_channel_mtls_with_client_cert_source(transport_ 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", @@ -1099,7 +1312,6 @@ def test_query_service_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, ) @@ -1120,7 +1332,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = QueryServiceClient.common_folder_path(folder) assert expected == actual @@ -1139,7 +1350,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = QueryServiceClient.common_organization_path(organization) assert expected == actual @@ -1158,7 +1368,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = QueryServiceClient.common_project_path(project) assert expected == actual @@ -1178,7 +1387,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, ) @@ -1205,7 +1413,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.QueryServiceTransport, "_prep_wrapped_messages" ) as prep: client = QueryServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1214,6 +1422,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = QueryServiceClient.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/tests/unit/gapic/monitoring_v3/test_service_monitoring_service.py b/tests/unit/gapic/monitoring_v3/test_service_monitoring_service.py index 74bd82dc..7cf15631 100644 --- a/tests/unit/gapic/monitoring_v3/test_service_monitoring_service.py +++ b/tests/unit/gapic/monitoring_v3/test_service_monitoring_service.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.monitoring_v3.services.service_monitoring_service import ( ServiceMonitoringServiceAsyncClient, @@ -40,13 +39,43 @@ ) from google.cloud.monitoring_v3.services.service_monitoring_service import pagers from google.cloud.monitoring_v3.services.service_monitoring_service import transports +from google.cloud.monitoring_v3.services.service_monitoring_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.service_monitoring_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import service from google.cloud.monitoring_v3.types import service as gm_service from google.cloud.monitoring_v3.types import service_service 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.type import calendar_period_pb2 as calendar_period # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.type import calendar_period_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(): [ServiceMonitoringServiceClient, ServiceMonitoringServiceAsyncClient,], ) def test_service_monitoring_service_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: @@ -117,7 +146,7 @@ def test_service_monitoring_service_client_from_service_account_info(client_clas [ServiceMonitoringServiceClient, ServiceMonitoringServiceAsyncClient,], ) def test_service_monitoring_service_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: @@ -176,7 +205,7 @@ def test_service_monitoring_service_client_client_options( with mock.patch.object( ServiceMonitoringServiceClient, "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() @@ -484,7 +513,7 @@ def test_create_service( transport: str = "grpc", request_type=service_service.CreateServiceRequest ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,21 +526,16 @@ def test_create_service( call.return_value = gm_service.Service( name="name_value", display_name="display_name_value", custom=None, ) - response = client.create_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] == service_service.CreateServiceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gm_service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -523,7 +547,7 @@ def test_create_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -531,7 +555,6 @@ def test_create_service_empty_call(): client.create_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.CreateServiceRequest() @@ -540,7 +563,7 @@ async def test_create_service_async( transport: str = "grpc_asyncio", request_type=service_service.CreateServiceRequest ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -553,20 +576,16 @@ async def test_create_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gm_service.Service(name="name_value", display_name="display_name_value",) ) - response = await client.create_service(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.CreateServiceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gm_service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -577,18 +596,18 @@ async def test_create_service_async_from_dict(): def test_create_service_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.CreateServiceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_service), "__call__") as call: call.return_value = gm_service.Service() - client.create_service(request) # Establish that the underlying gRPC stub method was called. @@ -604,18 +623,18 @@ def test_create_service_field_headers(): @pytest.mark.asyncio async def test_create_service_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.CreateServiceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_service), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gm_service.Service()) - await client.create_service(request) # Establish that the underlying gRPC stub method was called. @@ -630,14 +649,13 @@ async def test_create_service_field_headers_async(): def test_create_service_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gm_service.Service() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_service( @@ -648,15 +666,13 @@ def test_create_service_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].service == gm_service.Service(name="name_value") def test_create_service_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -672,7 +688,7 @@ def test_create_service_flattened_error(): @pytest.mark.asyncio async def test_create_service_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,16 +707,14 @@ async def test_create_service_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].service == gm_service.Service(name="name_value") @pytest.mark.asyncio async def test_create_service_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -717,7 +731,7 @@ def test_get_service( transport: str = "grpc", request_type=service_service.GetServiceRequest ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -730,21 +744,16 @@ def test_get_service( call.return_value = service.Service( name="name_value", display_name="display_name_value", custom=None, ) - 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] == service_service.GetServiceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -756,7 +765,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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -764,7 +773,6 @@ def test_get_service_empty_call(): client.get_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.GetServiceRequest() @@ -773,7 +781,7 @@ async def test_get_service_async( transport: str = "grpc_asyncio", request_type=service_service.GetServiceRequest ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -786,20 +794,16 @@ async def test_get_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.Service(name="name_value", display_name="display_name_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] == service_service.GetServiceRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -810,18 +814,18 @@ async def test_get_service_async_from_dict(): def test_get_service_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.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. @@ -837,18 +841,18 @@ def test_get_service_field_headers(): @pytest.mark.asyncio async def test_get_service_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.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. @@ -863,14 +867,13 @@ async def test_get_service_field_headers_async(): def test_get_service_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. 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() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_service(name="name_value",) @@ -879,13 +882,12 @@ def test_get_service_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_service_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -899,7 +901,7 @@ def test_get_service_flattened_error(): @pytest.mark.asyncio async def test_get_service_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -916,14 +918,13 @@ async def test_get_service_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_service_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -938,7 +939,7 @@ def test_list_services( transport: str = "grpc", request_type=service_service.ListServicesRequest ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -951,19 +952,15 @@ def test_list_services( call.return_value = service_service.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] == service_service.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" @@ -975,7 +972,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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -983,7 +980,6 @@ def test_list_services_empty_call(): client.list_services() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.ListServicesRequest() @@ -992,7 +988,7 @@ async def test_list_services_async( transport: str = "grpc_asyncio", request_type=service_service.ListServicesRequest ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1007,18 +1003,15 @@ async def test_list_services_async( 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] == service_service.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" @@ -1029,18 +1022,18 @@ async def test_list_services_async_from_dict(): def test_list_services_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.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 = service_service.ListServicesResponse() - client.list_services(request) # Establish that the underlying gRPC stub method was called. @@ -1056,12 +1049,13 @@ def test_list_services_field_headers(): @pytest.mark.asyncio async def test_list_services_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.ListServicesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1069,7 +1063,6 @@ async def test_list_services_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service_service.ListServicesResponse() ) - await client.list_services(request) # Establish that the underlying gRPC stub method was called. @@ -1084,14 +1077,13 @@ async def test_list_services_field_headers_async(): def test_list_services_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + 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: # Designate an appropriate return value for the call. call.return_value = service_service.ListServicesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_services(parent="parent_value",) @@ -1100,13 +1092,12 @@ def test_list_services_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_services_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1120,7 +1111,7 @@ def test_list_services_flattened_error(): @pytest.mark.asyncio async def test_list_services_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1139,14 +1130,13 @@ async def test_list_services_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_services_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1159,7 +1149,7 @@ async def test_list_services_flattened_error_async(): def test_list_services_pager(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1195,7 +1185,7 @@ def test_list_services_pager(): def test_list_services_pages(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1223,7 +1213,7 @@ def test_list_services_pages(): @pytest.mark.asyncio async def test_list_services_async_pager(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1258,7 +1248,7 @@ async def test_list_services_async_pager(): @pytest.mark.asyncio async def test_list_services_async_pages(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1291,7 +1281,7 @@ def test_update_service( transport: str = "grpc", request_type=service_service.UpdateServiceRequest ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1304,21 +1294,16 @@ def test_update_service( call.return_value = gm_service.Service( name="name_value", display_name="display_name_value", custom=None, ) - 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] == service_service.UpdateServiceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gm_service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1330,7 +1315,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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1338,7 +1323,6 @@ def test_update_service_empty_call(): client.update_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.UpdateServiceRequest() @@ -1347,7 +1331,7 @@ async def test_update_service_async( transport: str = "grpc_asyncio", request_type=service_service.UpdateServiceRequest ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1360,20 +1344,16 @@ async def test_update_service_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gm_service.Service(name="name_value", display_name="display_name_value",) ) - 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] == service_service.UpdateServiceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gm_service.Service) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1384,18 +1364,18 @@ async def test_update_service_async_from_dict(): def test_update_service_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.UpdateServiceRequest() + request.service.name = "service.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 = gm_service.Service() - client.update_service(request) # Establish that the underlying gRPC stub method was called. @@ -1413,18 +1393,18 @@ def test_update_service_field_headers(): @pytest.mark.asyncio async def test_update_service_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.UpdateServiceRequest() + request.service.name = "service.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 = grpc_helpers_async.FakeUnaryUnaryCall(gm_service.Service()) - await client.update_service(request) # Establish that the underlying gRPC stub method was called. @@ -1441,14 +1421,13 @@ async def test_update_service_field_headers_async(): def test_update_service_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gm_service.Service() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_service(service=gm_service.Service(name="name_value"),) @@ -1457,13 +1436,12 @@ def test_update_service_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].service == gm_service.Service(name="name_value") def test_update_service_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1478,7 +1456,7 @@ def test_update_service_flattened_error(): @pytest.mark.asyncio async def test_update_service_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1497,14 +1475,13 @@ async def test_update_service_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].service == gm_service.Service(name="name_value") @pytest.mark.asyncio async def test_update_service_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1520,7 +1497,7 @@ def test_delete_service( transport: str = "grpc", request_type=service_service.DeleteServiceRequest ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1531,13 +1508,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 = None - 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] == service_service.DeleteServiceRequest() # Establish that the response is the type that we expect. @@ -1552,7 +1527,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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1560,7 +1535,6 @@ def test_delete_service_empty_call(): client.delete_service() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.DeleteServiceRequest() @@ -1569,7 +1543,7 @@ async def test_delete_service_async( transport: str = "grpc_asyncio", request_type=service_service.DeleteServiceRequest ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1580,13 +1554,11 @@ async def test_delete_service_async( with mock.patch.object(type(client.transport.delete_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - 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] == service_service.DeleteServiceRequest() # Establish that the response is the type that we expect. @@ -1600,18 +1572,18 @@ async def test_delete_service_async_from_dict(): def test_delete_service_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.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 = None - client.delete_service(request) # Establish that the underlying gRPC stub method was called. @@ -1627,18 +1599,18 @@ def test_delete_service_field_headers(): @pytest.mark.asyncio async def test_delete_service_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.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 = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_service(request) # Establish that the underlying gRPC stub method was called. @@ -1653,14 +1625,13 @@ async def test_delete_service_field_headers_async(): def test_delete_service_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_service), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_service(name="name_value",) @@ -1669,13 +1640,12 @@ def test_delete_service_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_service_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1689,7 +1659,7 @@ def test_delete_service_flattened_error(): @pytest.mark.asyncio async def test_delete_service_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1706,14 +1676,13 @@ async def test_delete_service_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_service_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1729,7 +1698,7 @@ def test_create_service_level_objective( request_type=service_service.CreateServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1745,25 +1714,19 @@ def test_create_service_level_objective( name="name_value", display_name="display_name_value", goal=0.419, - rolling_period=duration.Duration(seconds=751), + rolling_period=duration_pb2.Duration(seconds=751), ) - response = client.create_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service_service.CreateServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. - assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -1775,7 +1738,7 @@ def test_create_service_level_objective_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1785,7 +1748,6 @@ def test_create_service_level_objective_empty_call(): client.create_service_level_objective() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.CreateServiceLevelObjectiveRequest() @@ -1795,7 +1757,7 @@ async def test_create_service_level_objective_async( request_type=service_service.CreateServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1812,22 +1774,17 @@ async def test_create_service_level_objective_async( name="name_value", display_name="display_name_value", goal=0.419, ) ) - response = await client.create_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.CreateServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -1838,12 +1795,13 @@ async def test_create_service_level_objective_async_from_dict(): def test_create_service_level_objective_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.CreateServiceLevelObjectiveRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1851,7 +1809,6 @@ def test_create_service_level_objective_field_headers(): type(client.transport.create_service_level_objective), "__call__" ) as call: call.return_value = service.ServiceLevelObjective() - client.create_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -1867,12 +1824,13 @@ def test_create_service_level_objective_field_headers(): @pytest.mark.asyncio async def test_create_service_level_objective_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.CreateServiceLevelObjectiveRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1882,7 +1840,6 @@ async def test_create_service_level_objective_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ServiceLevelObjective() ) - await client.create_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -1897,7 +1854,7 @@ async def test_create_service_level_objective_field_headers_async(): def test_create_service_level_objective_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1906,7 +1863,6 @@ def test_create_service_level_objective_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = service.ServiceLevelObjective() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_service_level_objective( @@ -1918,9 +1874,7 @@ def test_create_service_level_objective_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].service_level_objective == service.ServiceLevelObjective( name="name_value" ) @@ -1928,7 +1882,7 @@ def test_create_service_level_objective_flattened(): def test_create_service_level_objective_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1944,7 +1898,7 @@ def test_create_service_level_objective_flattened_error(): @pytest.mark.asyncio async def test_create_service_level_objective_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1968,9 +1922,7 @@ async def test_create_service_level_objective_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].service_level_objective == service.ServiceLevelObjective( name="name_value" ) @@ -1979,7 +1931,7 @@ async def test_create_service_level_objective_flattened_async(): @pytest.mark.asyncio async def test_create_service_level_objective_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1997,7 +1949,7 @@ def test_get_service_level_objective( request_type=service_service.GetServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,25 +1965,19 @@ def test_get_service_level_objective( name="name_value", display_name="display_name_value", goal=0.419, - rolling_period=duration.Duration(seconds=751), + rolling_period=duration_pb2.Duration(seconds=751), ) - response = client.get_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service_service.GetServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. - assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -2043,7 +1989,7 @@ def test_get_service_level_objective_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2053,7 +1999,6 @@ def test_get_service_level_objective_empty_call(): client.get_service_level_objective() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.GetServiceLevelObjectiveRequest() @@ -2063,7 +2008,7 @@ async def test_get_service_level_objective_async( request_type=service_service.GetServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2080,22 +2025,17 @@ async def test_get_service_level_objective_async( name="name_value", display_name="display_name_value", goal=0.419, ) ) - response = await client.get_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.GetServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -2106,12 +2046,13 @@ async def test_get_service_level_objective_async_from_dict(): def test_get_service_level_objective_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.GetServiceLevelObjectiveRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2119,7 +2060,6 @@ def test_get_service_level_objective_field_headers(): type(client.transport.get_service_level_objective), "__call__" ) as call: call.return_value = service.ServiceLevelObjective() - client.get_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -2135,12 +2075,13 @@ def test_get_service_level_objective_field_headers(): @pytest.mark.asyncio async def test_get_service_level_objective_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.GetServiceLevelObjectiveRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2150,7 +2091,6 @@ async def test_get_service_level_objective_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ServiceLevelObjective() ) - await client.get_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -2165,7 +2105,7 @@ async def test_get_service_level_objective_field_headers_async(): def test_get_service_level_objective_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2174,7 +2114,6 @@ def test_get_service_level_objective_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = service.ServiceLevelObjective() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_service_level_objective(name="name_value",) @@ -2183,13 +2122,12 @@ def test_get_service_level_objective_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_service_level_objective_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2203,7 +2141,7 @@ def test_get_service_level_objective_flattened_error(): @pytest.mark.asyncio async def test_get_service_level_objective_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2224,14 +2162,13 @@ async def test_get_service_level_objective_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_service_level_objective_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2247,7 +2184,7 @@ def test_list_service_level_objectives( request_type=service_service.ListServiceLevelObjectivesRequest, ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2262,19 +2199,15 @@ def test_list_service_level_objectives( call.return_value = service_service.ListServiceLevelObjectivesResponse( next_page_token="next_page_token_value", ) - response = client.list_service_level_objectives(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service_service.ListServiceLevelObjectivesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceLevelObjectivesPager) - assert response.next_page_token == "next_page_token_value" @@ -2286,7 +2219,7 @@ def test_list_service_level_objectives_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2296,7 +2229,6 @@ def test_list_service_level_objectives_empty_call(): client.list_service_level_objectives() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.ListServiceLevelObjectivesRequest() @@ -2306,7 +2238,7 @@ async def test_list_service_level_objectives_async( request_type=service_service.ListServiceLevelObjectivesRequest, ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2323,18 +2255,15 @@ async def test_list_service_level_objectives_async( next_page_token="next_page_token_value", ) ) - response = await client.list_service_level_objectives(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.ListServiceLevelObjectivesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListServiceLevelObjectivesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2345,12 +2274,13 @@ async def test_list_service_level_objectives_async_from_dict(): def test_list_service_level_objectives_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.ListServiceLevelObjectivesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2358,7 +2288,6 @@ def test_list_service_level_objectives_field_headers(): type(client.transport.list_service_level_objectives), "__call__" ) as call: call.return_value = service_service.ListServiceLevelObjectivesResponse() - client.list_service_level_objectives(request) # Establish that the underlying gRPC stub method was called. @@ -2374,12 +2303,13 @@ def test_list_service_level_objectives_field_headers(): @pytest.mark.asyncio async def test_list_service_level_objectives_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.ListServiceLevelObjectivesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2389,7 +2319,6 @@ async def test_list_service_level_objectives_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service_service.ListServiceLevelObjectivesResponse() ) - await client.list_service_level_objectives(request) # Establish that the underlying gRPC stub method was called. @@ -2404,7 +2333,7 @@ async def test_list_service_level_objectives_field_headers_async(): def test_list_service_level_objectives_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2413,7 +2342,6 @@ def test_list_service_level_objectives_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = service_service.ListServiceLevelObjectivesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_service_level_objectives(parent="parent_value",) @@ -2422,13 +2350,12 @@ def test_list_service_level_objectives_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_service_level_objectives_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2442,7 +2369,7 @@ def test_list_service_level_objectives_flattened_error(): @pytest.mark.asyncio async def test_list_service_level_objectives_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2463,14 +2390,13 @@ async def test_list_service_level_objectives_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_service_level_objectives_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2483,7 +2409,7 @@ async def test_list_service_level_objectives_flattened_error_async(): def test_list_service_level_objectives_pager(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2531,7 +2457,7 @@ def test_list_service_level_objectives_pager(): def test_list_service_level_objectives_pages(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2571,7 +2497,7 @@ def test_list_service_level_objectives_pages(): @pytest.mark.asyncio async def test_list_service_level_objectives_async_pager(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2618,7 +2544,7 @@ async def test_list_service_level_objectives_async_pager(): @pytest.mark.asyncio async def test_list_service_level_objectives_async_pages(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2666,7 +2592,7 @@ def test_update_service_level_objective( request_type=service_service.UpdateServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2682,25 +2608,19 @@ def test_update_service_level_objective( name="name_value", display_name="display_name_value", goal=0.419, - rolling_period=duration.Duration(seconds=751), + rolling_period=duration_pb2.Duration(seconds=751), ) - response = client.update_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service_service.UpdateServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. - assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -2712,7 +2632,7 @@ def test_update_service_level_objective_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2722,7 +2642,6 @@ def test_update_service_level_objective_empty_call(): client.update_service_level_objective() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.UpdateServiceLevelObjectiveRequest() @@ -2732,7 +2651,7 @@ async def test_update_service_level_objective_async( request_type=service_service.UpdateServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2749,22 +2668,17 @@ async def test_update_service_level_objective_async( name="name_value", display_name="display_name_value", goal=0.419, ) ) - response = await client.update_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.UpdateServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.ServiceLevelObjective) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert math.isclose(response.goal, 0.419, rel_tol=1e-6) @@ -2775,12 +2689,13 @@ async def test_update_service_level_objective_async_from_dict(): def test_update_service_level_objective_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.UpdateServiceLevelObjectiveRequest() + request.service_level_objective.name = "service_level_objective.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2788,7 +2703,6 @@ def test_update_service_level_objective_field_headers(): type(client.transport.update_service_level_objective), "__call__" ) as call: call.return_value = service.ServiceLevelObjective() - client.update_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -2807,12 +2721,13 @@ def test_update_service_level_objective_field_headers(): @pytest.mark.asyncio async def test_update_service_level_objective_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.UpdateServiceLevelObjectiveRequest() + request.service_level_objective.name = "service_level_objective.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2822,7 +2737,6 @@ async def test_update_service_level_objective_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ServiceLevelObjective() ) - await client.update_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -2840,7 +2754,7 @@ async def test_update_service_level_objective_field_headers_async(): def test_update_service_level_objective_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2849,7 +2763,6 @@ def test_update_service_level_objective_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = service.ServiceLevelObjective() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_service_level_objective( @@ -2860,7 +2773,6 @@ def test_update_service_level_objective_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].service_level_objective == service.ServiceLevelObjective( name="name_value" ) @@ -2868,7 +2780,7 @@ def test_update_service_level_objective_flattened(): def test_update_service_level_objective_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2883,7 +2795,7 @@ def test_update_service_level_objective_flattened_error(): @pytest.mark.asyncio async def test_update_service_level_objective_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2906,7 +2818,6 @@ async def test_update_service_level_objective_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].service_level_objective == service.ServiceLevelObjective( name="name_value" ) @@ -2915,7 +2826,7 @@ async def test_update_service_level_objective_flattened_async(): @pytest.mark.asyncio async def test_update_service_level_objective_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2932,7 +2843,7 @@ def test_delete_service_level_objective( request_type=service_service.DeleteServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2945,13 +2856,11 @@ def test_delete_service_level_objective( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service_service.DeleteServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. @@ -2966,7 +2875,7 @@ def test_delete_service_level_objective_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 = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2976,7 +2885,6 @@ def test_delete_service_level_objective_empty_call(): client.delete_service_level_objective() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service_service.DeleteServiceLevelObjectiveRequest() @@ -2986,7 +2894,7 @@ async def test_delete_service_level_objective_async( request_type=service_service.DeleteServiceLevelObjectiveRequest, ): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2999,13 +2907,11 @@ async def test_delete_service_level_objective_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_service_level_objective(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service_service.DeleteServiceLevelObjectiveRequest() # Establish that the response is the type that we expect. @@ -3019,12 +2925,13 @@ async def test_delete_service_level_objective_async_from_dict(): def test_delete_service_level_objective_field_headers(): client = ServiceMonitoringServiceClient( - 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 = service_service.DeleteServiceLevelObjectiveRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3032,7 +2939,6 @@ def test_delete_service_level_objective_field_headers(): type(client.transport.delete_service_level_objective), "__call__" ) as call: call.return_value = None - client.delete_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -3048,12 +2954,13 @@ def test_delete_service_level_objective_field_headers(): @pytest.mark.asyncio async def test_delete_service_level_objective_field_headers_async(): client = ServiceMonitoringServiceAsyncClient( - 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 = service_service.DeleteServiceLevelObjectiveRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3061,7 +2968,6 @@ async def test_delete_service_level_objective_field_headers_async(): type(client.transport.delete_service_level_objective), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_service_level_objective(request) # Establish that the underlying gRPC stub method was called. @@ -3076,7 +2982,7 @@ async def test_delete_service_level_objective_field_headers_async(): def test_delete_service_level_objective_flattened(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3085,7 +2991,6 @@ def test_delete_service_level_objective_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_service_level_objective(name="name_value",) @@ -3094,13 +2999,12 @@ def test_delete_service_level_objective_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_service_level_objective_flattened_error(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3114,7 +3018,7 @@ def test_delete_service_level_objective_flattened_error(): @pytest.mark.asyncio async def test_delete_service_level_objective_flattened_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3133,14 +3037,13 @@ async def test_delete_service_level_objective_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_service_level_objective_flattened_error_async(): client = ServiceMonitoringServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -3154,16 +3057,16 @@ async def test_delete_service_level_objective_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ServiceMonitoringServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServiceMonitoringServiceClient( - 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.ServiceMonitoringServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServiceMonitoringServiceClient( @@ -3173,7 +3076,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ServiceMonitoringServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ServiceMonitoringServiceClient( @@ -3184,7 +3087,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ServiceMonitoringServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ServiceMonitoringServiceClient(transport=transport) assert client.transport is transport @@ -3193,13 +3096,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ServiceMonitoringServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ServiceMonitoringServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3214,8 +3117,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() @@ -3223,7 +3126,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.ServiceMonitoringServiceGrpcTransport, @@ -3232,9 +3135,9 @@ def test_transport_grpc_default(): def test_service_monitoring_service_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.ServiceMonitoringServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3246,7 +3149,7 @@ def test_service_monitoring_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ServiceMonitoringServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3268,15 +3171,41 @@ def test_service_monitoring_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_service_monitoring_service_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.monitoring_v3.services.service_monitoring_service.transports.ServiceMonitoringServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServiceMonitoringServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_service_monitoring_service_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.monitoring_v3.services.service_monitoring_service.transports.ServiceMonitoringServiceTransport._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.ServiceMonitoringServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3293,19 +3222,37 @@ def test_service_monitoring_service_base_transport_with_credentials_file(): def test_service_monitoring_service_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.monitoring_v3.services.service_monitoring_service.transports.ServiceMonitoringServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ServiceMonitoringServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_service_monitoring_service_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) + ServiceMonitoringServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_service_monitoring_service_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) ServiceMonitoringServiceClient() adc.assert_called_once_with( scopes=( @@ -3317,14 +3264,45 @@ def test_service_monitoring_service_auth_adc(): ) -def test_service_monitoring_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceMonitoringServiceGrpcTransport, + transports.ServiceMonitoringServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_service_monitoring_service_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.ServiceMonitoringServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServiceMonitoringServiceGrpcTransport, + transports.ServiceMonitoringServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_service_monitoring_service_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/cloud-platform", @@ -3335,6 +3313,125 @@ def test_service_monitoring_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServiceMonitoringServiceGrpcTransport, grpc_helpers), + (transports.ServiceMonitoringServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_service_monitoring_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.ServiceMonitoringServiceGrpcTransport, grpc_helpers), + (transports.ServiceMonitoringServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_service_monitoring_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServiceMonitoringServiceGrpcTransport, grpc_helpers), + (transports.ServiceMonitoringServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_service_monitoring_service_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( + "monitoring.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", [ @@ -3345,7 +3442,7 @@ def test_service_monitoring_service_transport_auth_adc(): def test_service_monitoring_service_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: @@ -3388,7 +3485,7 @@ def test_service_monitoring_service_grpc_transport_client_cert_source_for_mtls( def test_service_monitoring_service_host_no_port(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -3398,7 +3495,7 @@ def test_service_monitoring_service_host_no_port(): def test_service_monitoring_service_host_with_port(): client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -3454,9 +3551,9 @@ def test_service_monitoring_service_transport_channel_mtls_with_client_cert_sour 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", @@ -3541,7 +3638,6 @@ def test_service_monitoring_service_transport_channel_mtls_with_adc(transport_cl def test_service_path(): project = "squid" service = "clam" - expected = "projects/{project}/services/{service}".format( project=project, service=service, ) @@ -3565,7 +3661,6 @@ def test_service_level_objective_path(): project = "oyster" service = "nudibranch" service_level_objective = "cuttlefish" - expected = "projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}".format( project=project, service=service, @@ -3592,7 +3687,6 @@ def test_parse_service_level_objective_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3613,7 +3707,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = ServiceMonitoringServiceClient.common_folder_path(folder) assert expected == actual @@ -3632,7 +3725,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = ServiceMonitoringServiceClient.common_organization_path(organization) assert expected == actual @@ -3651,7 +3743,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = ServiceMonitoringServiceClient.common_project_path(project) assert expected == actual @@ -3671,7 +3762,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3698,7 +3788,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ServiceMonitoringServiceTransport, "_prep_wrapped_messages" ) as prep: client = ServiceMonitoringServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3707,6 +3797,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ServiceMonitoringServiceClient.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/tests/unit/gapic/monitoring_v3/test_uptime_check_service.py b/tests/unit/gapic/monitoring_v3/test_uptime_check_service.py index 2d757678..63b1bd7b 100644 --- a/tests/unit/gapic/monitoring_v3/test_uptime_check_service.py +++ b/tests/unit/gapic/monitoring_v3/test_uptime_check_service.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,14 +23,14 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth -from google.api import monitored_resource_pb2 as monitored_resource # type: ignore + +from google.api import monitored_resource_pb2 # type: ignore 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.monitoring_v3.services.uptime_check_service import ( UptimeCheckServiceAsyncClient, @@ -41,11 +40,41 @@ ) from google.cloud.monitoring_v3.services.uptime_check_service import pagers from google.cloud.monitoring_v3.services.uptime_check_service import transports +from google.cloud.monitoring_v3.services.uptime_check_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.monitoring_v3.services.uptime_check_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.monitoring_v3.types import uptime from google.cloud.monitoring_v3.types import uptime_service 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(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): "client_class", [UptimeCheckServiceClient, UptimeCheckServiceAsyncClient,] ) def test_uptime_check_service_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: @@ -114,7 +143,7 @@ def test_uptime_check_service_client_from_service_account_info(client_class): "client_class", [UptimeCheckServiceClient, UptimeCheckServiceAsyncClient,] ) def test_uptime_check_service_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: @@ -167,7 +196,7 @@ def test_uptime_check_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(UptimeCheckServiceClient, "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() @@ -465,7 +494,7 @@ def test_list_uptime_check_configs( transport: str = "grpc", request_type=uptime_service.ListUptimeCheckConfigsRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -480,21 +509,16 @@ def test_list_uptime_check_configs( call.return_value = uptime_service.ListUptimeCheckConfigsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_uptime_check_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckConfigsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUptimeCheckConfigsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -506,7 +530,7 @@ def test_list_uptime_check_configs_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 = UptimeCheckServiceClient( - 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 +540,6 @@ def test_list_uptime_check_configs_empty_call(): client.list_uptime_check_configs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckConfigsRequest() @@ -526,7 +549,7 @@ async def test_list_uptime_check_configs_async( request_type=uptime_service.ListUptimeCheckConfigsRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,20 +566,16 @@ async def test_list_uptime_check_configs_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_uptime_check_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckConfigsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListUptimeCheckConfigsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -566,11 +585,14 @@ async def test_list_uptime_check_configs_async_from_dict(): def test_list_uptime_check_configs_field_headers(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + 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 = uptime_service.ListUptimeCheckConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -578,7 +600,6 @@ def test_list_uptime_check_configs_field_headers(): type(client.transport.list_uptime_check_configs), "__call__" ) as call: call.return_value = uptime_service.ListUptimeCheckConfigsResponse() - client.list_uptime_check_configs(request) # Establish that the underlying gRPC stub method was called. @@ -594,12 +615,13 @@ def test_list_uptime_check_configs_field_headers(): @pytest.mark.asyncio async def test_list_uptime_check_configs_field_headers_async(): client = UptimeCheckServiceAsyncClient( - 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 = uptime_service.ListUptimeCheckConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -609,7 +631,6 @@ async def test_list_uptime_check_configs_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( uptime_service.ListUptimeCheckConfigsResponse() ) - await client.list_uptime_check_configs(request) # Establish that the underlying gRPC stub method was called. @@ -623,7 +644,9 @@ async def test_list_uptime_check_configs_field_headers_async(): def test_list_uptime_check_configs_flattened(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -631,7 +654,6 @@ def test_list_uptime_check_configs_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = uptime_service.ListUptimeCheckConfigsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_uptime_check_configs(parent="parent_value",) @@ -640,12 +662,13 @@ def test_list_uptime_check_configs_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_uptime_check_configs_flattened_error(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -658,7 +681,7 @@ def test_list_uptime_check_configs_flattened_error(): @pytest.mark.asyncio async def test_list_uptime_check_configs_flattened_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -679,14 +702,13 @@ async def test_list_uptime_check_configs_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_uptime_check_configs_flattened_error_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -698,7 +720,7 @@ async def test_list_uptime_check_configs_flattened_error_async(): def test_list_uptime_check_configs_pager(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials,) + client = UptimeCheckServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +766,7 @@ def test_list_uptime_check_configs_pager(): def test_list_uptime_check_configs_pages(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials,) + client = UptimeCheckServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -783,7 +805,7 @@ def test_list_uptime_check_configs_pages(): @pytest.mark.asyncio async def test_list_uptime_check_configs_async_pager(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -830,7 +852,7 @@ async def test_list_uptime_check_configs_async_pager(): @pytest.mark.asyncio async def test_list_uptime_check_configs_async_pages(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -875,7 +897,7 @@ def test_get_uptime_check_config( transport: str = "grpc", request_type=uptime_service.GetUptimeCheckConfigRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -892,30 +914,25 @@ def test_get_uptime_check_config( display_name="display_name_value", selected_regions=[uptime.UptimeCheckRegion.USA], is_internal=True, - monitored_resource=monitored_resource.MonitoredResource(type="type_value"), + monitored_resource=monitored_resource_pb2.MonitoredResource( + type="type_value" + ), http_check=uptime.UptimeCheckConfig.HttpCheck( request_method=uptime.UptimeCheckConfig.HttpCheck.RequestMethod.GET ), ) - response = client.get_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.GetUptimeCheckConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -927,7 +944,7 @@ def test_get_uptime_check_config_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 = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -937,7 +954,6 @@ def test_get_uptime_check_config_empty_call(): client.get_uptime_check_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.GetUptimeCheckConfigRequest() @@ -947,7 +963,7 @@ async def test_get_uptime_check_config_async( request_type=uptime_service.GetUptimeCheckConfigRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,24 +983,18 @@ async def test_get_uptime_check_config_async( is_internal=True, ) ) - response = await client.get_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.GetUptimeCheckConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -994,11 +1004,14 @@ async def test_get_uptime_check_config_async_from_dict(): def test_get_uptime_check_config_field_headers(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + 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 = uptime_service.GetUptimeCheckConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1006,7 +1019,6 @@ def test_get_uptime_check_config_field_headers(): type(client.transport.get_uptime_check_config), "__call__" ) as call: call.return_value = uptime.UptimeCheckConfig() - client.get_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1022,12 +1034,13 @@ def test_get_uptime_check_config_field_headers(): @pytest.mark.asyncio async def test_get_uptime_check_config_field_headers_async(): client = UptimeCheckServiceAsyncClient( - 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 = uptime_service.GetUptimeCheckConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1037,7 +1050,6 @@ async def test_get_uptime_check_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( uptime.UptimeCheckConfig() ) - await client.get_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1051,7 +1063,9 @@ async def test_get_uptime_check_config_field_headers_async(): def test_get_uptime_check_config_flattened(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1059,7 +1073,6 @@ def test_get_uptime_check_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = uptime.UptimeCheckConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_uptime_check_config(name="name_value",) @@ -1068,12 +1081,13 @@ def test_get_uptime_check_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_uptime_check_config_flattened_error(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1086,7 +1100,7 @@ def test_get_uptime_check_config_flattened_error(): @pytest.mark.asyncio async def test_get_uptime_check_config_flattened_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1107,14 +1121,13 @@ async def test_get_uptime_check_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_uptime_check_config_flattened_error_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1129,7 +1142,7 @@ def test_create_uptime_check_config( transport: str = "grpc", request_type=uptime_service.CreateUptimeCheckConfigRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1146,30 +1159,25 @@ def test_create_uptime_check_config( display_name="display_name_value", selected_regions=[uptime.UptimeCheckRegion.USA], is_internal=True, - monitored_resource=monitored_resource.MonitoredResource(type="type_value"), + monitored_resource=monitored_resource_pb2.MonitoredResource( + type="type_value" + ), http_check=uptime.UptimeCheckConfig.HttpCheck( request_method=uptime.UptimeCheckConfig.HttpCheck.RequestMethod.GET ), ) - response = client.create_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.CreateUptimeCheckConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -1181,7 +1189,7 @@ def test_create_uptime_check_config_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 = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1191,7 +1199,6 @@ def test_create_uptime_check_config_empty_call(): client.create_uptime_check_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.CreateUptimeCheckConfigRequest() @@ -1201,7 +1208,7 @@ async def test_create_uptime_check_config_async( request_type=uptime_service.CreateUptimeCheckConfigRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1221,24 +1228,18 @@ async def test_create_uptime_check_config_async( is_internal=True, ) ) - response = await client.create_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.CreateUptimeCheckConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -1248,11 +1249,14 @@ async def test_create_uptime_check_config_async_from_dict(): def test_create_uptime_check_config_field_headers(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + 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 = uptime_service.CreateUptimeCheckConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1260,7 +1264,6 @@ def test_create_uptime_check_config_field_headers(): type(client.transport.create_uptime_check_config), "__call__" ) as call: call.return_value = uptime.UptimeCheckConfig() - client.create_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1276,12 +1279,13 @@ def test_create_uptime_check_config_field_headers(): @pytest.mark.asyncio async def test_create_uptime_check_config_field_headers_async(): client = UptimeCheckServiceAsyncClient( - 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 = uptime_service.CreateUptimeCheckConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1291,7 +1295,6 @@ async def test_create_uptime_check_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( uptime.UptimeCheckConfig() ) - await client.create_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1305,7 +1308,9 @@ async def test_create_uptime_check_config_field_headers_async(): def test_create_uptime_check_config_flattened(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,7 +1318,6 @@ def test_create_uptime_check_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = uptime.UptimeCheckConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_uptime_check_config( @@ -1325,16 +1329,16 @@ def test_create_uptime_check_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].uptime_check_config == uptime.UptimeCheckConfig( name="name_value" ) def test_create_uptime_check_config_flattened_error(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1349,7 +1353,7 @@ def test_create_uptime_check_config_flattened_error(): @pytest.mark.asyncio async def test_create_uptime_check_config_flattened_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1373,9 +1377,7 @@ async def test_create_uptime_check_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].uptime_check_config == uptime.UptimeCheckConfig( name="name_value" ) @@ -1384,7 +1386,7 @@ async def test_create_uptime_check_config_flattened_async(): @pytest.mark.asyncio async def test_create_uptime_check_config_flattened_error_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1401,7 +1403,7 @@ def test_update_uptime_check_config( transport: str = "grpc", request_type=uptime_service.UpdateUptimeCheckConfigRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1418,30 +1420,25 @@ def test_update_uptime_check_config( display_name="display_name_value", selected_regions=[uptime.UptimeCheckRegion.USA], is_internal=True, - monitored_resource=monitored_resource.MonitoredResource(type="type_value"), + monitored_resource=monitored_resource_pb2.MonitoredResource( + type="type_value" + ), http_check=uptime.UptimeCheckConfig.HttpCheck( request_method=uptime.UptimeCheckConfig.HttpCheck.RequestMethod.GET ), ) - response = client.update_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.UpdateUptimeCheckConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -1453,7 +1450,7 @@ def test_update_uptime_check_config_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 = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1463,7 +1460,6 @@ def test_update_uptime_check_config_empty_call(): client.update_uptime_check_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.UpdateUptimeCheckConfigRequest() @@ -1473,7 +1469,7 @@ async def test_update_uptime_check_config_async( request_type=uptime_service.UpdateUptimeCheckConfigRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1493,24 +1489,18 @@ async def test_update_uptime_check_config_async( is_internal=True, ) ) - response = await client.update_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.UpdateUptimeCheckConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, uptime.UptimeCheckConfig) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.selected_regions == [uptime.UptimeCheckRegion.USA] - assert response.is_internal is True @@ -1520,11 +1510,14 @@ async def test_update_uptime_check_config_async_from_dict(): def test_update_uptime_check_config_field_headers(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + 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 = uptime_service.UpdateUptimeCheckConfigRequest() + request.uptime_check_config.name = "uptime_check_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,7 +1525,6 @@ def test_update_uptime_check_config_field_headers(): type(client.transport.update_uptime_check_config), "__call__" ) as call: call.return_value = uptime.UptimeCheckConfig() - client.update_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1551,12 +1543,13 @@ def test_update_uptime_check_config_field_headers(): @pytest.mark.asyncio async def test_update_uptime_check_config_field_headers_async(): client = UptimeCheckServiceAsyncClient( - 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 = uptime_service.UpdateUptimeCheckConfigRequest() + request.uptime_check_config.name = "uptime_check_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1566,7 +1559,6 @@ async def test_update_uptime_check_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( uptime.UptimeCheckConfig() ) - await client.update_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1583,7 +1575,9 @@ async def test_update_uptime_check_config_field_headers_async(): def test_update_uptime_check_config_flattened(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1591,7 +1585,6 @@ def test_update_uptime_check_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = uptime.UptimeCheckConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_uptime_check_config( @@ -1602,14 +1595,15 @@ def test_update_uptime_check_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].uptime_check_config == uptime.UptimeCheckConfig( name="name_value" ) def test_update_uptime_check_config_flattened_error(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1623,7 +1617,7 @@ def test_update_uptime_check_config_flattened_error(): @pytest.mark.asyncio async def test_update_uptime_check_config_flattened_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1646,7 +1640,6 @@ async def test_update_uptime_check_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].uptime_check_config == uptime.UptimeCheckConfig( name="name_value" ) @@ -1655,7 +1648,7 @@ async def test_update_uptime_check_config_flattened_async(): @pytest.mark.asyncio async def test_update_uptime_check_config_flattened_error_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1671,7 +1664,7 @@ def test_delete_uptime_check_config( transport: str = "grpc", request_type=uptime_service.DeleteUptimeCheckConfigRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1684,13 +1677,11 @@ def test_delete_uptime_check_config( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.DeleteUptimeCheckConfigRequest() # Establish that the response is the type that we expect. @@ -1705,7 +1696,7 @@ def test_delete_uptime_check_config_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 = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1715,7 +1706,6 @@ def test_delete_uptime_check_config_empty_call(): client.delete_uptime_check_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.DeleteUptimeCheckConfigRequest() @@ -1725,7 +1715,7 @@ async def test_delete_uptime_check_config_async( request_type=uptime_service.DeleteUptimeCheckConfigRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1738,13 +1728,11 @@ async def test_delete_uptime_check_config_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.DeleteUptimeCheckConfigRequest() # Establish that the response is the type that we expect. @@ -1757,11 +1745,14 @@ async def test_delete_uptime_check_config_async_from_dict(): def test_delete_uptime_check_config_field_headers(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + 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 = uptime_service.DeleteUptimeCheckConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1769,7 +1760,6 @@ def test_delete_uptime_check_config_field_headers(): type(client.transport.delete_uptime_check_config), "__call__" ) as call: call.return_value = None - client.delete_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1785,12 +1775,13 @@ def test_delete_uptime_check_config_field_headers(): @pytest.mark.asyncio async def test_delete_uptime_check_config_field_headers_async(): client = UptimeCheckServiceAsyncClient( - 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 = uptime_service.DeleteUptimeCheckConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1798,7 +1789,6 @@ async def test_delete_uptime_check_config_field_headers_async(): type(client.transport.delete_uptime_check_config), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_uptime_check_config(request) # Establish that the underlying gRPC stub method was called. @@ -1812,7 +1802,9 @@ async def test_delete_uptime_check_config_field_headers_async(): def test_delete_uptime_check_config_flattened(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1820,7 +1812,6 @@ def test_delete_uptime_check_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_uptime_check_config(name="name_value",) @@ -1829,12 +1820,13 @@ def test_delete_uptime_check_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_uptime_check_config_flattened_error(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1847,7 +1839,7 @@ def test_delete_uptime_check_config_flattened_error(): @pytest.mark.asyncio async def test_delete_uptime_check_config_flattened_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1866,14 +1858,13 @@ async def test_delete_uptime_check_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_uptime_check_config_flattened_error_async(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1888,7 +1879,7 @@ def test_list_uptime_check_ips( transport: str = "grpc", request_type=uptime_service.ListUptimeCheckIpsRequest ): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1903,19 +1894,15 @@ def test_list_uptime_check_ips( call.return_value = uptime_service.ListUptimeCheckIpsResponse( next_page_token="next_page_token_value", ) - response = client.list_uptime_check_ips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckIpsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUptimeCheckIpsPager) - assert response.next_page_token == "next_page_token_value" @@ -1927,7 +1914,7 @@ def test_list_uptime_check_ips_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 = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1937,7 +1924,6 @@ def test_list_uptime_check_ips_empty_call(): client.list_uptime_check_ips() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckIpsRequest() @@ -1947,7 +1933,7 @@ async def test_list_uptime_check_ips_async( request_type=uptime_service.ListUptimeCheckIpsRequest, ): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1964,18 +1950,15 @@ async def test_list_uptime_check_ips_async( next_page_token="next_page_token_value", ) ) - response = await client.list_uptime_check_ips(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == uptime_service.ListUptimeCheckIpsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListUptimeCheckIpsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1985,7 +1968,7 @@ async def test_list_uptime_check_ips_async_from_dict(): def test_list_uptime_check_ips_pager(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials,) + client = UptimeCheckServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2024,7 +2007,7 @@ def test_list_uptime_check_ips_pager(): def test_list_uptime_check_ips_pages(): - client = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials,) + client = UptimeCheckServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2059,7 +2042,7 @@ def test_list_uptime_check_ips_pages(): @pytest.mark.asyncio async def test_list_uptime_check_ips_async_pager(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2102,7 +2085,7 @@ async def test_list_uptime_check_ips_async_pager(): @pytest.mark.asyncio async def test_list_uptime_check_ips_async_pages(): client = UptimeCheckServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2142,16 +2125,16 @@ async def test_list_uptime_check_ips_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.UptimeCheckServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UptimeCheckServiceClient( - 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.UptimeCheckServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UptimeCheckServiceClient( @@ -2161,7 +2144,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.UptimeCheckServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UptimeCheckServiceClient( @@ -2172,7 +2155,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.UptimeCheckServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = UptimeCheckServiceClient(transport=transport) assert client.transport is transport @@ -2181,13 +2164,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.UptimeCheckServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.UptimeCheckServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2202,23 +2185,25 @@ 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 = UptimeCheckServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UptimeCheckServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.UptimeCheckServiceGrpcTransport,) def test_uptime_check_service_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.UptimeCheckServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2230,7 +2215,7 @@ def test_uptime_check_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.UptimeCheckServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2248,15 +2233,41 @@ def test_uptime_check_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_uptime_check_service_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.monitoring_v3.services.uptime_check_service.transports.UptimeCheckServiceTransport._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.UptimeCheckServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_uptime_check_service_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.monitoring_v3.services.uptime_check_service.transports.UptimeCheckServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UptimeCheckServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2273,19 +2284,37 @@ def test_uptime_check_service_base_transport_with_credentials_file(): def test_uptime_check_service_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.monitoring_v3.services.uptime_check_service.transports.UptimeCheckServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UptimeCheckServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_uptime_check_service_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) + UptimeCheckServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_uptime_check_service_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) UptimeCheckServiceClient() adc.assert_called_once_with( scopes=( @@ -2297,14 +2326,45 @@ def test_uptime_check_service_auth_adc(): ) -def test_uptime_check_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.UptimeCheckServiceGrpcTransport, + transports.UptimeCheckServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_uptime_check_service_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.UptimeCheckServiceGrpcTransport( - 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/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UptimeCheckServiceGrpcTransport, + transports.UptimeCheckServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_uptime_check_service_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/cloud-platform", @@ -2315,6 +2375,123 @@ def test_uptime_check_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UptimeCheckServiceGrpcTransport, grpc_helpers), + (transports.UptimeCheckServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_uptime_check_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + scopes=["1", "2"], + default_host="monitoring.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.UptimeCheckServiceGrpcTransport, grpc_helpers), + (transports.UptimeCheckServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_uptime_check_service_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( + "monitoring.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/monitoring", + "https://www.googleapis.com/auth/monitoring.read", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UptimeCheckServiceGrpcTransport, grpc_helpers), + (transports.UptimeCheckServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_uptime_check_service_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( + "monitoring.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", [ @@ -2325,7 +2502,7 @@ def test_uptime_check_service_transport_auth_adc(): def test_uptime_check_service_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: @@ -2368,7 +2545,7 @@ def test_uptime_check_service_grpc_transport_client_cert_source_for_mtls( def test_uptime_check_service_host_no_port(): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com" ), @@ -2378,7 +2555,7 @@ def test_uptime_check_service_host_no_port(): def test_uptime_check_service_host_with_port(): client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="monitoring.googleapis.com:8000" ), @@ -2434,9 +2611,9 @@ def test_uptime_check_service_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", @@ -2521,7 +2698,6 @@ def test_uptime_check_service_transport_channel_mtls_with_adc(transport_class): def test_uptime_check_config_path(): project = "squid" uptime_check_config = "clam" - expected = "projects/{project}/uptimeCheckConfigs/{uptime_check_config}".format( project=project, uptime_check_config=uptime_check_config, ) @@ -2545,7 +2721,6 @@ def test_parse_uptime_check_config_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2566,7 +2741,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = UptimeCheckServiceClient.common_folder_path(folder) assert expected == actual @@ -2585,7 +2759,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = UptimeCheckServiceClient.common_organization_path(organization) assert expected == actual @@ -2604,7 +2777,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = UptimeCheckServiceClient.common_project_path(project) assert expected == actual @@ -2624,7 +2796,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2651,7 +2822,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.UptimeCheckServiceTransport, "_prep_wrapped_messages" ) as prep: client = UptimeCheckServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2660,6 +2831,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = UptimeCheckServiceClient.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)