diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/_metadata.json b/sdk/webpubsub/azure-messaging-webpubsubservice/_metadata.json index 2ae13b97aba7..523ec06deec0 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/_metadata.json +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/_metadata.json @@ -1,3 +1,6 @@ { - "apiVersion": "2024-12-01" + "apiVersion": "2024-12-01", + "apiVersions": { + "WebPubSubService": "2024-12-01" + } } \ No newline at end of file diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/apiview-properties.json b/sdk/webpubsub/azure-messaging-webpubsubservice/apiview-properties.json index f6e5178000a4..7920e0fb548f 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/apiview-properties.json +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/apiview-properties.json @@ -15,8 +15,8 @@ "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.add_connections_to_groups": "WebPubSubService.addConnectionsToGroups", "azure.messaging.webpubsubservice.WebPubSubServiceClient.close_all_connections": "WebPubSubService.closeAllConnections", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.close_all_connections": "WebPubSubService.closeAllConnections", - "azure.messaging.webpubsubservice.WebPubSubServiceClient.get_client_access_token": "WebPubSubService.getClientAccessToken", - "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.get_client_access_token": "WebPubSubService.getClientAccessToken", + "azure.messaging.webpubsubservice.WebPubSubServiceClient.generate_client_token": "WebPubSubService.generateClientToken", + "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.generate_client_token": "WebPubSubService.generateClientToken", "azure.messaging.webpubsubservice.WebPubSubServiceClient.remove_connections_from_groups": "WebPubSubService.removeConnectionsFromGroups", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.remove_connections_from_groups": "WebPubSubService.removeConnectionsFromGroups", "azure.messaging.webpubsubservice.WebPubSubServiceClient.send_to_all": "WebPubSubService.sendToAll", @@ -35,16 +35,16 @@ "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.close_group_connections": "WebPubSubService.closeGroupConnections", "azure.messaging.webpubsubservice.WebPubSubServiceClient.send_to_group": "WebPubSubService.sendToGroup", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.send_to_group": "WebPubSubService.sendToGroup", - "azure.messaging.webpubsubservice.WebPubSubServiceClient.list_connections": "WebPubSubService.listConnections", - "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.list_connections": "WebPubSubService.listConnections", + "azure.messaging.webpubsubservice.WebPubSubServiceClient.list_connections_in_group": "WebPubSubService.listConnectionsInGroup", + "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.list_connections_in_group": "WebPubSubService.listConnectionsInGroup", "azure.messaging.webpubsubservice.WebPubSubServiceClient.remove_connection_from_group": "WebPubSubService.removeConnectionFromGroup", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.remove_connection_from_group": "WebPubSubService.removeConnectionFromGroup", "azure.messaging.webpubsubservice.WebPubSubServiceClient.add_connection_to_group": "WebPubSubService.addConnectionToGroup", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.add_connection_to_group": "WebPubSubService.addConnectionToGroup", "azure.messaging.webpubsubservice.WebPubSubServiceClient.revoke_permission": "WebPubSubService.revokePermission", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.revoke_permission": "WebPubSubService.revokePermission", - "azure.messaging.webpubsubservice.WebPubSubServiceClient.has_permission": "WebPubSubService.hasPermission", - "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.has_permission": "WebPubSubService.hasPermission", + "azure.messaging.webpubsubservice.WebPubSubServiceClient.check_permission": "WebPubSubService.checkPermission", + "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.check_permission": "WebPubSubService.checkPermission", "azure.messaging.webpubsubservice.WebPubSubServiceClient.grant_permission": "WebPubSubService.grantPermission", "azure.messaging.webpubsubservice.aio.WebPubSubServiceClient.grant_permission": "WebPubSubService.grantPermission", "azure.messaging.webpubsubservice.WebPubSubServiceClient.user_exists": "WebPubSubService.userExists", diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/assets.json b/sdk/webpubsub/azure-messaging-webpubsubservice/assets.json index 9a0883e473d2..f0e9d9f02012 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/assets.json +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/webpubsub/azure-messaging-webpubsubservice", - "Tag": "python/webpubsub/azure-messaging-webpubsubservice_34edba9a6b" + "Tag": "python/webpubsub/azure-messaging-webpubsubservice_447df314c8" } diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_client.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_client.py index fe5e565eed0a..6916054e9819 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_client.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_client.py @@ -30,10 +30,11 @@ class WebPubSubServiceClient(_WebPubSubServiceClientOperationsMixin): :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. Required. + alpha-numeric characters or underscore. Required. :type hub: str - :keyword api_version: The API version to use for this operation. Default value is "2024-12-01". - Note that overriding this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2024-12-01". + Default value is "2024-12-01". Note that overriding this default value may result in + unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py index 1efdfe7b0b0f..4920ecc2fe8f 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py @@ -27,10 +27,11 @@ class WebPubSubServiceClientConfiguration: # pylint: disable=too-many-instance- :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. Required. + alpha-numeric characters or underscore. Required. :type hub: str - :keyword api_version: The API version to use for this operation. Default value is "2024-12-01". - Note that overriding this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2024-12-01". + Default value is "2024-12-01". Note that overriding this default value may result in + unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py index ec991e9b6b30..36ec7ba335ad 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py @@ -9,7 +9,7 @@ from collections.abc import MutableMapping from io import IOBase import json -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core import PipelineClient @@ -37,29 +37,23 @@ JSON = MutableMapping[str, Any] T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_web_pub_sub_service_get_service_status_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/health" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_add_connections_to_groups_request( # pylint: disable=name-too-long @@ -70,8 +64,6 @@ def build_web_pub_sub_service_add_connections_to_groups_request( # pylint: disa content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/:addToGroups" path_format_arguments = { @@ -86,20 +78,16 @@ def build_web_pub_sub_service_add_connections_to_groups_request( # pylint: disa # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_web_pub_sub_service_close_all_connections_request( # pylint: disable=name-too-long - hub: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + hub: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/:closeConnections" path_format_arguments = { @@ -111,24 +99,21 @@ def build_web_pub_sub_service_close_all_connections_request( # pylint: disable= # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if excluded is not None: - _params["excluded"] = _SERIALIZER.query("excluded", excluded, "[str]", div=",") + _params["excluded"] = [_SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded] if reason is not None: _params["reason"] = _SERIALIZER.query("reason", reason, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) -def build_web_pub_sub_service_get_client_access_token_request( # pylint: disable=name-too-long +def build_web_pub_sub_service_generate_client_token_request( # pylint: disable=name-too-long hub: str, *, user_id: Optional[str] = None, - roles: Optional[List[str]] = None, + role: Optional[list[str]] = None, minutes_to_expire: Optional[int] = None, - groups: Optional[List[str]] = None, - client_protocol: Optional[Union[str, _models.WebPubSubClientType]] = None, + group: Optional[list[str]] = None, + client_type: Optional[Union[str, _models.WebPubSubClientType]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -149,14 +134,14 @@ def build_web_pub_sub_service_get_client_access_token_request( # pylint: disabl _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if user_id is not None: _params["userId"] = _SERIALIZER.query("user_id", user_id, "str") - if roles is not None: - _params["roles"] = _SERIALIZER.query("roles", roles, "[str]", div=",") + if role is not None: + _params["role"] = [_SERIALIZER.query("role", q, "str") if q is not None else "" for q in role] if minutes_to_expire is not None: _params["minutesToExpire"] = _SERIALIZER.query("minutes_to_expire", minutes_to_expire, "int") - if groups is not None: - _params["groups"] = _SERIALIZER.query("groups", groups, "[str]", div=",") - if client_protocol is not None: - _params["clientProtocol"] = _SERIALIZER.query("client_protocol", client_protocol, "str") + if group is not None: + _params["group"] = [_SERIALIZER.query("group", q, "str") if q is not None else "" for q in group] + if client_type is not None: + _params["clientType"] = _SERIALIZER.query("client_type", client_type, "str") # Construct headers if accept is not None: @@ -173,8 +158,6 @@ def build_web_pub_sub_service_remove_connections_from_groups_request( # pylint: content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/:removeFromGroups" path_format_arguments = { @@ -189,7 +172,6 @@ def build_web_pub_sub_service_remove_connections_from_groups_request( # pylint: # Construct headers if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -197,12 +179,9 @@ def build_web_pub_sub_service_remove_connections_from_groups_request( # pylint: def build_web_pub_sub_service_close_connection_request( # pylint: disable=name-too-long connection_id: str, hub: str, *, reason: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/connections/{connectionId}" path_format_arguments = { @@ -217,21 +196,15 @@ def build_web_pub_sub_service_close_connection_request( # pylint: disable=name- if reason is not None: _params["reason"] = _SERIALIZER.query("reason", reason, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_connection_exists_request( # pylint: disable=name-too-long connection_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/connections/{connectionId}" path_format_arguments = { @@ -244,21 +217,15 @@ def build_web_pub_sub_service_connection_exists_request( # pylint: disable=name # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_remove_connection_from_all_groups_request( # pylint: disable=name-too-long connection_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/connections/{connectionId}/groups" path_format_arguments = { @@ -271,21 +238,15 @@ def build_web_pub_sub_service_remove_connection_from_all_groups_request( # pyli # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_group_exists_request( # pylint: disable=name-too-long group: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/groups/{group}" path_format_arguments = { @@ -298,21 +259,15 @@ def build_web_pub_sub_service_group_exists_request( # pylint: disable=name-too- # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_close_group_connections_request( # pylint: disable=name-too-long - group: str, hub: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + group: str, hub: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/groups/{group}/:closeConnections" path_format_arguments = { @@ -325,17 +280,14 @@ def build_web_pub_sub_service_close_group_connections_request( # pylint: disabl # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if excluded is not None: - _params["excluded"] = _SERIALIZER.query("excluded", excluded, "[str]", div=",") + _params["excluded"] = [_SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded] if reason is not None: _params["reason"] = _SERIALIZER.query("reason", reason, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) -def build_web_pub_sub_service_list_connections_request( # pylint: disable=name-too-long +def build_web_pub_sub_service_list_connections_in_group_request( # pylint: disable=name-too-long group: str, hub: str, *, @@ -379,12 +331,9 @@ def build_web_pub_sub_service_list_connections_request( # pylint: disable=name- def build_web_pub_sub_service_remove_connection_from_group_request( # pylint: disable=name-too-long group: str, connection_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/groups/{group}/connections/{connectionId}" path_format_arguments = { @@ -398,21 +347,15 @@ def build_web_pub_sub_service_remove_connection_from_group_request( # pylint: d # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_add_connection_to_group_request( # pylint: disable=name-too-long group: str, connection_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/groups/{group}/connections/{connectionId}" path_format_arguments = { @@ -426,10 +369,7 @@ def build_web_pub_sub_service_add_connection_to_group_request( # pylint: disabl # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_revoke_permission_request( # pylint: disable=name-too-long @@ -440,12 +380,9 @@ def build_web_pub_sub_service_revoke_permission_request( # pylint: disable=name target_name: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { @@ -461,13 +398,10 @@ def build_web_pub_sub_service_revoke_permission_request( # pylint: disable=name if target_name is not None: _params["targetName"] = _SERIALIZER.query("target_name", target_name, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) -def build_web_pub_sub_service_has_permission_request( # pylint: disable=name-too-long +def build_web_pub_sub_service_check_permission_request( # pylint: disable=name-too-long permission: Union[str, _models.WebPubSubPermission], connection_id: str, hub: str, @@ -475,12 +409,9 @@ def build_web_pub_sub_service_has_permission_request( # pylint: disable=name-to target_name: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { @@ -496,10 +427,7 @@ def build_web_pub_sub_service_has_permission_request( # pylint: disable=name-to if target_name is not None: _params["targetName"] = _SERIALIZER.query("target_name", target_name, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_grant_permission_request( # pylint: disable=name-too-long @@ -510,12 +438,9 @@ def build_web_pub_sub_service_grant_permission_request( # pylint: disable=name- target_name: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { @@ -531,21 +456,15 @@ def build_web_pub_sub_service_grant_permission_request( # pylint: disable=name- if target_name is not None: _params["targetName"] = _SERIALIZER.query("target_name", target_name, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_user_exists_request( # pylint: disable=name-too-long user_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/users/{userId}" path_format_arguments = { @@ -558,21 +477,15 @@ def build_web_pub_sub_service_user_exists_request( # pylint: disable=name-too-l # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="HEAD", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_close_user_connections_request( # pylint: disable=name-too-long - user_id: str, hub: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + user_id: str, hub: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/users/{userId}/:closeConnections" path_format_arguments = { @@ -585,25 +498,19 @@ def build_web_pub_sub_service_close_user_connections_request( # pylint: disable # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if excluded is not None: - _params["excluded"] = _SERIALIZER.query("excluded", excluded, "[str]", div=",") + _params["excluded"] = [_SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded] if reason is not None: _params["reason"] = _SERIALIZER.query("reason", reason, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_remove_user_from_all_groups_request( # pylint: disable=name-too-long user_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/users/{userId}/groups" path_format_arguments = { @@ -616,21 +523,15 @@ def build_web_pub_sub_service_remove_user_from_all_groups_request( # pylint: di # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_remove_user_from_group_request( # pylint: disable=name-too-long group: str, user_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/users/{userId}/groups/{group}" path_format_arguments = { @@ -644,21 +545,15 @@ def build_web_pub_sub_service_remove_user_from_group_request( # pylint: disable # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_web_pub_sub_service_add_user_to_group_request( # pylint: disable=name-too-long group: str, user_id: str, hub: str, **kwargs: Any ) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-12-01")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/api/hubs/{hub}/users/{userId}/groups/{group}" path_format_arguments = { @@ -672,10 +567,7 @@ def build_web_pub_sub_service_add_user_to_group_request( # pylint: disable=name # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) class _WebPubSubServiceClientOperationsMixin( # pylint: disable=abstract-class-instantiated,too-many-public-methods @@ -733,7 +625,7 @@ def get_service_status(self, **kwargs: Any) -> bool: response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -852,7 +744,7 @@ def add_connections_to_groups( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -861,7 +753,7 @@ def add_connections_to_groups( # pylint: disable=inconsistent-return-statements @distributed_trace def close_all_connections( # pylint: disable=inconsistent-return-statements - self, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close the connections in the hub. @@ -917,14 +809,14 @@ def close_all_connections( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get_client_access_token( + def generate_client_token( self, *, user_id: Optional[str] = None, - roles: Optional[List[str]] = None, + role: Optional[list[str]] = None, minutes_to_expire: Optional[int] = None, - groups: Optional[List[str]] = None, - client_protocol: Optional[Union[str, _models.WebPubSubClientType]] = None, + group: Optional[list[str]] = None, + client_type: Optional[Union[str, _models.WebPubSubClientType]] = None, **kwargs: Any ) -> _models.ClientTokenResponse: """Generate token for the client to connect Azure Web PubSub service. @@ -933,19 +825,18 @@ def get_client_access_token( :keyword user_id: User Id. Default value is None. :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. Default value is + :keyword role: Roles that the connection with the generated token will have. Default value is None. - :paramtype roles: list[str] + :paramtype role: list[str] :keyword minutes_to_expire: The expire time of the generated token. Default value is None. :paramtype minutes_to_expire: int - :keyword groups: Groups that the connection will join when it connects. Default value is None. - :paramtype groups: list[str] - :keyword client_protocol: The type of client. Case-insensitive. If not set, it's "Default". For - Web + :keyword group: Groups that the connection will join when it connects. Default value is None. + :paramtype group: list[str] + :keyword client_type: The type of client. Case-insensitive. If not set, it's "Default". For Web PubSub for Socket.IO, only the default value is supported. For Web PubSub, the - valid values are 'Default' and 'MQTT'. Known values are: "Default" and "mqtt". Default value + valid values are 'Default' and 'MQTT'. Known values are: "Default" and "MQTT". Default value is None. - :paramtype client_protocol: str or ~azure.messaging.webpubsubservice.models.WebPubSubClientType + :paramtype client_type: str or ~azure.messaging.webpubsubservice.models.WebPubSubClientType :return: ClientTokenResponse. The ClientTokenResponse is compatible with MutableMapping :rtype: ~azure.messaging.webpubsubservice.models.ClientTokenResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -963,13 +854,13 @@ def get_client_access_token( cls: ClsType[_models.ClientTokenResponse] = kwargs.pop("cls", None) - _request = build_web_pub_sub_service_get_client_access_token_request( + _request = build_web_pub_sub_service_generate_client_token_request( hub=self._config.hub, user_id=user_id, - roles=roles, + role=role, minutes_to_expire=minutes_to_expire, - groups=groups, - client_protocol=client_protocol, + group=group, + client_type=client_type, api_version=self._config.api_version, headers=_headers, params=_params, @@ -979,6 +870,7 @@ def get_client_access_token( } _request.url = self._client.format_url(_request.url, **path_format_arguments) + _decompress = kwargs.pop("decompress", True) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs @@ -999,7 +891,7 @@ def get_client_access_token( response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) if _stream: - deserialized = response.iter_bytes() + deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: deserialized = _deserialize(_models.ClientTokenResponse, response.json()) @@ -1123,7 +1015,7 @@ def remove_connections_from_groups( # pylint: disable=inconsistent-return-state response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1346,7 +1238,7 @@ def group_exists(self, group: str, **kwargs: Any) -> bool: @distributed_trace def close_group_connections( # pylint: disable=inconsistent-return-statements - self, group: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, group: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections in the specific group. @@ -1406,7 +1298,7 @@ def close_group_connections( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_connections( + def list_connections_in_group( self, group: str, *, @@ -1440,7 +1332,7 @@ def list_connections( _params = kwargs.pop("params", {}) or {} maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.GroupMember]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.GroupMember]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1453,7 +1345,7 @@ def list_connections( def prepare_request(next_link=None): if not next_link: - _request = build_web_pub_sub_service_list_connections_request( + _request = build_web_pub_sub_service_list_connections_in_group_request( group=group, hub=self._config.hub, maxpagesize=maxpagesize, @@ -1494,7 +1386,10 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.GroupMember], deserialized.get("value", [])) + list_of_elem = _deserialize( + list[_models.GroupMember], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1698,7 +1593,7 @@ def revoke_permission( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def has_permission( + def check_permission( self, permission: Union[str, _models.WebPubSubPermission], connection_id: str, @@ -1736,7 +1631,7 @@ def has_permission( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_web_pub_sub_service_has_permission_request( + _request = build_web_pub_sub_service_check_permission_request( permission=permission, connection_id=connection_id, hub=self._config.hub, @@ -1886,7 +1781,7 @@ def user_exists(self, user_id: str, **kwargs: Any) -> bool: @distributed_trace def close_user_connections( # pylint: disable=inconsistent-return-statements - self, user_id: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, user_id: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections for the specific user. diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py index 0ff7b7e0cb95..90c790f6cff3 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py @@ -559,7 +559,22 @@ def get_client_access_token(self, *, client_protocol: Optional[str] = "Default", endpoint, path, hub, self._config.credential.key, jwt_headers=jwt_headers, **kwargs ) else: - token = super().get_client_access_token(client_protocol=client_protocol, **kwargs).get("token") + user_id = kwargs.pop("user_id", None) + roles = kwargs.pop("roles", None) + minutes_to_expire = kwargs.pop("minutes_to_expire", None) + groups = kwargs.pop("groups", None) + token = ( + super() + .generate_client_token( + user_id=user_id, + role=roles, + minutes_to_expire=minutes_to_expire, + group=groups, + client_type=client_protocol, + **kwargs + ) + .get("token") + ) return { "baseUrl": client_url, "token": token, @@ -597,7 +612,7 @@ def list_connections(self, *, group: str, top: Optional[int] = None, **kwargs: A """ # Call the base implementation to get ItemPaged[dict] - paged_json = super().list_connections(group=group, top=top, **kwargs) + paged_json = super().list_connections_in_group(group=group, top=top, **kwargs) # Wrap the iterator to convert each item to GroupMember class GroupMemberPaged(ItemPaged): @@ -1263,6 +1278,31 @@ def send_to_connection( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) + @distributed_trace + def has_permission( + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any + ) -> bool: + """Check if a connection has permission to the specified action. + + Check if a connection has permission to the specified action. + + :param permission: The permission: current supported actions are joinLeaveGroup and + sendToGroup. Known values are: "sendToGroup" and "joinLeaveGroup". Required. + :type permission: str + :param connection_id: Target connection Id. Required. + :type connection_id: str + :keyword target_name: The meaning of the target depends on the specific permission. For + joinLeaveGroup and sendToGroup, targetName is a required parameter standing for + the group name. Default value is None. + :paramtype target_name: str + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + return super().check_permission( + permission=permission, connection_id=connection_id, target_name=target_name, **kwargs + ) + __all__: List[str] = [ "_WebPubSubServiceClientOperationsMixin", diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/model_base.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/model_base.py index 49d5c7259389..7b7f8ba67b53 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/model_base.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/model_base.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -29,6 +29,7 @@ from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null +from azure.core.rest import HttpResponse _LOGGER = logging.getLogger(__name__) @@ -36,6 +37,7 @@ TZ_UTC = timezone.utc _T = typing.TypeVar("_T") +_NONE_TYPE = type(None) def _timedelta_as_isostr(td: timedelta) -> str: @@ -170,6 +172,21 @@ def default(self, o): # pylint: disable=too-many-return-statements r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" ) +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: """Deserialize ISO-8601 formatted string into Datetime object. @@ -201,7 +218,7 @@ def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: test_utc = date_obj.utctimetuple() if test_utc.tm_year > 9999 or test_utc.tm_year < 1: raise OverflowError("Hit max or min date") - return date_obj + return date_obj # type: ignore[no-any-return] def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: @@ -255,7 +272,7 @@ def _deserialize_time(attr: typing.Union[str, time]) -> time: """ if isinstance(attr, time): return attr - return isodate.parse_time(attr) + return isodate.parse_time(attr) # type: ignore[no-any-return] def _deserialize_bytes(attr): @@ -314,6 +331,8 @@ def _deserialize_int_as_str(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore @@ -345,16 +364,46 @@ def _get_model(module_name: str, model_name: str): class _MyMutableMapping(MutableMapping[str, typing.Any]): - def __init__(self, data: typing.Dict[str, typing.Any]) -> None: + def __init__(self, data: dict[str, typing.Any]) -> None: self._data = data def __contains__(self, key: typing.Any) -> bool: return key in self._data def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized return self._data.__getitem__(key) def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass self._data.__setitem__(key, value) def __delitem__(self, key: str) -> None: @@ -425,7 +474,7 @@ def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: return self._data.pop(key) return self._data.pop(key, default) - def popitem(self) -> typing.Tuple[str, typing.Any]: + def popitem(self) -> tuple[str, typing.Any]: """ Removes and returns some (key, value) pair :returns: The (key, value) pair. @@ -466,6 +515,8 @@ def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: return self._data.setdefault(key, default) def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data try: other_model = self.__class__(other) except Exception: @@ -482,6 +533,8 @@ def _is_model(obj: typing.Any) -> bool: def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) return [_serialize(x, format) for x in o] if isinstance(o, dict): return {k: _serialize(v, format) for k, v in o.items()} @@ -513,9 +566,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m return o -def _get_rest_field( - attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str -) -> typing.Optional["_RestField"]: +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: try: return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) except StopIteration: @@ -538,7 +589,7 @@ class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated # could not see _attr_to_rest_field directly because subclass inherits it from parent class - _calculated: typing.Set[str] = set() + _calculated: set[str] = set() def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ @@ -579,6 +630,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if len(items) > 0: existed_attr_keys.append(xml_name) dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = [] continue # text element is primitive type @@ -623,7 +677,7 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order - attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") } annotations = { @@ -638,7 +692,7 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) if not rf._rest_name_input: rf._rest_name_input = attr - cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -680,7 +734,7 @@ def _deserialize(cls, data, exist_discriminators): mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member return mapped_cls._deserialize(data, exist_discriminators) - def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: """Return a dict that can be turned into json using json.dump. :keyword bool exclude_readonly: Whether to remove the readonly properties. @@ -740,7 +794,7 @@ def _deserialize_with_union(deserializers, obj): def _deserialize_dict( value_deserializer: typing.Optional[typing.Callable], module: typing.Optional[str], - obj: typing.Dict[typing.Any, typing.Any], + obj: dict[typing.Any, typing.Any], ): if obj is None: return obj @@ -750,7 +804,7 @@ def _deserialize_dict( def _deserialize_multiple_sequence( - entry_deserializers: typing.List[typing.Optional[typing.Callable]], + entry_deserializers: list[typing.Optional[typing.Callable]], module: typing.Optional[str], obj, ): @@ -759,6 +813,14 @@ def _deserialize_multiple_sequence( return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + def _deserialize_sequence( deserializer: typing.Optional[typing.Callable], module: typing.Optional[str], @@ -768,17 +830,30 @@ def _deserialize_sequence( return obj if isinstance(obj, ET.Element): obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) -def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: return sorted( types, key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), ) -def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches annotation: typing.Any, module: typing.Optional[str], rf: typing.Optional["_RestField"] = None, @@ -818,16 +893,18 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur # is it optional? try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True if len(annotation.__args__) <= 2: # pyright: ignore if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore ) return functools.partial(_deserialize_with_optional, if_obj_deserializer) # the type is Optional[Union[...]], we need to remove the None type from the Union annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass @@ -843,7 +920,10 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur return functools.partial(_deserialize_with_union, deserializers) try: - if annotation._name == "Dict": # pyright: ignore + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": value_deserializer = _get_deserialize_callable_from_annotation( annotation.__args__[1], module, rf # pyright: ignore ) @@ -856,7 +936,10 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur except (AttributeError, IndexError): pass try: - if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: if len(annotation.__args__) > 1: # pyright: ignore entry_deserializers = [ _get_deserialize_callable_from_annotation(dt, module, rf) @@ -905,16 +988,20 @@ def _deserialize_with_callable( return float(value.text) if value.text else None if deserializer is bool: return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None if deserializer is None: return value if deserializer in [int, float, bool]: return deserializer(value) if isinstance(deserializer, CaseInsensitiveEnumMeta): try: - return deserializer(value) + return deserializer(value.text if isinstance(value, ET.Element) else value) except ValueError: # for unknown value, return raw value - return value + return value.text if isinstance(value, ET.Element) else value if isinstance(deserializer, type) and issubclass(deserializer, Model): return deserializer._deserialize(value, []) return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) @@ -940,14 +1027,14 @@ def _deserialize( def _failsafe_deserialize( deserializer: typing.Any, - value: typing.Any, + response: HttpResponse, module: typing.Optional[str] = None, rf: typing.Optional["_RestField"] = None, format: typing.Optional[str] = None, ) -> typing.Any: try: - return _deserialize(deserializer, value, module, rf, format) - except DeserializationError: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except _LOGGER.warning( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -956,17 +1043,18 @@ def _failsafe_deserialize( def _failsafe_deserialize_xml( deserializer: typing.Any, - value: typing.Any, + response: HttpResponse, ) -> typing.Any: try: - return _deserialize_xml(deserializer, value) - except DeserializationError: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except _LOGGER.warning( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) return None +# pylint: disable=too-many-instance-attributes class _RestField: def __init__( self, @@ -974,11 +1062,11 @@ def __init__( name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin is_discriminator: bool = False, - visibility: typing.Optional[typing.List[str]] = None, + visibility: typing.Optional[list[str]] = None, default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, ): self._type = type self._rest_name_input = name @@ -986,6 +1074,7 @@ def __init__( self._is_discriminator = is_discriminator self._visibility = visibility self._is_model = False + self._is_optional = False self._default = default self._format = format self._is_multipart_file_input = is_multipart_file_input @@ -993,7 +1082,11 @@ def __init__( @property def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result @property def _rest_name(self) -> str: @@ -1004,14 +1097,37 @@ def _rest_name(self) -> str: def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class - item = obj.get(self._rest_name) + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) if item is None: return item if self._is_model: return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + if value is None: # we want to wipe out entries if users set attr to None try: @@ -1036,11 +1152,11 @@ def rest_field( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[typing.List[str]] = None, + visibility: typing.Optional[list[str]] = None, default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, ) -> typing.Any: return _RestField( name=name, @@ -1057,8 +1173,8 @@ def rest_discriminator( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[typing.List[str]] = None, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, ) -> typing.Any: return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) @@ -1077,9 +1193,9 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: def _get_element( o: typing.Any, exclude_readonly: bool = False, - parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, wrapped_element: typing.Optional[ET.Element] = None, -) -> typing.Union[ET.Element, typing.List[ET.Element]]: +) -> typing.Union[ET.Element, list[ET.Element]]: if _is_model(o): model_meta = getattr(o, "_xml", {}) @@ -1168,7 +1284,7 @@ def _get_element( def _get_wrapped_element( v: typing.Any, exclude_readonly: bool, - meta: typing.Optional[typing.Dict[str, typing.Any]], + meta: typing.Optional[dict[str, typing.Any]], ) -> ET.Element: wrapped_element = _create_xml_element( meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None @@ -1179,7 +1295,7 @@ def _get_wrapped_element( _get_element(v, exclude_readonly, meta, wrapped_element) else: wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element + return wrapped_element # type: ignore[no-any-return] def _get_primitive_type_value(v) -> str: @@ -1192,7 +1308,9 @@ def _get_primitive_type_value(v) -> str: return str(v) -def _create_xml_element(tag, prefix=None, ns=None): +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: if prefix and ns: ET.register_namespace(prefix, ns) if ns: @@ -1211,7 +1329,7 @@ def _deserialize_xml( def _convert_element(e: ET.Element): # dict case if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: - dict_result: typing.Dict[str, typing.Any] = {} + dict_result: dict[str, typing.Any] = {} for child in e: if dict_result.get(child.tag) is not None: if isinstance(dict_result[child.tag], list): @@ -1224,7 +1342,7 @@ def _convert_element(e: ET.Element): return dict_result # array case if len(e) > 0: - array_result: typing.List[typing.Any] = [] + array_result: list[typing.Any] = [] for child in e: array_result.append(_convert_element(child)) return array_result diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/serialization.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/serialization.py index eb86ea23c965..81ec1de5922b 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/serialization.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_utils/serialization.py @@ -21,7 +21,6 @@ import sys import codecs from typing import ( - Dict, Any, cast, Optional, @@ -31,7 +30,6 @@ Mapping, Callable, MutableMapping, - List, ) try: @@ -229,12 +227,12 @@ class Model: serialization and deserialization. """ - _subtype_map: Dict[str, Dict[str, Any]] = {} - _attribute_map: Dict[str, Dict[str, Any]] = {} - _validation: Dict[str, Dict[str, Any]] = {} + _subtype_map: dict[str, dict[str, Any]] = {} + _attribute_map: dict[str, dict[str, Any]] = {} + _validation: dict[str, dict[str, Any]] = {} def __init__(self, **kwargs: Any) -> None: - self.additional_properties: Optional[Dict[str, Any]] = {} + self.additional_properties: Optional[dict[str, Any]] = {} for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) @@ -311,7 +309,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: def as_dict( self, keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -380,7 +378,7 @@ def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: def from_dict( cls, data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, ) -> Self: """Parse a dict using given key extractor return a model. @@ -414,7 +412,7 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod @@ -528,7 +526,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True @@ -579,7 +577,7 @@ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, to if attr_name == "additional_properties" and attr_desc["key"] == "": if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) + serialized |= target_obj.additional_properties continue try: @@ -789,7 +787,7 @@ def serialize_data(self, data, data_type, **kwargs): # If dependencies is empty, try with current data class # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -823,13 +821,20 @@ def serialize_basic(cls, data, data_type, **kwargs): :param str data_type: Type of object in the iterable. :rtype: str, int, float, bool :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @classmethod def serialize_unicode(cls, data): @@ -1184,7 +1189,7 @@ def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argumen while "." in key: # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1386,7 +1391,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} + self.dependencies: dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1759,7 +1764,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1785,7 +1790,11 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_client.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_client.py index e7211a2c8afc..f64d86f7cb3a 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_client.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_client.py @@ -30,10 +30,11 @@ class WebPubSubServiceClient(_WebPubSubServiceClientOperationsMixin): :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. Required. + alpha-numeric characters or underscore. Required. :type hub: str - :keyword api_version: The API version to use for this operation. Default value is "2024-12-01". - Note that overriding this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2024-12-01". + Default value is "2024-12-01". Note that overriding this default value may result in + unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py index d0e17a5c296f..6c80ffbbca8f 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py @@ -27,10 +27,11 @@ class WebPubSubServiceClientConfiguration: # pylint: disable=too-many-instance- :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. Required. + alpha-numeric characters or underscore. Required. :type hub: str - :keyword api_version: The API version to use for this operation. Default value is "2024-12-01". - Note that overriding this default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2024-12-01". + Default value is "2024-12-01". Note that overriding this default value may result in + unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py index 7dcab626dbea..abb5c5130cd5 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py @@ -9,7 +9,7 @@ from collections.abc import MutableMapping from io import IOBase import json -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse from azure.core import AsyncPipelineClient @@ -35,17 +35,17 @@ build_web_pub_sub_service_add_connection_to_group_request, build_web_pub_sub_service_add_connections_to_groups_request, build_web_pub_sub_service_add_user_to_group_request, + build_web_pub_sub_service_check_permission_request, build_web_pub_sub_service_close_all_connections_request, build_web_pub_sub_service_close_connection_request, build_web_pub_sub_service_close_group_connections_request, build_web_pub_sub_service_close_user_connections_request, build_web_pub_sub_service_connection_exists_request, - build_web_pub_sub_service_get_client_access_token_request, + build_web_pub_sub_service_generate_client_token_request, build_web_pub_sub_service_get_service_status_request, build_web_pub_sub_service_grant_permission_request, build_web_pub_sub_service_group_exists_request, - build_web_pub_sub_service_has_permission_request, - build_web_pub_sub_service_list_connections_request, + build_web_pub_sub_service_list_connections_in_group_request, build_web_pub_sub_service_remove_connection_from_all_groups_request, build_web_pub_sub_service_remove_connection_from_group_request, build_web_pub_sub_service_remove_connections_from_groups_request, @@ -60,7 +60,7 @@ JSON = MutableMapping[str, Any] T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] class _WebPubSubServiceClientOperationsMixin( # pylint: disable=abstract-class-instantiated,too-many-public-methods @@ -118,7 +118,7 @@ async def get_service_status(self, **kwargs: Any) -> bool: response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -237,7 +237,7 @@ async def add_connections_to_groups( response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -246,7 +246,7 @@ async def add_connections_to_groups( @distributed_trace_async async def close_all_connections( - self, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close the connections in the hub. @@ -302,14 +302,14 @@ async def close_all_connections( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get_client_access_token( + async def generate_client_token( self, *, user_id: Optional[str] = None, - roles: Optional[List[str]] = None, + role: Optional[list[str]] = None, minutes_to_expire: Optional[int] = None, - groups: Optional[List[str]] = None, - client_protocol: Optional[Union[str, _models.WebPubSubClientType]] = None, + group: Optional[list[str]] = None, + client_type: Optional[Union[str, _models.WebPubSubClientType]] = None, **kwargs: Any ) -> _models.ClientTokenResponse: """Generate token for the client to connect Azure Web PubSub service. @@ -318,19 +318,18 @@ async def get_client_access_token( :keyword user_id: User Id. Default value is None. :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. Default value is + :keyword role: Roles that the connection with the generated token will have. Default value is None. - :paramtype roles: list[str] + :paramtype role: list[str] :keyword minutes_to_expire: The expire time of the generated token. Default value is None. :paramtype minutes_to_expire: int - :keyword groups: Groups that the connection will join when it connects. Default value is None. - :paramtype groups: list[str] - :keyword client_protocol: The type of client. Case-insensitive. If not set, it's "Default". For - Web + :keyword group: Groups that the connection will join when it connects. Default value is None. + :paramtype group: list[str] + :keyword client_type: The type of client. Case-insensitive. If not set, it's "Default". For Web PubSub for Socket.IO, only the default value is supported. For Web PubSub, the - valid values are 'Default' and 'MQTT'. Known values are: "Default" and "mqtt". Default value + valid values are 'Default' and 'MQTT'. Known values are: "Default" and "MQTT". Default value is None. - :paramtype client_protocol: str or ~azure.messaging.webpubsubservice.models.WebPubSubClientType + :paramtype client_type: str or ~azure.messaging.webpubsubservice.models.WebPubSubClientType :return: ClientTokenResponse. The ClientTokenResponse is compatible with MutableMapping :rtype: ~azure.messaging.webpubsubservice.models.ClientTokenResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -348,13 +347,13 @@ async def get_client_access_token( cls: ClsType[_models.ClientTokenResponse] = kwargs.pop("cls", None) - _request = build_web_pub_sub_service_get_client_access_token_request( + _request = build_web_pub_sub_service_generate_client_token_request( hub=self._config.hub, user_id=user_id, - roles=roles, + role=role, minutes_to_expire=minutes_to_expire, - groups=groups, - client_protocol=client_protocol, + group=group, + client_type=client_type, api_version=self._config.api_version, headers=_headers, params=_params, @@ -364,6 +363,7 @@ async def get_client_access_token( } _request.url = self._client.format_url(_request.url, **path_format_arguments) + _decompress = kwargs.pop("decompress", True) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access _request, stream=_stream, **kwargs @@ -384,7 +384,7 @@ async def get_client_access_token( response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) if _stream: - deserialized = response.iter_bytes() + deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: deserialized = _deserialize(_models.ClientTokenResponse, response.json()) @@ -508,7 +508,7 @@ async def remove_connections_from_groups( response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -727,7 +727,7 @@ async def group_exists(self, group: str, **kwargs: Any) -> bool: @distributed_trace_async async def close_group_connections( - self, group: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, group: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections in the specific group. @@ -787,7 +787,7 @@ async def close_group_connections( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_connections( + def list_connections_in_group( self, group: str, *, @@ -822,7 +822,7 @@ def list_connections( _params = kwargs.pop("params", {}) or {} maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.GroupMember]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.GroupMember]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -835,7 +835,7 @@ def list_connections( def prepare_request(next_link=None): if not next_link: - _request = build_web_pub_sub_service_list_connections_request( + _request = build_web_pub_sub_service_list_connections_in_group_request( group=group, hub=self._config.hub, maxpagesize=maxpagesize, @@ -876,7 +876,10 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.GroupMember], deserialized.get("value", [])) + list_of_elem = _deserialize( + list[_models.GroupMember], + deserialized.get("value", []), + ) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1076,7 +1079,7 @@ async def revoke_permission( return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def has_permission( + async def check_permission( self, permission: Union[str, _models.WebPubSubPermission], connection_id: str, @@ -1114,7 +1117,7 @@ async def has_permission( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_web_pub_sub_service_has_permission_request( + _request = build_web_pub_sub_service_check_permission_request( permission=permission, connection_id=connection_id, hub=self._config.hub, @@ -1264,7 +1267,7 @@ async def user_exists(self, user_id: str, **kwargs: Any) -> bool: @distributed_trace_async async def close_user_connections( - self, user_id: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + self, user_id: str, *, excluded: Optional[list[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections for the specific user. diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py index e9556cac6ecd..62bf8bed8a5e 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py @@ -111,12 +111,12 @@ async def get_client_access_token( # pylint: disable=arguments-differ **kwargs ) else: - access_token = await super().get_client_access_token( + access_token = await super().generate_client_token( user_id=user_id, - roles=roles, + role=roles, minutes_to_expire=minutes_to_expire, - groups=groups, - client_protocol=client_protocol, + group=groups, + client_type=client_protocol, **kwargs ) token = access_token.get("token") @@ -157,7 +157,7 @@ def list_connections(self, *, group: str, top: Optional[int] = None, **kwargs: A """ - paged_json = super().list_connections(group=group, top=top, **kwargs) + paged_json = super().list_connections_in_group(group=group, top=top, **kwargs) class GroupMemberPaged(AsyncItemPaged): def __aiter__(self_inner): @@ -839,6 +839,31 @@ async def send_to_user( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) + @distributed_trace_async + async def has_permission( + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any + ) -> bool: + """Check if a connection has permission to the specified action. + + Check if a connection has permission to the specified action. + + :param permission: The permission: current supported actions are joinLeaveGroup and + sendToGroup. Known values are: "sendToGroup" and "joinLeaveGroup". Required. + :type permission: str + :param connection_id: Target connection Id. Required. + :type connection_id: str + :keyword target_name: The meaning of the target depends on the specific permission. For + joinLeaveGroup and sendToGroup, targetName is a required parameter standing for + the group name. Default value is None. + :paramtype target_name: str + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + return await super().check_permission( + permission=permission, connection_id=connection_id, target_name=target_name, **kwargs + ) + __all__: List[str] = [ "_WebPubSubServiceClientOperationsMixin" diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_enums.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_enums.py index 33fd79d9b4c6..e2d5857c65f8 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_enums.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_enums.py @@ -14,20 +14,20 @@ class MessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Content type for HTTP headers in message operations (closed union for HTTP compliance).""" APPLICATION_JSON = "application/json" - """Content Type 'application/json'""" + """Content Type 'application/json'.""" APPLICATION_OCTET_STREAM = "application/octet-stream" - """Content Type 'application/octet-stream'""" + """Content Type 'application/octet-stream'.""" TEXT_PLAIN = "text/plain" - """Content Type 'text/plain'""" + """Content Type 'text/plain'.""" class ResponseContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Content type for response headers (closed union for HTTP compliance).""" APPLICATION_JSON = "application/json" - """Content Type 'application/json'""" + """Content Type 'application/json'.""" TEXT_JSON = "text/json" - """Content Type 'text/json'""" + """Content Type 'text/json'.""" class WebPubSubClientType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -35,7 +35,7 @@ class WebPubSubClientType(str, Enum, metaclass=CaseInsensitiveEnumMeta): DEFAULT = "Default" """Default value.""" - MQTT = "mqtt" + MQTT = "MQTT" """MQTT client.""" diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_models.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_models.py index 1399d256a226..d6acc676b2e1 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_models.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/models/_models.py @@ -7,7 +7,7 @@ # -------------------------------------------------------------------------- # pylint: disable=useless-super-delegation -from typing import Any, List, Mapping, Optional, overload +from typing import Any, Mapping, Optional, overload from .._utils.model_base import Model as _Model, rest_field @@ -22,7 +22,7 @@ class AddToGroupsRequest(_Model): :vartype filter: str """ - groups: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + groups: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Target groups.""" filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Following OData filter syntax to filter out the subscribers receiving the messages.""" @@ -31,7 +31,7 @@ class AddToGroupsRequest(_Model): def __init__( self, *, - groups: Optional[List[str]] = None, + groups: Optional[list[str]] = None, filter: Optional[str] = None, # pylint: disable=redefined-builtin ) -> None: ... @@ -117,7 +117,7 @@ class RemoveFromGroupsRequest(_Model): :vartype filter: str """ - groups: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + groups: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Target groups.""" filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Following OData filter syntax to filter out the subscribers receiving the messages.""" @@ -126,7 +126,7 @@ class RemoveFromGroupsRequest(_Model): def __init__( self, *, - groups: Optional[List[str]] = None, + groups: Optional[list[str]] = None, filter: Optional[str] = None, # pylint: disable=redefined-builtin ) -> None: ... diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/health_api_get_service_status.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/health_api_get_service_status.py new file mode 100644 index 000000000000..edde9c3a008f --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/health_api_get_service_status.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python health_api_get_service_status.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.get_service_status() + print(response) + + +# x-ms-original-file: 2024-12-01/HealthApi_GetServiceStatus.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connection_to_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connection_to_group.py new file mode 100644 index 000000000000..b4ccdbb9bc16 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connection_to_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_add_connection_to_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.add_connection_to_group( + group="group1", + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_AddConnectionToGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connections_to_groups.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connections_to_groups.py new file mode 100644 index 000000000000..1f7e682dff25 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_connections_to_groups.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_add_connections_to_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.add_connections_to_groups( + groups_to_add={"filter": "startswith(userId, 'listener-')", "groups": ["group1", "group2"]}, + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_AddConnectionsToGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_user_to_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_user_to_group.py new file mode 100644 index 000000000000..3b8ac6b722b4 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_add_user_to_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_add_user_to_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.add_user_to_group( + group="group1", + user_id="user1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_AddUserToGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_check_permission.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_check_permission.py new file mode 100644 index 000000000000..091ab7fde3f2 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_check_permission.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_check_permission.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.check_permission( + permission="joinLeaveGroup", + connection_id="connection1", + ) + print(response) + + +# x-ms-original-file: 2024-12-01/WebPubSub_CheckPermission.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_all_connections.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_all_connections.py new file mode 100644 index 000000000000..d503f76342c6 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_all_connections.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_close_all_connections.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.close_all_connections() + + +# x-ms-original-file: 2024-12-01/WebPubSub_CloseAllConnections.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_connection.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_connection.py new file mode 100644 index 000000000000..3c999b87664e --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_connection.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_close_connection.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.close_connection( + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_CloseConnection.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_group_connections.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_group_connections.py new file mode 100644 index 000000000000..1bc3ddf54ed6 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_group_connections.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_close_group_connections.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.close_group_connections( + group="group1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_CloseGroupConnections.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_user_connections.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_user_connections.py new file mode 100644 index 000000000000..e2e8d9ddc9a9 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_close_user_connections.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_close_user_connections.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.close_user_connections( + user_id="user1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_CloseUserConnections.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_connection_exists.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_connection_exists.py new file mode 100644 index 000000000000..8d9ec9900fd8 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_connection_exists.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_connection_exists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.connection_exists( + connection_id="connection1", + ) + print(response) + + +# x-ms-original-file: 2024-12-01/WebPubSub_ConnectionExists.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_generate_client_token.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_generate_client_token.py new file mode 100644 index 000000000000..27cdea9179f5 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_generate_client_token.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_generate_client_token.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.generate_client_token() + print(response) + + +# x-ms-original-file: 2024-12-01/WebPubSub_GenerateClientToken.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_grant_permission.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_grant_permission.py new file mode 100644 index 000000000000..11cbe377c479 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_grant_permission.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_grant_permission.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.grant_permission( + permission="joinLeaveGroup", + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_GrantPermission.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_group_exists.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_group_exists.py new file mode 100644 index 000000000000..1f10be224367 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_group_exists.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_group_exists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.group_exists( + group="group1", + ) + print(response) + + +# x-ms-original-file: 2024-12-01/WebPubSub_GroupExists.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_list_connections_in_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_list_connections_in_group.py new file mode 100644 index 000000000000..b0ef64cceba2 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_list_connections_in_group.py @@ -0,0 +1,43 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_list_connections_in_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.list_connections_in_group( + group="group1", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2024-12-01/WebPubSub_ListConnectionsInGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_all_groups.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_all_groups.py new file mode 100644 index 000000000000..83a9285e7528 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_all_groups.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_remove_connection_from_all_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.remove_connection_from_all_groups( + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RemoveConnectionFromAllGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_group.py new file mode 100644 index 000000000000..4cb8a14a8a9a --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connection_from_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_remove_connection_from_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.remove_connection_from_group( + group="group1", + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RemoveConnectionFromGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connections_from_groups.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connections_from_groups.py new file mode 100644 index 000000000000..06a364dcc54b --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_connections_from_groups.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_remove_connections_from_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.remove_connections_from_groups( + groups_to_remove={"filter": "startswith(userId, 'listener-')", "groups": ["group1", "group2"]}, + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RemoveConnectionsFromGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_all_groups.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_all_groups.py new file mode 100644 index 000000000000..1eae59a1b181 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_all_groups.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_remove_user_from_all_groups.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.remove_user_from_all_groups( + user_id="user1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RemoveUserFromAllGroups.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_group.py new file mode 100644 index 000000000000..78950528bf14 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_remove_user_from_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_remove_user_from_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.remove_user_from_group( + group="group1", + user_id="user1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RemoveUserFromGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_revoke_permission.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_revoke_permission.py new file mode 100644 index 000000000000..cbee8aa939c7 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_revoke_permission.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_revoke_permission.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.revoke_permission( + permission="joinLeaveGroup", + connection_id="connection1", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_RevokePermission.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_all.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_all.py new file mode 100644 index 000000000000..8f322a87bfde --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_all.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_send_to_all.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.send_to_all( + message="TWVzc2FnZSB0byBzZW5k", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_SendToAll.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_connection.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_connection.py new file mode 100644 index 000000000000..4e196f258373 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_connection.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_send_to_connection.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.send_to_connection( + connection_id="connection1", + message="TWVzc2FnZSB0byBzZW5k", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_SendToConnection.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_group.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_group.py new file mode 100644 index 000000000000..a0c01348ea1d --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_group.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_send_to_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.send_to_group( + group="group1", + message="TWVzc2FnZSB0byBzZW5k", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_SendToGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_user.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_user.py new file mode 100644 index 000000000000..9cb48ca2355f --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_send_to_user.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_send_to_user.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + client.send_to_user( + user_id="user1", + message="TWVzc2FnZSB0byBzZW5k", + ) + + +# x-ms-original-file: 2024-12-01/WebPubSub_SendToUser.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_user_exists.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_user_exists.py new file mode 100644 index 000000000000..006a53987d35 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_samples/web_pub_sub_user_exists.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.messaging.webpubsubservice import WebPubSubServiceClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-messaging-webpubsubservice +# USAGE + python web_pub_sub_user_exists.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = WebPubSubServiceClient( + endpoint="ENDPOINT", + credential=DefaultAzureCredential(), + hub="HUB", + ) + + response = client.user_exists( + user_id="user1", + ) + print(response) + + +# x-ms-original-file: 2024-12-01/WebPubSub_UserExists.json +if __name__ == "__main__": + main() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub.py deleted file mode 100644 index 08ea4202d928..000000000000 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub.py +++ /dev/null @@ -1,296 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# import pytest -# from devtools_testutils import recorded_by_proxy -# from .testpreparer import WebPubSubClientTestBase, WebPubSubPreparer - - -# @pytest.mark.skip("you may need to update the auto-generated test case before run it") -# class TestWebPubSub(WebPubSubClientTestBase): -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_get_service_status(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.get_service_status() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_add_connections_to_groups(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.add_connections_to_groups( -# groups_to_add={"filter": "str", "groups": ["str"]}, -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_close_all_connections(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.close_all_connections() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_get_client_access_token(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.get_client_access_token() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_remove_connections_from_groups(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.remove_connections_from_groups( -# groups_to_remove={"filter": "str", "groups": ["str"]}, -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_send_to_all(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.send_to_all( -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_close_connection(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.close_connection( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_connection_exists(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.connection_exists( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_send_to_connection(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.send_to_connection( -# connection_id="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_remove_connection_from_all_groups(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.remove_connection_from_all_groups( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_group_exists(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.group_exists( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_close_group_connections(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.close_group_connections( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_send_to_group(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.send_to_group( -# group="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_list_connections(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.list_connections( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_remove_connection_from_group(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.remove_connection_from_group( -# group="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_add_connection_to_group(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.add_connection_to_group( -# group="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_revoke_permission(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.revoke_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_has_permission(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.has_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_grant_permission(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.grant_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_user_exists(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.user_exists( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_close_user_connections(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.close_user_connections( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_send_to_user(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.send_to_user( -# user_id="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_remove_user_from_all_groups(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.remove_user_from_all_groups( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_remove_user_from_group(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.remove_user_from_group( -# group="str", -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy -# def test_add_user_to_group(self, webpubsub_endpoint): -# client = self.create_client(endpoint=webpubsub_endpoint) -# response = client.add_user_to_group( -# group="str", -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_async.py deleted file mode 100644 index 855f7f3733bc..000000000000 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_async.py +++ /dev/null @@ -1,297 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# import pytest -# from devtools_testutils.aio import recorded_by_proxy_async -# from .testpreparer import WebPubSubPreparer -# from .testpreparer_async import WebPubSubClientTestBaseAsync - - -# @pytest.mark.skip("you may need to update the auto-generated test case before run it") -# class TestWebPubSubAsync(WebPubSubClientTestBaseAsync): -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_get_service_status(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.get_service_status() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_add_connections_to_groups(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.add_connections_to_groups( -# groups_to_add={"filter": "str", "groups": ["str"]}, -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_close_all_connections(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.close_all_connections() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_get_client_access_token(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.get_client_access_token() - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_remove_connections_from_groups(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.remove_connections_from_groups( -# groups_to_remove={"filter": "str", "groups": ["str"]}, -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_send_to_all(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.send_to_all( -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_close_connection(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.close_connection( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_connection_exists(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.connection_exists( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_send_to_connection(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.send_to_connection( -# connection_id="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_remove_connection_from_all_groups(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.remove_connection_from_all_groups( -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_group_exists(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.group_exists( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_close_group_connections(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.close_group_connections( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_send_to_group(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.send_to_group( -# group="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_list_connections(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.list_connections( -# group="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_remove_connection_from_group(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.remove_connection_from_group( -# group="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_add_connection_to_group(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.add_connection_to_group( -# group="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_revoke_permission(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.revoke_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_has_permission(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.has_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_grant_permission(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.grant_permission( -# permission="str", -# connection_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_user_exists(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.user_exists( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_close_user_connections(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.close_user_connections( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_send_to_user(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.send_to_user( -# user_id="str", -# message=bytes("bytes", encoding="utf-8"), -# content_type="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_remove_user_from_all_groups(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.remove_user_from_all_groups( -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_remove_user_from_group(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.remove_user_from_group( -# group="str", -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... - -# @WebPubSubPreparer() -# @recorded_by_proxy_async -# async def test_add_user_to_group(self, webpubsub_endpoint): -# client = self.create_async_client(endpoint=webpubsub_endpoint) -# response = await client.add_user_to_group( -# group="str", -# user_id="str", -# ) - -# # please add some check logic here by yourself -# # ... diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service.py index 41e46f48f8b5..5d0e34e23fbd 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service.py @@ -43,9 +43,9 @@ def test_close_all_connections(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy - def test_get_client_access_token(self, webpubsubservice_endpoint): + def test_generate_client_token(self, webpubsubservice_endpoint): client = self.create_client(endpoint=webpubsubservice_endpoint) - response = client.get_client_access_token() + response = client.generate_client_token() # please add some check logic here by yourself # ... @@ -156,9 +156,9 @@ def test_send_to_group(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy - def test_list_connections(self, webpubsubservice_endpoint): + def test_list_connections_in_group(self, webpubsubservice_endpoint): client = self.create_client(endpoint=webpubsubservice_endpoint) - response = client.list_connections( + response = client.list_connections_in_group( group="str", ) result = [r for r in response] @@ -203,9 +203,9 @@ def test_revoke_permission(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy - def test_has_permission(self, webpubsubservice_endpoint): + def test_check_permission(self, webpubsubservice_endpoint): client = self.create_client(endpoint=webpubsubservice_endpoint) - response = client.has_permission( + response = client.check_permission( permission="str", connection_id="str", ) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service_async.py index 28fb69f3bee1..a0d030fcf75d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service_async.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/generated_tests/test_web_pub_sub_service_async.py @@ -44,9 +44,9 @@ async def test_close_all_connections(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy_async - async def test_get_client_access_token(self, webpubsubservice_endpoint): + async def test_generate_client_token(self, webpubsubservice_endpoint): client = self.create_async_client(endpoint=webpubsubservice_endpoint) - response = await client.get_client_access_token() + response = await client.generate_client_token() # please add some check logic here by yourself # ... @@ -157,9 +157,9 @@ async def test_send_to_group(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy_async - async def test_list_connections(self, webpubsubservice_endpoint): + async def test_list_connections_in_group(self, webpubsubservice_endpoint): client = self.create_async_client(endpoint=webpubsubservice_endpoint) - response = client.list_connections( + response = client.list_connections_in_group( group="str", ) result = [r async for r in response] @@ -204,9 +204,9 @@ async def test_revoke_permission(self, webpubsubservice_endpoint): @WebPubSubServicePreparer() @recorded_by_proxy_async - async def test_has_permission(self, webpubsubservice_endpoint): + async def test_check_permission(self, webpubsubservice_endpoint): client = self.create_async_client(endpoint=webpubsubservice_endpoint) - response = await client.has_permission( + response = await client.check_permission( permission="str", connection_id="str", ) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/pyproject.toml b/sdk/webpubsub/azure-messaging-webpubsubservice/pyproject.toml index 5a8b1e09d60b..3a08ab67322d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/pyproject.toml +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/pyproject.toml @@ -1,3 +1,65 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-messaging-webpubsubservice" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure WebPubSub Service Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.messaging.webpubsubservice._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.messaging", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] pylint = false pyright = false diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/setup.py b/sdk/webpubsub/azure-messaging-webpubsubservice/setup.py deleted file mode 100644 index 178d516750fa..000000000000 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/setup.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -import os -import re -from setuptools import setup, find_packages - - -PACKAGE_NAME = "azure-messaging-webpubsubservice" -PACKAGE_PPRINT_NAME = "Azure WebPubSub Service" -PACKAGE_NAMESPACE = "azure.messaging.webpubsubservice" - -# a.b.c => a/b/c -package_folder_path = PACKAGE_NAMESPACE.replace(".", "/") - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError("Cannot find version information") - - -setup( - name=PACKAGE_NAME, - version=version, - description="Microsoft Corporation {} Client Library for Python".format(PACKAGE_PPRINT_NAME), - long_description=open("README.md", "r").read(), - long_description_content_type="text/markdown", - license="MIT License", - author="Microsoft Corporation", - author_email="azpysdkhelp@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", - keywords="azure, azure sdk", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - "tests", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - "azure.messaging", - ] - ), - include_package_data=True, - package_data={ - "azure.messaging.webpubsubservice": ["py.typed"], - }, - install_requires=[ - "isodate>=0.6.1", - "azure-core>=1.35.0", - "typing-extensions>=4.6.0", - ], - python_requires=">=3.9", -) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/conftest.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/conftest.py index b03bc2e970d5..cd6c1afb6d99 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/conftest.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/conftest.py @@ -3,10 +3,14 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # ------------------------------------------------------------------------- +import os import pytest +from dotenv import load_dotenv from devtools_testutils import test_proxy, set_custom_default_matcher +load_dotenv(os.path.join(os.path.dirname(__file__), ".env"), override=False) + # autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method @pytest.fixture(scope="session", autouse=True) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage.py new file mode 100644 index 000000000000..12c020c6cb40 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage.py @@ -0,0 +1,261 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import pytest +from azure.core.exceptions import ResourceNotFoundError +from devtools_testutils import recorded_by_proxy +from testcase import WebpubsubTest, WebpubsubPowerShellPreparer + + +class TestGeneratedApiCoverage(WebpubsubTest): + """Recorded tests that make real HTTP requests for all generated APIs. + + APIs that require a live WebSocket connection (send_to_connection, close_connection, + add/remove_connection_to/from_group, grant/revoke_permission, add_user_to_group) are covered in + test_live_coverage.py instead. + """ + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_get_service_status(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert client.get_service_status() + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_generate_client_token(self, webpubsub_endpoint, **kwargs): + client = self.create_client(endpoint=webpubsub_endpoint, hub="apicoverage") + token = client.generate_client_token( + user_id="user1", + role=["webpubsub.sendToGroup"], + group=["group1"], + minutes_to_expire=10, + client_type="Default", + ) + assert token["token"] + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_close_all_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.close_all_connections(excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_add_connections_to_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.add_connections_to_groups( + groups_to_add={"filter": "userId eq 'nobody'", "groups": ["group1", "group2"]} + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_remove_connections_from_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.remove_connections_from_groups( + groups_to_remove={"filter": "userId eq 'nobody'", "groups": ["group1", "group2"]} + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_all_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_all( + message={"hello": "world"}, + content_type="application/json", + excluded=["fake-conn-1", "fake-conn-2"], + filter="userId ne 'nobody'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_all_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_all(message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_all_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_all(message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_group_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_group( + group="group1", + message={"hello": "world"}, + content_type="application/json", + excluded=["fake-conn-1", "fake-conn-2"], + filter="userId ne 'nobody'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_group_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_group(group="group1", message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_group_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_group(group="group1", message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_user_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_user( + user_id="user1", + message={"hello": "world"}, + content_type="application/json", + filter="userId eq 'user1'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_user_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_user(user_id="user1", message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_user_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_user(user_id="user1", message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_send_to_connection_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.send_to_connection( + connection_id="fake-connection-id", + message={"hello": "world"}, + content_type="application/json", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_close_connection_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.close_connection(connection_id="fake-connection-id", reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_add_connection_to_group_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + client.add_connection_to_group(group="group1", connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_grant_permission_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + client.grant_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_revoke_permission_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.revoke_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_add_user_to_group_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + client.add_user_to_group(group="group1", user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_connection_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not client.connection_exists(connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_user_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not client.user_exists(user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_group_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not client.group_exists(group="fake-group") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_check_permission(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not client.check_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_has_permission(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not client.has_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_remove_connection_from_all_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.remove_connection_from_all_groups(connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_remove_user_from_all_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.remove_user_from_all_groups(user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_close_group_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.close_group_connections(group="group1", excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_close_user_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.close_user_connections(user_id="user1", excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_remove_user_from_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.remove_user_from_group(group="group1", user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_list_connections_in_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + result = list(client.list_connections_in_group(group="group1", top=10)) + assert isinstance(result, list) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_list_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + result = list(client.list_connections(group="group1", top=10)) + assert isinstance(result, list) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_remove_connection_from_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + client.remove_connection_from_group(group="group1", connection_id="fake-connection-id") diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage_async.py new file mode 100644 index 000000000000..a10f5efd452f --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_generated_api_coverage_async.py @@ -0,0 +1,263 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import pytest +from azure.core.exceptions import ResourceNotFoundError +from devtools_testutils.aio import recorded_by_proxy_async +from testcase import WebpubsubPowerShellPreparer +from testcase_async import WebpubsubAsyncTest + + +@pytest.mark.live_test_only +class TestGeneratedApiCoverageAsync(WebpubsubAsyncTest): + """Recorded async tests that make real HTTP requests for all generated APIs. + + APIs that require a live WebSocket connection (send_to_connection, close_connection, + add/remove_connection_to/from_group, grant/revoke_permission, add_user_to_group) are covered in + test_live_coverage_async.py instead. + """ + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_get_service_status(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert await client.get_service_status() + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_generate_client_token(self, webpubsub_endpoint, **kwargs): + client = self.create_client(endpoint=webpubsub_endpoint, hub="apicoverage") + token = await client.generate_client_token( + user_id="user1", + role=["webpubsub.sendToGroup"], + group=["group1"], + minutes_to_expire=10, + client_type="Default", + ) + assert token["token"] + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_close_all_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.close_all_connections(excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_add_connections_to_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.add_connections_to_groups( + groups_to_add={"filter": "userId eq 'nobody'", "groups": ["group1", "group2"]} + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_remove_connections_from_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.remove_connections_from_groups( + groups_to_remove={"filter": "userId eq 'nobody'", "groups": ["group1", "group2"]} + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_all_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_all( + message={"hello": "world"}, + content_type="application/json", + excluded=["fake-conn-1", "fake-conn-2"], + filter="userId ne 'nobody'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_all_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_all(message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_all_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_all(message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_group_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_group( + group="group1", + message={"hello": "world"}, + content_type="application/json", + excluded=["fake-conn-1", "fake-conn-2"], + filter="userId ne 'nobody'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_group_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_group(group="group1", message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_group_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_group(group="group1", message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_user_json(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_user( + user_id="user1", + message={"hello": "world"}, + content_type="application/json", + filter="userId eq 'user1'", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_user_text(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_user(user_id="user1", message="hello", content_type="text/plain") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_user_binary(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_user(user_id="user1", message=b"hello", content_type="application/octet-stream") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_send_to_connection_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.send_to_connection( + connection_id="fake-connection-id", + message={"hello": "world"}, + content_type="application/json", + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_close_connection_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.close_connection(connection_id="fake-connection-id", reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_add_connection_to_group_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + await client.add_connection_to_group(group="group1", connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_grant_permission_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + await client.grant_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_revoke_permission_with_fake_connection_id(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.revoke_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_add_user_to_group_not_found(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + with pytest.raises(ResourceNotFoundError): + await client.add_user_to_group(group="group1", user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_connection_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not await client.connection_exists(connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_user_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not await client.user_exists(user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_group_exists(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not await client.group_exists(group="fake-group") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_check_permission(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not await client.check_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_has_permission(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + assert not await client.has_permission( + permission="sendToGroup", connection_id="fake-connection-id", target_name="group1" + ) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_remove_connection_from_all_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.remove_connection_from_all_groups(connection_id="fake-connection-id") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_remove_user_from_all_groups(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.remove_user_from_all_groups(user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_close_group_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.close_group_connections(group="group1", excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_close_user_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.close_user_connections(user_id="user1", excluded=["fake-conn-1", "fake-conn-2"], reason="test") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_remove_user_from_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.remove_user_from_group(group="group1", user_id="fake-user") + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_connections_in_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + result = [member async for member in client.list_connections_in_group(group="group1", top=10)] + assert isinstance(result, list) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_list_connections(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + result = [member async for member in client.list_connections(group="group1", top=10)] + assert isinstance(result, list) + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_remove_connection_from_group(self, webpubsub_connection_string): + client = self.create_client(connection_string=webpubsub_connection_string, hub="apicoverage") + await client.remove_connection_from_group(group="group1", connection_id="fake-connection-id") diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage.py new file mode 100644 index 000000000000..01a486403dd0 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage.py @@ -0,0 +1,197 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import time + +import jwt +import pytest +from devtools_testutils import recorded_by_proxy +from websockets.sync.client import connect as ws_connect + +from testcase import WebpubsubPowerShellPreparer, WebpubsubTest + + +@pytest.mark.live_test_only +class TestLiveApiCoverage(WebpubsubTest): + def _find_connection_id(self, client, group_name, user_id): + for _ in range(10): + members = list(client.list_connections(group=group_name, top=20)) + for member in members: + if member.user_id == user_id and member.connection_id: + return member.connection_id + time.sleep(1) + return None + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy + def test_live_api_coverage_all_apis_and_parameters(self, webpubsub_endpoint, webpubsub_connection_string): + if not getattr(self, "is_live", False): + pytest.skip("Live WebSocket coverage test is skipped in playback mode") + + client = self.create_client(connection_string=webpubsub_connection_string, hub="hub") + aad_client = self.create_client(endpoint=webpubsub_endpoint, hub="hub") + + user_id = "live-user-1" + group_1 = "group-live-1" + group_2 = "group-live-2" + group_3 = "group-live-3" + group_4 = "group-live-4" + + access_token = client.get_client_access_token( + user_id=user_id, + roles=["webpubsub.sendToGroup", "webpubsub.joinLeaveGroup"], + groups=[group_1], + minutes_to_expire=15, + client_protocol="Default", + jwt_headers={"kid": "live-coverage-kid"}, + ) + assert access_token["token"] + decoded = jwt.decode(access_token["token"], options={"verify_signature": False}) + assert decoded["sub"] == user_id + assert "webpubsub.sendToGroup" in decoded["role"] + assert "webpubsub.joinLeaveGroup" in decoded["role"] + assert group_1 in decoded["webpubsub.group"] + + socketio_token = client.get_client_access_token(user_id=user_id, groups=[group_1], client_protocol="SocketIO") + assert socketio_token["token"] + + generated_token = aad_client.generate_client_token( + user_id=user_id, + role=["webpubsub.sendToGroup"], + group=[group_1], + minutes_to_expire=10, + client_type="MQTT", + ) + assert generated_token["token"] + + ws = None + try: + ws = ws_connect(access_token["url"]) + + assert client.get_service_status() + + connection_id = self._find_connection_id(client, group_1, user_id) + assert connection_id is not None + + assert client.connection_exists(connection_id=connection_id) + assert client.user_exists(user_id=user_id) + assert client.group_exists(group=group_1) + + client.send_to_all(message={"kind": "json"}, content_type="application/json", excluded=[connection_id, "fake-conn-id"]) + client.send_to_all(message="plain", content_type="text/plain", filter=f"userId eq '{user_id}'") + client.send_to_all(message=b"binary", content_type="application/octet-stream") + + client.send_to_group( + group=group_1, + message={"kind": "json"}, + content_type="application/json", + excluded=[connection_id, "fake-conn-id"], + ) + client.send_to_group( + group=group_1, + message="plain", + content_type="text/plain", + filter=f"userId eq '{user_id}'", + ) + client.send_to_group(group=group_1, message=b"binary", content_type="application/octet-stream") + + client.send_to_connection( + connection_id=connection_id, + message={"kind": "json"}, + content_type="application/json", + ) + client.send_to_connection(connection_id=connection_id, message="plain", content_type="text/plain") + client.send_to_connection( + connection_id=connection_id, + message=b"binary", + content_type="application/octet-stream", + ) + + client.send_to_user( + user_id=user_id, + message={"kind": "json"}, + content_type="application/json", + filter=f"userId eq '{user_id}'", + ) + client.send_to_user(user_id=user_id, message="plain", content_type="text/plain") + client.send_to_user(user_id=user_id, message=b"binary", content_type="application/octet-stream") + + client.add_connection_to_group(group=group_2, connection_id=connection_id) + members_group_2 = list(client.list_connections_in_group(group=group_2, top=20)) + assert any(member.connection_id == connection_id for member in members_group_2) + + client.add_connections_to_groups(groups_to_add={"filter": f"userId eq '{user_id}'", "groups": [group_3]}) + members_group_3 = list(client.list_connections_in_group(group=group_3, top=20)) + assert any(member.connection_id == connection_id for member in members_group_3) + + client.grant_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + assert client.check_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + assert client.has_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + client.revoke_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + + client.add_user_to_group(group=group_4, user_id=user_id) + client.remove_user_from_group(group=group_4, user_id=user_id) + + client.remove_connections_from_groups( + groups_to_remove={"filter": f"userId eq '{user_id}'", "groups": [group_3]} + ) + client.remove_connection_from_group(group=group_2, connection_id=connection_id) + client.remove_connection_from_all_groups(connection_id=connection_id) + client.remove_user_from_all_groups(user_id=user_id) + + # --- Close operations: reconnect between each so every close API has a real connection --- + + # close_group_connections (connection auto-joins group_1 via token) + ws.close() + ws = ws_connect(access_token["url"]) + conn = self._find_connection_id(client, group_1, user_id) + assert conn is not None + client.close_group_connections(group=group_1, reason="live-coverage") + assert not client.connection_exists(connection_id=conn) + + # close_user_connections + ws = ws_connect(access_token["url"]) + conn = self._find_connection_id(client, group_1, user_id) + assert conn is not None + client.close_user_connections(user_id=user_id, reason="live-coverage") + assert not client.connection_exists(connection_id=conn) + + # close_connection + ws = ws_connect(access_token["url"]) + conn = self._find_connection_id(client, group_1, user_id) + assert conn is not None + client.close_connection(connection_id=conn, reason="live-coverage") + assert not client.connection_exists(connection_id=conn) + + # close_all_connections + ws = ws_connect(access_token["url"]) + conn = self._find_connection_id(client, group_1, user_id) + assert conn is not None + client.close_all_connections(reason="live-coverage") + assert not client.connection_exists(connection_id=conn) + ws = None + + assert not client.user_exists(user_id="live-user-not-exist") + assert not client.group_exists(group="live-group-not-exist") + finally: + if ws: + ws.close() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage_async.py new file mode 100644 index 000000000000..35f238d0eef2 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_live_api_coverage_async.py @@ -0,0 +1,226 @@ +# coding: utf-8 +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# ------------------------------------------------------------------------- +import asyncio + +import jwt +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from websockets import connect as ws_connect + +from testcase import WebpubsubPowerShellPreparer +from testcase_async import WebpubsubAsyncTest + + +@pytest.mark.live_test_only +@pytest.mark.asyncio +class TestLiveApiCoverageAsync(WebpubsubAsyncTest): + async def _find_connection_id(self, client, group_name, user_id): + for _ in range(10): + members = [member async for member in client.list_connections(group=group_name, top=20)] + for member in members: + if member.user_id == user_id and member.connection_id: + return member.connection_id + await asyncio.sleep(1) + return None + + @WebpubsubPowerShellPreparer() + @recorded_by_proxy_async + async def test_live_api_coverage_all_apis_and_parameters_async(self, webpubsub_endpoint, webpubsub_connection_string): + if not getattr(self, "is_live", False): + pytest.skip("Live WebSocket coverage test is skipped in playback mode") + + client = self.create_client(connection_string=webpubsub_connection_string, hub="hub") + aad_client = self.create_client(endpoint=webpubsub_endpoint, hub="hub") + + user_id = "live-user-1" + group_1 = "group-live-1" + group_2 = "group-live-2" + group_3 = "group-live-3" + group_4 = "group-live-4" + + async with client: + access_token = await client.get_client_access_token( + user_id=user_id, + roles=["webpubsub.sendToGroup", "webpubsub.joinLeaveGroup"], + groups=[group_1], + minutes_to_expire=15, + client_protocol="Default", + jwt_headers={"kid": "live-coverage-kid"}, + ) + assert access_token["token"] + decoded = jwt.decode(access_token["token"], options={"verify_signature": False}) + assert decoded["sub"] == user_id + assert "webpubsub.sendToGroup" in decoded["role"] + assert "webpubsub.joinLeaveGroup" in decoded["role"] + assert group_1 in decoded["webpubsub.group"] + + socketio_token = await client.get_client_access_token( + user_id=user_id, + groups=[group_1], + client_protocol="SocketIO", + ) + assert socketio_token["token"] + + generated_token = await aad_client.generate_client_token( + user_id=user_id, + role=["webpubsub.sendToGroup"], + group=[group_1], + minutes_to_expire=10, + client_type="MQTT", + ) + assert generated_token["token"] + + ws = None + try: + ws = await ws_connect(access_token["url"]) + + assert await client.get_service_status() + + connection_id = await self._find_connection_id(client, group_1, user_id) + assert connection_id is not None + + assert await client.connection_exists(connection_id=connection_id) + assert await client.user_exists(user_id=user_id) + assert await client.group_exists(group=group_1) + + await client.send_to_all( + message={"kind": "json"}, + content_type="application/json", + excluded=[connection_id, "fake-conn-id"], + ) + await client.send_to_all( + message="plain", + content_type="text/plain", + filter=f"userId eq '{user_id}'", + ) + await client.send_to_all(message=b"binary", content_type="application/octet-stream") + + await client.send_to_group( + group=group_1, + message={"kind": "json"}, + content_type="application/json", + excluded=[connection_id, "fake-conn-id"], + ) + await client.send_to_group( + group=group_1, + message="plain", + content_type="text/plain", + filter=f"userId eq '{user_id}'", + ) + await client.send_to_group( + group=group_1, + message=b"binary", + content_type="application/octet-stream", + ) + + await client.send_to_connection( + connection_id=connection_id, + message={"kind": "json"}, + content_type="application/json", + ) + await client.send_to_connection( + connection_id=connection_id, + message="plain", + content_type="text/plain", + ) + await client.send_to_connection( + connection_id=connection_id, + message=b"binary", + content_type="application/octet-stream", + ) + + await client.send_to_user( + user_id=user_id, + message={"kind": "json"}, + content_type="application/json", + filter=f"userId eq '{user_id}'", + ) + await client.send_to_user(user_id=user_id, message="plain", content_type="text/plain") + await client.send_to_user( + user_id=user_id, + message=b"binary", + content_type="application/octet-stream", + ) + + await client.add_connection_to_group(group=group_2, connection_id=connection_id) + members_group_2 = [member async for member in client.list_connections_in_group(group=group_2, top=20)] + assert any(member.connection_id == connection_id for member in members_group_2) + + await client.add_connections_to_groups( + groups_to_add={"filter": f"userId eq '{user_id}'", "groups": [group_3]} + ) + members_group_3 = [member async for member in client.list_connections_in_group(group=group_3, top=20)] + assert any(member.connection_id == connection_id for member in members_group_3) + + await client.grant_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + assert await client.check_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + assert await client.has_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + await client.revoke_permission( + permission="sendToGroup", + connection_id=connection_id, + target_name=group_1, + ) + + await client.add_user_to_group(group=group_4, user_id=user_id) + await client.remove_user_from_group(group=group_4, user_id=user_id) + + await client.remove_connections_from_groups( + groups_to_remove={"filter": f"userId eq '{user_id}'", "groups": [group_3]} + ) + await client.remove_connection_from_group(group=group_2, connection_id=connection_id) + await client.remove_connection_from_all_groups(connection_id=connection_id) + await client.remove_user_from_all_groups(user_id=user_id) + + # --- Close operations: reconnect between each so every close API has a real connection --- + + # close_group_connections (connection auto-joins group_1 via token) + await ws.close() + ws = await ws_connect(access_token["url"]) + conn = await self._find_connection_id(client, group_1, user_id) + assert conn is not None + await client.close_group_connections(group=group_1, reason="live-coverage") + assert not await client.connection_exists(connection_id=conn) + + # close_user_connections + ws = await ws_connect(access_token["url"]) + conn = await self._find_connection_id(client, group_1, user_id) + assert conn is not None + await client.close_user_connections(user_id=user_id, reason="live-coverage") + assert not await client.connection_exists(connection_id=conn) + + # close_connection + ws = await ws_connect(access_token["url"]) + conn = await self._find_connection_id(client, group_1, user_id) + assert conn is not None + await client.close_connection(connection_id=conn, reason="live-coverage") + assert not await client.connection_exists(connection_id=conn) + + # close_all_connections + ws = await ws_connect(access_token["url"]) + conn = await self._find_connection_id(client, group_1, user_id) + assert conn is not None + await client.close_all_connections(reason="live-coverage") + assert not await client.connection_exists(connection_id=conn) + ws = None + + assert not await client.user_exists(user_id="live-user-not-exist") + assert not await client.group_exists(group="live-group-not-exist") + finally: + if ws: + await ws.close() \ No newline at end of file diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy.py index 93a95fe1b587..e373804ba7a3 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy.py @@ -13,7 +13,6 @@ from devtools_testutils import recorded_by_proxy -@pytest.mark.live_test_only class TestWebpubsubReverseProxy(WebpubsubTest): @recorded_by_proxy diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy_async.py index 6832c37b5740..7ef02f256ecc 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy_async.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_reverse_proxy_async.py @@ -14,7 +14,6 @@ from devtools_testutils.aio import recorded_by_proxy_async -@pytest.mark.live_test_only class TestWebpubsubReverseProxyAsync(WebpubsubAsyncTest): @pytest.mark.asyncio diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke.py index 8cfd90ca342f..e876bb201947 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke.py @@ -12,7 +12,6 @@ from devtools_testutils import recorded_by_proxy -@pytest.mark.live_test_only class TestWebpubsubSmoke(WebpubsubTest): @WebpubsubPowerShellPreparer() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke_async.py b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke_async.py index 9cc7df45481e..84e70c05a288 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke_async.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tests/test_smoke_async.py @@ -10,7 +10,6 @@ from devtools_testutils.aio import recorded_by_proxy_async -@pytest.mark.live_test_only class TestWebpubsubSmokeAsync(WebpubsubAsyncTest): @WebpubsubPowerShellPreparer() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/tsp-location.yaml b/sdk/webpubsub/azure-messaging-webpubsubservice/tsp-location.yaml index 63ca9b845014..fbe24ebfaf01 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/tsp-location.yaml +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/webpubsub/data-plane/WebPubSub -commit: 31e9334fb19097c919bd17b5cdf4c4c3f45df3bf -repo: Azure/azure-rest-api-specs +commit: 12a75a4910e5d84677a598473cf4e4d9d0a6d5fa +repo: MoChilia/azure-rest-api-specs additionalDirectories: []