From e3955133d91b3d18b14b099f842b8d088cacbbd5 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 29 Sep 2023 15:00:53 -0400 Subject: [PATCH] feat: add new RPCs GetSettings, UpdateSettings and new messages Settings, NotificationSettings, GetSettingsRequest, UpdateSettingsRequest (#11752) BEGIN_COMMIT_OVERRIDE feat: add new RPCs GetSettings, UpdateSettings and new messages Settings, NotificationSettings, GetSettingsRequest, UpdateSettingsRequest END_COMMIT_OVERRIDE - [ ] Regenerate this pull request now. PiperOrigin-RevId: 568252764 Source-Link: https://github.com/googleapis/googleapis/commit/c981bf5700cfb327da0619b4594120b35dc2ad46 Source-Link: https://github.com/googleapis/googleapis-gen/commit/a37d28dacbcd18faf5297d2fdfae29fea00d96bd Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWFkdmlzb3J5bm90aWZpY2F0aW9ucy8uT3dsQm90LnlhbWwiLCJoIjoiYTM3ZDI4ZGFjYmNkMThmYWY1Mjk3ZDJmZGZhZTI5ZmVhMDBkOTZiZCJ9 --------- Co-authored-by: Owl Bot Co-authored-by: ohmayr --- .../CONTRIBUTING.rst | 4 +- .../cloud/advisorynotifications/__init__.py | 8 + .../advisorynotifications/gapic_version.py | 2 +- .../advisorynotifications_v1/__init__.py | 8 + .../gapic_metadata.json | 30 + .../advisorynotifications_v1/gapic_version.py | 2 +- .../async_client.py | 207 +++ .../advisory_notifications_service/client.py | 223 +++ .../transports/base.py | 28 + .../transports/grpc.py | 50 + .../transports/grpc_asyncio.py | 52 + .../transports/rest.py | 251 +++ .../types/__init__.py | 8 + .../advisorynotifications_v1/types/service.py | 90 ++ .../noxfile.py | 23 +- ...otifications_service_get_settings_async.py | 52 + ...notifications_service_get_settings_sync.py | 52 + ...fications_service_update_settings_async.py | 55 + ...ifications_service_update_settings_sync.py | 55 + ...google.cloud.advisorynotifications.v1.json | 324 +++- ...fixup_advisorynotifications_v1_keywords.py | 2 + .../test_advisory_notifications_service.py | 1427 ++++++++++++++--- 22 files changed, 2731 insertions(+), 222 deletions(-) create mode 100644 packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py create mode 100644 packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py create mode 100644 packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py create mode 100644 packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py diff --git a/packages/google-cloud-advisorynotifications/CONTRIBUTING.rst b/packages/google-cloud-advisorynotifications/CONTRIBUTING.rst index 697fc4fbab5e..337164ecce0c 100644 --- a/packages/google-cloud-advisorynotifications/CONTRIBUTING.rst +++ b/packages/google-cloud-advisorynotifications/CONTRIBUTING.rst @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system- -- -k + $ nox -s system-3.11 -- -k .. note:: - System tests are only configured to run under Python. + System tests are only configured to run under Python 3.8, 3.9, 3.10 and 3.11. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/__init__.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/__init__.py index 10fa11e2a263..d370bf948d60 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/__init__.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/__init__.py @@ -28,15 +28,19 @@ Attachment, Csv, GetNotificationRequest, + GetSettingsRequest, ListNotificationsRequest, ListNotificationsResponse, LocalizationState, Message, Notification, + NotificationSettings, NotificationType, NotificationView, + Settings, Subject, Text, + UpdateSettingsRequest, ) __all__ = ( @@ -45,12 +49,16 @@ "Attachment", "Csv", "GetNotificationRequest", + "GetSettingsRequest", "ListNotificationsRequest", "ListNotificationsResponse", "Message", "Notification", + "NotificationSettings", + "Settings", "Subject", "Text", + "UpdateSettingsRequest", "LocalizationState", "NotificationType", "NotificationView", diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py index 14bfd0fce7ce..360a0d13ebdd 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/__init__.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/__init__.py index ae83dd0396de..e8f30f1f4441 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/__init__.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/__init__.py @@ -26,15 +26,19 @@ Attachment, Csv, GetNotificationRequest, + GetSettingsRequest, ListNotificationsRequest, ListNotificationsResponse, LocalizationState, Message, Notification, + NotificationSettings, NotificationType, NotificationView, + Settings, Subject, Text, + UpdateSettingsRequest, ) __all__ = ( @@ -43,13 +47,17 @@ "Attachment", "Csv", "GetNotificationRequest", + "GetSettingsRequest", "ListNotificationsRequest", "ListNotificationsResponse", "LocalizationState", "Message", "Notification", + "NotificationSettings", "NotificationType", "NotificationView", + "Settings", "Subject", "Text", + "UpdateSettingsRequest", ) diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_metadata.json b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_metadata.json index 5c1c2efdc5bb..166869d9247d 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_metadata.json +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_metadata.json @@ -15,10 +15,20 @@ "get_notification" ] }, + "GetSettings": { + "methods": [ + "get_settings" + ] + }, "ListNotifications": { "methods": [ "list_notifications" ] + }, + "UpdateSettings": { + "methods": [ + "update_settings" + ] } } }, @@ -30,10 +40,20 @@ "get_notification" ] }, + "GetSettings": { + "methods": [ + "get_settings" + ] + }, "ListNotifications": { "methods": [ "list_notifications" ] + }, + "UpdateSettings": { + "methods": [ + "update_settings" + ] } } }, @@ -45,10 +65,20 @@ "get_notification" ] }, + "GetSettings": { + "methods": [ + "get_settings" + ] + }, "ListNotifications": { "methods": [ "list_notifications" ] + }, + "UpdateSettings": { + "methods": [ + "update_settings" + ] } } } diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py index 14bfd0fce7ce..360a0d13ebdd 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/async_client.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/async_client.py index 4e611285fcba..a137d7a383ce 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/async_client.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/async_client.py @@ -68,6 +68,10 @@ class AdvisoryNotificationsServiceAsyncClient: parse_notification_path = staticmethod( AdvisoryNotificationsServiceClient.parse_notification_path ) + settings_path = staticmethod(AdvisoryNotificationsServiceClient.settings_path) + parse_settings_path = staticmethod( + AdvisoryNotificationsServiceClient.parse_settings_path + ) common_billing_account_path = staticmethod( AdvisoryNotificationsServiceClient.common_billing_account_path ) @@ -468,6 +472,209 @@ async def sample_get_notification(): # Done; return the response. return response + async def get_settings( + self, + request: Optional[Union[service.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Get notification settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import advisorynotifications_v1 + + async def sample_get_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient() + + # Initialize request argument(s) + request = advisorynotifications_v1.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.advisorynotifications_v1.types.GetSettingsRequest, dict]]): + The request object. Request of GetSettings endpoint. + name (:class:`str`): + Required. The resource name of the + settings to retrieve. Format: + + organizations/{organization}/locations/{location}/settings. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.advisorynotifications_v1.types.Settings: + Settings for Advisory Notifications. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_settings( + self, + request: Optional[Union[service.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[service.Settings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Update notification settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import advisorynotifications_v1 + + async def sample_update_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient() + + # Initialize request argument(s) + settings = advisorynotifications_v1.Settings() + settings.etag = "etag_value" + + request = advisorynotifications_v1.UpdateSettingsRequest( + settings=settings, + ) + + # Make the request + response = await client.update_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.advisorynotifications_v1.types.UpdateSettingsRequest, dict]]): + The request object. Request of UpdateSettings endpoint. + settings (:class:`google.cloud.advisorynotifications_v1.types.Settings`): + Required. New settings. + This corresponds to the ``settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.advisorynotifications_v1.types.Settings: + Settings for Advisory Notifications. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([settings]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.UpdateSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if settings is not None: + request.settings = settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("settings.name", request.settings.name),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "AdvisoryNotificationsServiceAsyncClient": return self diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py index 7b1fc84870a1..206cc2793c33 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/client.py @@ -207,6 +207,26 @@ def parse_notification_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def settings_path( + organization: str, + location: str, + ) -> str: + """Returns a fully-qualified settings string.""" + return "organizations/{organization}/locations/{location}/settings".format( + organization=organization, + location=location, + ) + + @staticmethod + def parse_settings_path(path: str) -> Dict[str, str]: + """Parses a settings path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/settings$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -672,6 +692,209 @@ def sample_get_notification(): # Done; return the response. return response + def get_settings( + self, + request: Optional[Union[service.GetSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Get notification settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import advisorynotifications_v1 + + def sample_get_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceClient() + + # Initialize request argument(s) + request = advisorynotifications_v1.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.advisorynotifications_v1.types.GetSettingsRequest, dict]): + The request object. Request of GetSettings endpoint. + name (str): + Required. The resource name of the + settings to retrieve. Format: + + organizations/{organization}/locations/{location}/settings. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.advisorynotifications_v1.types.Settings: + Settings for Advisory Notifications. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.GetSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetSettingsRequest): + request = service.GetSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_settings( + self, + request: Optional[Union[service.UpdateSettingsRequest, dict]] = None, + *, + settings: Optional[service.Settings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Update notification settings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import advisorynotifications_v1 + + def sample_update_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceClient() + + # Initialize request argument(s) + settings = advisorynotifications_v1.Settings() + settings.etag = "etag_value" + + request = advisorynotifications_v1.UpdateSettingsRequest( + settings=settings, + ) + + # Make the request + response = client.update_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.advisorynotifications_v1.types.UpdateSettingsRequest, dict]): + The request object. Request of UpdateSettings endpoint. + settings (google.cloud.advisorynotifications_v1.types.Settings): + Required. New settings. + This corresponds to the ``settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.advisorynotifications_v1.types.Settings: + Settings for Advisory Notifications. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([settings]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.UpdateSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateSettingsRequest): + request = service.UpdateSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if settings is not None: + request.settings = settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("settings.name", request.settings.name),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AdvisoryNotificationsServiceClient": return self diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/base.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/base.py index ed345a2f9d4a..d1f08c4972c8 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/base.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/base.py @@ -150,6 +150,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.get_settings: gapic_v1.method.wrap_method( + self.get_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_settings: gapic_v1.method.wrap_method( + self.update_settings, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -182,6 +192,24 @@ def get_notification( ]: raise NotImplementedError() + @property + def get_settings( + self, + ) -> Callable[ + [service.GetSettingsRequest], + Union[service.Settings, Awaitable[service.Settings]], + ]: + raise NotImplementedError() + + @property + def update_settings( + self, + ) -> Callable[ + [service.UpdateSettingsRequest], + Union[service.Settings, Awaitable[service.Settings]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc.py index 6d1706334360..978420255e6f 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc.py @@ -282,6 +282,56 @@ def get_notification( ) return self._stubs["get_notification"] + @property + def get_settings(self) -> Callable[[service.GetSettingsRequest], service.Settings]: + r"""Return a callable for the get settings method over gRPC. + + Get notification settings. + + Returns: + Callable[[~.GetSettingsRequest], + ~.Settings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.advisorynotifications.v1.AdvisoryNotificationsService/GetSettings", + request_serializer=service.GetSettingsRequest.serialize, + response_deserializer=service.Settings.deserialize, + ) + return self._stubs["get_settings"] + + @property + def update_settings( + self, + ) -> Callable[[service.UpdateSettingsRequest], service.Settings]: + r"""Return a callable for the update settings method over gRPC. + + Update notification settings. + + Returns: + Callable[[~.UpdateSettingsRequest], + ~.Settings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.advisorynotifications.v1.AdvisoryNotificationsService/UpdateSettings", + request_serializer=service.UpdateSettingsRequest.serialize, + response_deserializer=service.Settings.deserialize, + ) + return self._stubs["update_settings"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc_asyncio.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc_asyncio.py index e18f6eef74c2..88dbdb71331e 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/grpc_asyncio.py @@ -287,6 +287,58 @@ def get_notification( ) return self._stubs["get_notification"] + @property + def get_settings( + self, + ) -> Callable[[service.GetSettingsRequest], Awaitable[service.Settings]]: + r"""Return a callable for the get settings method over gRPC. + + Get notification settings. + + Returns: + Callable[[~.GetSettingsRequest], + Awaitable[~.Settings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_settings" not in self._stubs: + self._stubs["get_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.advisorynotifications.v1.AdvisoryNotificationsService/GetSettings", + request_serializer=service.GetSettingsRequest.serialize, + response_deserializer=service.Settings.deserialize, + ) + return self._stubs["get_settings"] + + @property + def update_settings( + self, + ) -> Callable[[service.UpdateSettingsRequest], Awaitable[service.Settings]]: + r"""Return a callable for the update settings method over gRPC. + + Update notification settings. + + Returns: + Callable[[~.UpdateSettingsRequest], + Awaitable[~.Settings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_settings" not in self._stubs: + self._stubs["update_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.advisorynotifications.v1.AdvisoryNotificationsService/UpdateSettings", + request_serializer=service.UpdateSettingsRequest.serialize, + response_deserializer=service.Settings.deserialize, + ) + return self._stubs["update_settings"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/rest.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/rest.py index fc61e55048db..5e6bca71b7e6 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/rest.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/services/advisory_notifications_service/transports/rest.py @@ -71,6 +71,14 @@ def post_get_notification(self, response): logging.log(f"Received response: {response}") return response + def pre_get_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_settings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_notifications(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -79,6 +87,14 @@ def post_list_notifications(self, response): logging.log(f"Received response: {response}") return response + def pre_update_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_settings(self, response): + logging.log(f"Received response: {response}") + return response + transport = AdvisoryNotificationsServiceRestTransport(interceptor=MyCustomAdvisoryNotificationsServiceInterceptor()) client = AdvisoryNotificationsServiceClient(transport=transport) @@ -108,6 +124,25 @@ def post_get_notification( """ return response + def pre_get_settings( + self, request: service.GetSettingsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdvisoryNotificationsService server. + """ + return request, metadata + + def post_get_settings(self, response: service.Settings) -> service.Settings: + """Post-rpc interceptor for get_settings + + Override in a subclass to manipulate the response + after it is returned by the AdvisoryNotificationsService server but before + it is returned to user code. + """ + return response + def pre_list_notifications( self, request: service.ListNotificationsRequest, @@ -131,6 +166,27 @@ def post_list_notifications( """ return response + def pre_update_settings( + self, + request: service.UpdateSettingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AdvisoryNotificationsService server. + """ + return request, metadata + + def post_update_settings(self, response: service.Settings) -> service.Settings: + """Post-rpc interceptor for update_settings + + Override in a subclass to manipulate the response + after it is returned by the AdvisoryNotificationsService server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class AdvisoryNotificationsServiceRestStub: @@ -319,6 +375,92 @@ def __call__( resp = self._interceptor.post_get_notification(resp) return resp + class _GetSettings(AdvisoryNotificationsServiceRestStub): + def __hash__(self): + return hash("GetSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Call the get settings method over HTTP. + + Args: + request (~.service.GetSettingsRequest): + The request object. Request of GetSettings endpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.Settings: + Settings for Advisory Notifications. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/settings}", + }, + ] + request, metadata = self._interceptor.pre_get_settings(request, metadata) + pb_request = service.GetSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.Settings() + pb_resp = service.Settings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_settings(resp) + return resp + class _ListNotifications(AdvisoryNotificationsServiceRestStub): def __hash__(self): return hash("ListNotifications") @@ -410,6 +552,101 @@ def __call__( resp = self._interceptor.post_list_notifications(resp) return resp + class _UpdateSettings(AdvisoryNotificationsServiceRestStub): + def __hash__(self): + return hash("UpdateSettings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Settings: + r"""Call the update settings method over HTTP. + + Args: + request (~.service.UpdateSettingsRequest): + The request object. Request of UpdateSettings endpoint. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.Settings: + Settings for Advisory Notifications. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{settings.name=organizations/*/locations/*/settings}", + "body": "settings", + }, + ] + request, metadata = self._interceptor.pre_update_settings(request, metadata) + pb_request = service.UpdateSettingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.Settings() + pb_resp = service.Settings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_settings(resp) + return resp + @property def get_notification( self, @@ -418,6 +655,12 @@ def get_notification( # In C++ this would require a dynamic_cast return self._GetNotification(self._session, self._host, self._interceptor) # type: ignore + @property + def get_settings(self) -> Callable[[service.GetSettingsRequest], service.Settings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSettings(self._session, self._host, self._interceptor) # type: ignore + @property def list_notifications( self, @@ -428,6 +671,14 @@ def list_notifications( # In C++ this would require a dynamic_cast return self._ListNotifications(self._session, self._host, self._interceptor) # type: ignore + @property + def update_settings( + self, + ) -> Callable[[service.UpdateSettingsRequest], service.Settings]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSettings(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/__init__.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/__init__.py index a24e4ea74224..1ef8ad933103 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/__init__.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/__init__.py @@ -17,27 +17,35 @@ Attachment, Csv, GetNotificationRequest, + GetSettingsRequest, ListNotificationsRequest, ListNotificationsResponse, LocalizationState, Message, Notification, + NotificationSettings, NotificationType, NotificationView, + Settings, Subject, Text, + UpdateSettingsRequest, ) __all__ = ( "Attachment", "Csv", "GetNotificationRequest", + "GetSettingsRequest", "ListNotificationsRequest", "ListNotificationsResponse", "Message", "Notification", + "NotificationSettings", + "Settings", "Subject", "Text", + "UpdateSettingsRequest", "LocalizationState", "NotificationType", "NotificationView", diff --git a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/service.py b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/service.py index af5006748b19..3ff314dd441b 100644 --- a/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/service.py +++ b/packages/google-cloud-advisorynotifications/google/cloud/advisorynotifications_v1/types/service.py @@ -35,6 +35,10 @@ "ListNotificationsRequest", "ListNotificationsResponse", "GetNotificationRequest", + "Settings", + "NotificationSettings", + "GetSettingsRequest", + "UpdateSettingsRequest", }, ) @@ -435,4 +439,90 @@ class GetNotificationRequest(proto.Message): ) +class Settings(proto.Message): + r"""Settings for Advisory Notifications. + + Attributes: + name (str): + Output only. The resource name of the + settings to retrieve. Format: + + organizations/{organization}/locations/{location}/settings. + notification_settings (MutableMapping[str, google.cloud.advisorynotifications_v1.types.NotificationSettings]): + Required. Map of each notification type and + its settings to get/set all settings at once. + The server will validate the value for each + notification type. + etag (str): + Required. Fingerprint for optimistic + concurrency returned in Get requests. Must be + provided for Update requests. If the value + provided does not match the value known to the + server, ABORTED will be thrown, and the client + should retry the read-modify-write cycle. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + notification_settings: MutableMapping[str, "NotificationSettings"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="NotificationSettings", + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class NotificationSettings(proto.Message): + r"""Settings for each NotificationType. + + Attributes: + enabled (bool): + Whether the associated NotificationType is + enabled. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class GetSettingsRequest(proto.Message): + r"""Request of GetSettings endpoint. + + Attributes: + name (str): + Required. The resource name of the settings + to retrieve. Format: + + organizations/{organization}/locations/{location}/settings. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSettingsRequest(proto.Message): + r"""Request of UpdateSettings endpoint. + + Attributes: + settings (google.cloud.advisorynotifications_v1.types.Settings): + Required. New settings. + """ + + settings: "Settings" = proto.Field( + proto.MESSAGE, + number=1, + message="Settings", + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-advisorynotifications/noxfile.py b/packages/google-cloud-advisorynotifications/noxfile.py index 9a2acd8b6787..be54712bfa8f 100644 --- a/packages/google-cloud-advisorynotifications/noxfile.py +++ b/packages/google-cloud-advisorynotifications/noxfile.py @@ -46,7 +46,7 @@ UNIT_TEST_EXTRAS = [] UNIT_TEST_EXTRAS_BY_PYTHON = {} -SYSTEM_TEST_PYTHON_VERSIONS = [] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -405,24 +405,3 @@ def prerelease_deps(session): session.run("python", "-c", "import google.auth; print(google.auth.__version__)") session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py new file mode 100644 index 000000000000..083e2e9495d4 --- /dev/null +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-advisorynotifications + + +# [START advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import advisorynotifications_v1 + + +async def sample_get_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient() + + # Initialize request argument(s) + request = advisorynotifications_v1.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_settings(request=request) + + # Handle the response + print(response) + +# [END advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_async] diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py new file mode 100644 index 000000000000..710ed7cc2892 --- /dev/null +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-advisorynotifications + + +# [START advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import advisorynotifications_v1 + + +def sample_get_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceClient() + + # Initialize request argument(s) + request = advisorynotifications_v1.GetSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_settings(request=request) + + # Handle the response + print(response) + +# [END advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_sync] diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py new file mode 100644 index 000000000000..8b045cb42564 --- /dev/null +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-advisorynotifications + + +# [START advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import advisorynotifications_v1 + + +async def sample_update_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient() + + # Initialize request argument(s) + settings = advisorynotifications_v1.Settings() + settings.etag = "etag_value" + + request = advisorynotifications_v1.UpdateSettingsRequest( + settings=settings, + ) + + # Make the request + response = await client.update_settings(request=request) + + # Handle the response + print(response) + +# [END advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_async] diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py new file mode 100644 index 000000000000..ca4b17d97a46 --- /dev/null +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-advisorynotifications + + +# [START advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import advisorynotifications_v1 + + +def sample_update_settings(): + # Create a client + client = advisorynotifications_v1.AdvisoryNotificationsServiceClient() + + # Initialize request argument(s) + settings = advisorynotifications_v1.Settings() + settings.etag = "etag_value" + + request = advisorynotifications_v1.UpdateSettingsRequest( + settings=settings, + ) + + # Make the request + response = client.update_settings(request=request) + + # Handle the response + print(response) + +# [END advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_sync] diff --git a/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json b/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json index 25220e592f95..d786a8bfb8cb 100644 --- a/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json +++ b/packages/google-cloud-advisorynotifications/samples/generated_samples/snippet_metadata_google.cloud.advisorynotifications.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-advisorynotifications", - "version": "0.3.0" + "version": "0.1.0" }, "snippets": [ { @@ -172,6 +172,167 @@ ], "title": "advisorynotifications_v1_generated_advisory_notifications_service_get_notification_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient", + "shortName": "AdvisoryNotificationsServiceAsyncClient" + }, + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient.get_settings", + "method": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService.GetSettings", + "service": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService", + "shortName": "AdvisoryNotificationsService" + }, + "shortName": "GetSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.advisorynotifications_v1.types.GetSettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.advisorynotifications_v1.types.Settings", + "shortName": "get_settings" + }, + "description": "Sample for GetSettings", + "file": "advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "advisorynotifications_v1_generated_advisory_notifications_service_get_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceClient", + "shortName": "AdvisoryNotificationsServiceClient" + }, + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceClient.get_settings", + "method": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService.GetSettings", + "service": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService", + "shortName": "AdvisoryNotificationsService" + }, + "shortName": "GetSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.advisorynotifications_v1.types.GetSettingsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.advisorynotifications_v1.types.Settings", + "shortName": "get_settings" + }, + "description": "Sample for GetSettings", + "file": "advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "advisorynotifications_v1_generated_AdvisoryNotificationsService_GetSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "advisorynotifications_v1_generated_advisory_notifications_service_get_settings_sync.py" + }, { "canonical": true, "clientMethod": { @@ -332,6 +493,167 @@ } ], "title": "advisorynotifications_v1_generated_advisory_notifications_service_list_notifications_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient", + "shortName": "AdvisoryNotificationsServiceAsyncClient" + }, + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceAsyncClient.update_settings", + "method": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService.UpdateSettings", + "service": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService", + "shortName": "AdvisoryNotificationsService" + }, + "shortName": "UpdateSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.advisorynotifications_v1.types.UpdateSettingsRequest" + }, + { + "name": "settings", + "type": "google.cloud.advisorynotifications_v1.types.Settings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.advisorynotifications_v1.types.Settings", + "shortName": "update_settings" + }, + "description": "Sample for UpdateSettings", + "file": "advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "advisorynotifications_v1_generated_advisory_notifications_service_update_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceClient", + "shortName": "AdvisoryNotificationsServiceClient" + }, + "fullName": "google.cloud.advisorynotifications_v1.AdvisoryNotificationsServiceClient.update_settings", + "method": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService.UpdateSettings", + "service": { + "fullName": "google.cloud.advisorynotifications.v1.AdvisoryNotificationsService", + "shortName": "AdvisoryNotificationsService" + }, + "shortName": "UpdateSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.advisorynotifications_v1.types.UpdateSettingsRequest" + }, + { + "name": "settings", + "type": "google.cloud.advisorynotifications_v1.types.Settings" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.advisorynotifications_v1.types.Settings", + "shortName": "update_settings" + }, + "description": "Sample for UpdateSettings", + "file": "advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "advisorynotifications_v1_generated_AdvisoryNotificationsService_UpdateSettings_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "advisorynotifications_v1_generated_advisory_notifications_service_update_settings_sync.py" } ] } diff --git a/packages/google-cloud-advisorynotifications/scripts/fixup_advisorynotifications_v1_keywords.py b/packages/google-cloud-advisorynotifications/scripts/fixup_advisorynotifications_v1_keywords.py index 6279b84a7bb4..706081de89ae 100644 --- a/packages/google-cloud-advisorynotifications/scripts/fixup_advisorynotifications_v1_keywords.py +++ b/packages/google-cloud-advisorynotifications/scripts/fixup_advisorynotifications_v1_keywords.py @@ -40,7 +40,9 @@ class advisorynotificationsCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'get_notification': ('name', 'language_code', ), + 'get_settings': ('name', ), 'list_notifications': ('parent', 'page_size', 'page_token', 'view', 'language_code', ), + 'update_settings': ('settings', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py b/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py index c1aeb84feded..9f3c61af54d9 100644 --- a/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py +++ b/packages/google-cloud-advisorynotifications/tests/unit/gapic/advisorynotifications_v1/test_advisory_notifications_service.py @@ -1448,6 +1448,470 @@ async def test_get_notification_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + service.GetSettingsRequest, + dict, + ], +) +def test_get_settings(request_type, transport: str = "grpc"): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings( + name="name_value", + etag="etag_value", + ) + response = client.get_settings(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.GetSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Settings) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_get_settings_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 = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + client.get_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetSettingsRequest() + + +@pytest.mark.asyncio +async def test_get_settings_async( + transport: str = "grpc_asyncio", request_type=service.GetSettingsRequest +): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.Settings( + name="name_value", + etag="etag_value", + ) + ) + response = await client.get_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Settings) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_settings_async_from_dict(): + await test_get_settings_async(request_type=dict) + + +def test_get_settings_field_headers(): + client = AdvisoryNotificationsServiceClient( + 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.GetSettingsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + call.return_value = service.Settings() + client.get_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_settings_field_headers_async(): + client = AdvisoryNotificationsServiceAsyncClient( + 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.GetSettingsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Settings()) + await client.get_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_settings_flattened(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_settings( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_settings_flattened_error(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_settings( + service.GetSettingsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_settings_flattened_async(): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Settings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_settings( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_settings_flattened_error_async(): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_settings( + service.GetSettingsRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateSettingsRequest, + dict, + ], +) +def test_update_settings(request_type, transport: str = "grpc"): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings( + name="name_value", + etag="etag_value", + ) + response = client.update_settings(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.UpdateSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Settings) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_update_settings_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 = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + client.update_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateSettingsRequest() + + +@pytest.mark.asyncio +async def test_update_settings_async( + transport: str = "grpc_asyncio", request_type=service.UpdateSettingsRequest +): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.Settings( + name="name_value", + etag="etag_value", + ) + ) + response = await client.update_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Settings) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_settings_async_from_dict(): + await test_update_settings_async(request_type=dict) + + +def test_update_settings_field_headers(): + client = AdvisoryNotificationsServiceClient( + 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.UpdateSettingsRequest() + + request.settings.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + call.return_value = service.Settings() + client.update_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "settings.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_settings_field_headers_async(): + client = AdvisoryNotificationsServiceAsyncClient( + 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.UpdateSettingsRequest() + + request.settings.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Settings()) + await client.update_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "settings.name=name_value", + ) in kw["metadata"] + + +def test_update_settings_flattened(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_settings( + settings=service.Settings(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].settings + mock_val = service.Settings(name="name_value") + assert arg == mock_val + + +def test_update_settings_flattened_error(): + client = AdvisoryNotificationsServiceClient( + 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_settings( + service.UpdateSettingsRequest(), + settings=service.Settings(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_update_settings_flattened_async(): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_settings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.Settings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Settings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_settings( + settings=service.Settings(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].settings + mock_val = service.Settings(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_settings_flattened_error_async(): + client = AdvisoryNotificationsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_settings( + service.UpdateSettingsRequest(), + settings=service.Settings(name="name_value"), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -1455,47 +1919,667 @@ async def test_get_notification_flattened_error_async(): dict, ], ) -def test_list_notifications_rest(request_type): +def test_list_notifications_rest(request_type): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListNotificationsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListNotificationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_notifications(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_notifications_rest_required_fields( + request_type=service.ListNotificationsRequest, +): + transport_class = transports.AdvisoryNotificationsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_notifications._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_notifications._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "language_code", + "page_size", + "page_token", + "view", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListNotificationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListNotificationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_notifications(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_notifications_rest_unset_required_fields(): + transport = transports.AdvisoryNotificationsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_notifications._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "languageCode", + "pageSize", + "pageToken", + "view", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notifications_rest_interceptors(null_interceptor): + transport = transports.AdvisoryNotificationsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdvisoryNotificationsServiceRestInterceptor(), + ) + client = AdvisoryNotificationsServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AdvisoryNotificationsServiceRestInterceptor, + "post_list_notifications", + ) as post, mock.patch.object( + transports.AdvisoryNotificationsServiceRestInterceptor, "pre_list_notifications" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListNotificationsRequest.pb( + service.ListNotificationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListNotificationsResponse.to_json( + service.ListNotificationsResponse() + ) + + request = service.ListNotificationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListNotificationsResponse() + + client.list_notifications( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notifications_rest_bad_request( + transport: str = "rest", request_type=service.ListNotificationsRequest +): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notifications(request) + + +def test_list_notifications_rest_flattened(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListNotificationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListNotificationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_notifications(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*}/notifications" + % client.transport._host, + args[1], + ) + + +def test_list_notifications_rest_flattened_error(transport: str = "rest"): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_notifications( + service.ListNotificationsRequest(), + parent="parent_value", + ) + + +def test_list_notifications_rest_pager(transport: str = "rest"): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListNotificationsResponse( + notifications=[ + service.Notification(), + service.Notification(), + service.Notification(), + ], + next_page_token="abc", + ), + service.ListNotificationsResponse( + notifications=[], + next_page_token="def", + ), + service.ListNotificationsResponse( + notifications=[ + service.Notification(), + ], + next_page_token="ghi", + ), + service.ListNotificationsResponse( + notifications=[ + service.Notification(), + service.Notification(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListNotificationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_notifications(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, service.Notification) for i in results) + + pages = list(client.list_notifications(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetNotificationRequest, + dict, + ], +) +def test_get_notification_rest(request_type): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notifications/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.Notification( + name="name_value", + notification_type=service.NotificationType.NOTIFICATION_TYPE_SECURITY_PRIVACY_ADVISORY, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Notification.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_notification(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Notification) + assert response.name == "name_value" + assert ( + response.notification_type + == service.NotificationType.NOTIFICATION_TYPE_SECURITY_PRIVACY_ADVISORY + ) + + +def test_get_notification_rest_required_fields( + request_type=service.GetNotificationRequest, +): + transport_class = transports.AdvisoryNotificationsServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_notification._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_notification._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("language_code",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.Notification() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.Notification.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_notification(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_notification_rest_unset_required_fields(): + transport = transports.AdvisoryNotificationsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_notification._get_unset_required_fields({}) + assert set(unset_fields) == (set(("languageCode",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_rest_interceptors(null_interceptor): + transport = transports.AdvisoryNotificationsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AdvisoryNotificationsServiceRestInterceptor(), + ) + client = AdvisoryNotificationsServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AdvisoryNotificationsServiceRestInterceptor, "post_get_notification" + ) as post, mock.patch.object( + transports.AdvisoryNotificationsServiceRestInterceptor, "pre_get_notification" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetNotificationRequest.pb(service.GetNotificationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.Notification.to_json(service.Notification()) + + request = service.GetNotificationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Notification() + + client.get_notification( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_rest_bad_request( + transport: str = "rest", request_type=service.GetNotificationRequest +): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notifications/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification(request) + + +def test_get_notification_rest_flattened(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.Notification() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/notifications/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.Notification.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_notification(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=organizations/*/locations/*/notifications/*}" + % client.transport._host, + args[1], + ) + + +def test_get_notification_rest_flattened_error(transport: str = "rest"): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_notification( + service.GetNotificationRequest(), + name="name_value", + ) + + +def test_get_notification_rest_error(): + client = AdvisoryNotificationsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetSettingsRequest, + dict, + ], +) +def test_get_settings_rest(request_type): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init = {"name": "organizations/sample1/locations/sample2/settings"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListNotificationsResponse( - next_page_token="next_page_token_value", - total_size=1086, + return_value = service.Settings( + name="name_value", + etag="etag_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListNotificationsResponse.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_notifications(request) + response = client.get_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, service.Settings) + assert response.name == "name_value" + assert response.etag == "etag_value" -def test_list_notifications_rest_required_fields( - request_type=service.ListNotificationsRequest, -): +def test_get_settings_rest_required_fields(request_type=service.GetSettingsRequest): transport_class = transports.AdvisoryNotificationsServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -1510,30 +2594,21 @@ def test_list_notifications_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_notifications._get_unset_required_fields(jsonified_request) + ).get_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_notifications._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "language_code", - "page_size", - "page_token", - "view", - ) - ) + ).get_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1542,7 +2617,7 @@ def test_list_notifications_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListNotificationsResponse() + return_value = service.Settings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -1562,40 +2637,30 @@ def test_list_notifications_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListNotificationsResponse.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_notifications(request) + response = client.get_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_notifications_rest_unset_required_fields(): +def test_get_settings_rest_unset_required_fields(): transport = transports.AdvisoryNotificationsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_notifications._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "languageCode", - "pageSize", - "pageToken", - "view", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_notifications_rest_interceptors(null_interceptor): +def test_get_settings_rest_interceptors(null_interceptor): transport = transports.AdvisoryNotificationsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1608,16 +2673,13 @@ def test_list_notifications_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AdvisoryNotificationsServiceRestInterceptor, - "post_list_notifications", + transports.AdvisoryNotificationsServiceRestInterceptor, "post_get_settings" ) as post, mock.patch.object( - transports.AdvisoryNotificationsServiceRestInterceptor, "pre_list_notifications" + transports.AdvisoryNotificationsServiceRestInterceptor, "pre_get_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListNotificationsRequest.pb( - service.ListNotificationsRequest() - ) + pb_message = service.GetSettingsRequest.pb(service.GetSettingsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -1628,19 +2690,17 @@ def test_list_notifications_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListNotificationsResponse.to_json( - service.ListNotificationsResponse() - ) + req.return_value._content = service.Settings.to_json(service.Settings()) - request = service.ListNotificationsRequest() + request = service.GetSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListNotificationsResponse() + post.return_value = service.Settings() - client.list_notifications( + client.get_settings( request, metadata=[ ("key", "val"), @@ -1652,8 +2712,8 @@ def test_list_notifications_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_notifications_rest_bad_request( - transport: str = "rest", request_type=service.ListNotificationsRequest +def test_get_settings_rest_bad_request( + transport: str = "rest", request_type=service.GetSettingsRequest ): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1661,7 +2721,7 @@ def test_list_notifications_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init = {"name": "organizations/sample1/locations/sample2/settings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -1673,10 +2733,10 @@ def test_list_notifications_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_notifications(request) + client.get_settings(request) -def test_list_notifications_rest_flattened(): +def test_get_settings_rest_flattened(): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1685,39 +2745,39 @@ def test_list_notifications_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListNotificationsResponse() + return_value = service.Settings() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "organizations/sample1/locations/sample2"} + sample_request = {"name": "organizations/sample1/locations/sample2/settings"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListNotificationsResponse.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_notifications(**mock_args) + client.get_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=organizations/*/locations/*}/notifications" + "%s/v1/{name=organizations/*/locations/*/settings}" % client.transport._host, args[1], ) -def test_list_notifications_rest_flattened_error(transport: str = "rest"): +def test_get_settings_rest_flattened_error(transport: str = "rest"): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1726,81 +2786,26 @@ def test_list_notifications_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_notifications( - service.ListNotificationsRequest(), - parent="parent_value", + client.get_settings( + service.GetSettingsRequest(), + name="name_value", ) -def test_list_notifications_rest_pager(transport: str = "rest"): +def test_get_settings_rest_error(): client = AdvisoryNotificationsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListNotificationsResponse( - notifications=[ - service.Notification(), - service.Notification(), - service.Notification(), - ], - next_page_token="abc", - ), - service.ListNotificationsResponse( - notifications=[], - next_page_token="def", - ), - service.ListNotificationsResponse( - notifications=[ - service.Notification(), - ], - next_page_token="ghi", - ), - service.ListNotificationsResponse( - notifications=[ - service.Notification(), - service.Notification(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListNotificationsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "organizations/sample1/locations/sample2"} - - pager = client.list_notifications(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service.Notification) for i in results) - - pages = list(client.list_notifications(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetNotificationRequest, + service.UpdateSettingsRequest, dict, ], ) -def test_get_notification_rest(request_type): +def test_update_settings_rest(request_type): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1808,44 +2813,45 @@ def test_get_notification_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/notifications/sample3" + "settings": {"name": "organizations/sample1/locations/sample2/settings"} + } + request_init["settings"] = { + "name": "organizations/sample1/locations/sample2/settings", + "notification_settings": {}, + "etag": "etag_value", } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.Notification( + return_value = service.Settings( name="name_value", - notification_type=service.NotificationType.NOTIFICATION_TYPE_SECURITY_PRIVACY_ADVISORY, + etag="etag_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.Notification.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_notification(request) + response = client.update_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.Notification) + assert isinstance(response, service.Settings) assert response.name == "name_value" - assert ( - response.notification_type - == service.NotificationType.NOTIFICATION_TYPE_SECURITY_PRIVACY_ADVISORY - ) + assert response.etag == "etag_value" -def test_get_notification_rest_required_fields( - request_type=service.GetNotificationRequest, +def test_update_settings_rest_required_fields( + request_type=service.UpdateSettingsRequest, ): transport_class = transports.AdvisoryNotificationsServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -1860,23 +2866,17 @@ def test_get_notification_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_notification._get_unset_required_fields(jsonified_request) + ).update_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_notification._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code",)) + ).update_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1885,7 +2885,7 @@ def test_get_notification_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.Notification() + return_value = service.Settings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -1897,38 +2897,39 @@ def test_get_notification_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - pb_return_value = service.Notification.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_notification(request) + response = client.update_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_notification_rest_unset_required_fields(): +def test_update_settings_rest_unset_required_fields(): transport = transports.AdvisoryNotificationsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_notification._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode",)) & set(("name",))) + unset_fields = transport.update_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("settings",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_notification_rest_interceptors(null_interceptor): +def test_update_settings_rest_interceptors(null_interceptor): transport = transports.AdvisoryNotificationsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -1941,13 +2942,13 @@ def test_get_notification_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AdvisoryNotificationsServiceRestInterceptor, "post_get_notification" + transports.AdvisoryNotificationsServiceRestInterceptor, "post_update_settings" ) as post, mock.patch.object( - transports.AdvisoryNotificationsServiceRestInterceptor, "pre_get_notification" + transports.AdvisoryNotificationsServiceRestInterceptor, "pre_update_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetNotificationRequest.pb(service.GetNotificationRequest()) + pb_message = service.UpdateSettingsRequest.pb(service.UpdateSettingsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -1958,17 +2959,17 @@ def test_get_notification_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.Notification.to_json(service.Notification()) + req.return_value._content = service.Settings.to_json(service.Settings()) - request = service.GetNotificationRequest() + request = service.UpdateSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.Notification() + post.return_value = service.Settings() - client.get_notification( + client.update_settings( request, metadata=[ ("key", "val"), @@ -1980,8 +2981,8 @@ def test_get_notification_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_notification_rest_bad_request( - transport: str = "rest", request_type=service.GetNotificationRequest +def test_update_settings_rest_bad_request( + transport: str = "rest", request_type=service.UpdateSettingsRequest ): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1990,7 +2991,12 @@ def test_get_notification_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "organizations/sample1/locations/sample2/notifications/sample3" + "settings": {"name": "organizations/sample1/locations/sample2/settings"} + } + request_init["settings"] = { + "name": "organizations/sample1/locations/sample2/settings", + "notification_settings": {}, + "etag": "etag_value", } request = request_type(**request_init) @@ -2003,10 +3009,10 @@ def test_get_notification_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_notification(request) + client.update_settings(request) -def test_get_notification_rest_flattened(): +def test_update_settings_rest_flattened(): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2015,41 +3021,41 @@ def test_get_notification_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.Notification() + return_value = service.Settings() # get arguments that satisfy an http rule for this method sample_request = { - "name": "organizations/sample1/locations/sample2/notifications/sample3" + "settings": {"name": "organizations/sample1/locations/sample2/settings"} } # get truthy value for each flattened field mock_args = dict( - name="name_value", + settings=service.Settings(name="name_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.Notification.pb(return_value) + pb_return_value = service.Settings.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_notification(**mock_args) + client.update_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=organizations/*/locations/*/notifications/*}" + "%s/v1/{settings.name=organizations/*/locations/*/settings}" % client.transport._host, args[1], ) -def test_get_notification_rest_flattened_error(transport: str = "rest"): +def test_update_settings_rest_flattened_error(transport: str = "rest"): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2058,13 +3064,13 @@ def test_get_notification_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_notification( - service.GetNotificationRequest(), - name="name_value", + client.update_settings( + service.UpdateSettingsRequest(), + settings=service.Settings(name="name_value"), ) -def test_get_notification_rest_error(): +def test_update_settings_rest_error(): client = AdvisoryNotificationsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2211,6 +3217,8 @@ def test_advisory_notifications_service_base_transport(): methods = ( "list_notifications", "get_notification", + "get_settings", + "update_settings", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2486,6 +3494,12 @@ def test_advisory_notifications_service_client_transport_session_collision( session1 = client1.transport.get_notification._session session2 = client2.transport.get_notification._session assert session1 != session2 + session1 = client1.transport.get_settings._session + session2 = client2.transport.get_settings._session + assert session1 != session2 + session1 = client1.transport.update_settings._session + session2 = client2.transport.update_settings._session + assert session1 != session2 def test_advisory_notifications_service_grpc_transport_channel(): @@ -2644,8 +3658,31 @@ def test_parse_notification_path(): assert expected == actual +def test_settings_path(): + organization = "cuttlefish" + location = "mussel" + expected = "organizations/{organization}/locations/{location}/settings".format( + organization=organization, + location=location, + ) + actual = AdvisoryNotificationsServiceClient.settings_path(organization, location) + assert expected == actual + + +def test_parse_settings_path(): + expected = { + "organization": "winkle", + "location": "nautilus", + } + path = AdvisoryNotificationsServiceClient.settings_path(**expected) + + # Check that the path construction is reversible. + actual = AdvisoryNotificationsServiceClient.parse_settings_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2657,7 +3694,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "abalone", } path = AdvisoryNotificationsServiceClient.common_billing_account_path(**expected) @@ -2667,7 +3704,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -2677,7 +3714,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "clam", } path = AdvisoryNotificationsServiceClient.common_folder_path(**expected) @@ -2687,7 +3724,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -2697,7 +3734,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "octopus", } path = AdvisoryNotificationsServiceClient.common_organization_path(**expected) @@ -2707,7 +3744,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -2717,7 +3754,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nudibranch", } path = AdvisoryNotificationsServiceClient.common_project_path(**expected) @@ -2727,8 +3764,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -2739,8 +3776,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "winkle", + "location": "nautilus", } path = AdvisoryNotificationsServiceClient.common_location_path(**expected)