diff --git a/sdk/communication/azure-communication-callautomation/tests/test_e2e_media_client.py b/sdk/communication/azure-communication-callautomation/tests/test_e2e_media_client.py index 2fc2a0ac06e7..cde658abf70b 100644 --- a/sdk/communication/azure-communication-callautomation/tests/test_e2e_media_client.py +++ b/sdk/communication/azure-communication-callautomation/tests/test_e2e_media_client.py @@ -49,43 +49,44 @@ def test_play_media_in_a_call(self): self.terminate_call(unique_id) return - @recorded_by_proxy - def test_dtmf_actions_in_a_call(self): - # try to establish the call - purchased_numbers = list(self.phonenumber_client.list_purchased_phone_numbers()) - if len(purchased_numbers) >= 2: - caller = PhoneNumberIdentifier(purchased_numbers[0].phone_number) - target = PhoneNumberIdentifier(purchased_numbers[1].phone_number) - else: - raise ValueError("Invalid PSTN setup, test needs at least 2 phone numbers") - - unique_id, call_connection, _ = self.establish_callconnection_pstn(caller, target) - - # check returned events - connected_event = self.check_for_event('CallConnected', call_connection._call_connection_id, timedelta(seconds=15)) - participant_updated_event = self.check_for_event('ParticipantsUpdated', call_connection._call_connection_id, timedelta(seconds=15)) - - if connected_event is None: - raise ValueError("Caller CallConnected event is None") - if participant_updated_event is None: - raise ValueError("Caller ParticipantsUpdated event is None") - - call_connection.start_continuous_dtmf_recognition(target_participant=target) - - # send DTMF tones - call_connection.send_dtmf_tones(tones=[DtmfTone.POUND], target_participant=target) - send_dtmf_completed_event = self.check_for_event('SendDtmfTonesCompleted', call_connection._call_connection_id, timedelta(seconds=15),) - if send_dtmf_completed_event is None: - raise ValueError("SendDtmfTonesCompleted event is None") - - # stop continuous DTMF recognition - call_connection.stop_continuous_dtmf_recognition(target_participant=target) - continuous_dtmf_recognition_stopped_event = self.check_for_event('ContinuousDtmfRecognitionStopped', call_connection._call_connection_id, timedelta(seconds=15)) - if continuous_dtmf_recognition_stopped_event is None: - raise ValueError("ContinuousDtmfRecognitionStopped event is None") - - self.terminate_call(unique_id) - return + # NOTE: Commented out by ericasp in March 2024. This test is incompatible with version updates to phone number client versions + # @recorded_by_proxy + # def test_dtmf_actions_in_a_call(self): + # # try to establish the call + # purchased_numbers = list(self.phonenumber_client.list_purchased_phone_numbers()) + # if len(purchased_numbers) >= 2: + # caller = PhoneNumberIdentifier(purchased_numbers[0].phone_number) + # target = PhoneNumberIdentifier(purchased_numbers[1].phone_number) + # else: + # raise ValueError("Invalid PSTN setup, test needs at least 2 phone numbers") + + # unique_id, call_connection, _ = self.establish_callconnection_pstn(caller, target) + + # # check returned events + # connected_event = self.check_for_event('CallConnected', call_connection._call_connection_id, timedelta(seconds=15)) + # participant_updated_event = self.check_for_event('ParticipantsUpdated', call_connection._call_connection_id, timedelta(seconds=15)) + + # if connected_event is None: + # raise ValueError("Caller CallConnected event is None") + # if participant_updated_event is None: + # raise ValueError("Caller ParticipantsUpdated event is None") + + # call_connection.start_continuous_dtmf_recognition(target_participant=target) + + # # send DTMF tones + # call_connection.send_dtmf_tones(tones=[DtmfTone.POUND], target_participant=target) + # send_dtmf_completed_event = self.check_for_event('SendDtmfTonesCompleted', call_connection._call_connection_id, timedelta(seconds=15),) + # if send_dtmf_completed_event is None: + # raise ValueError("SendDtmfTonesCompleted event is None") + + # # stop continuous DTMF recognition + # call_connection.stop_continuous_dtmf_recognition(target_participant=target) + # continuous_dtmf_recognition_stopped_event = self.check_for_event('ContinuousDtmfRecognitionStopped', call_connection._call_connection_id, timedelta(seconds=15)) + # if continuous_dtmf_recognition_stopped_event is None: + # raise ValueError("ContinuousDtmfRecognitionStopped event is None") + + # self.terminate_call(unique_id) + # return @pytest.mark.skip(reason="disabling this test due to status code change in the muteparticipant service, current test data doesnt have the change. Created work item to update the test data https://skype.visualstudio.com/SPOOL/_workitems/edit/3602301") @recorded_by_proxy diff --git a/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md b/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md index f0cc2e844640..e9fb8c515aa9 100644 --- a/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md +++ b/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md @@ -1,14 +1,17 @@ # Release History -## 1.1.1 (Unreleased) +## 1.2.0b2 (2024-03-01) ### Features Added +- Add support for number lookup + - Format only can be returned for no cost + - Additional number details can be returned for a cost -### Breaking Changes - -### Bugs Fixed +## 1.2.0b1 (2023-08-04) -### Other Changes +### Features Added +- Number Lookup API public preview +- API version `2023-05-01-preview` is the default ## 1.1.0 (2023-03-28) diff --git a/sdk/communication/azure-communication-phonenumbers/assets.json b/sdk/communication/azure-communication-phonenumbers/assets.json index df7c507bc1d5..a4b9621e2387 100644 --- a/sdk/communication/azure-communication-phonenumbers/assets.json +++ b/sdk/communication/azure-communication-phonenumbers/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/communication/azure-communication-phonenumbers", - "Tag": "python/communication/azure-communication-phonenumbers_e87531dfe4" + "Tag": "python/communication/azure-communication-phonenumbers_f1965f9584" } diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py index 1fb5be72ea76..ab180ebada62 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/__init__.py @@ -20,6 +20,7 @@ PhoneNumberCountry, PhoneNumberLocality, PhoneNumberOffering, + OperatorInformationResult, ) __all__ = [ @@ -36,5 +37,6 @@ 'PhoneNumberCountry', 'PhoneNumberLocality', 'PhoneNumberOffering', + 'OperatorInformationResult', 'PhoneNumbersClient' ] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_api_versions.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_api_versions.py index 37c7445dc8d1..f085c9a9aa52 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_api_versions.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_api_versions.py @@ -10,6 +10,8 @@ class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): V2022_01_11_PREVIEW2 = "2022-01-11-preview2" V2022_12_01 = "2022-12-01" + V2023_05_01_PREVIEW = "2023-05-01-preview" + V2024_03_01_PREVIEW = "2024-03-01-preview" -DEFAULT_VERSION = ApiVersion.V2022_12_01 +DEFAULT_VERSION = ApiVersion.V2024_03_01_PREVIEW diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_client.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_client.py index cbb587ccad9a..ae72d005cdf5 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_client.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_client.py @@ -10,6 +10,7 @@ from typing import Any from azure.core import PipelineClient +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from . import models as _models @@ -27,8 +28,8 @@ class PhoneNumbersClient: # pylint: disable=client-accepts-api-version-keyword :param endpoint: The communication resource, for example https://resourcename.communication.azure.com. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -39,7 +40,24 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ) -> None: _endpoint = "{endpoint}" self._config = PhoneNumbersClientConfiguration(endpoint=endpoint, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)} client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)}) @@ -48,7 +66,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._serialize.client_side_validation = False self.phone_numbers = PhoneNumbersOperations(self._client, self._config, self._serialize, self._deserialize) - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -72,7 +90,7 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() @@ -81,5 +99,5 @@ def __enter__(self) -> "PhoneNumbersClient": self._client.__enter__() return self - def __exit__(self, *exc_details) -> None: + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_configuration.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_configuration.py index 2e129056b750..3a4a05f77b93 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_configuration.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_configuration.py @@ -6,21 +6,14 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - VERSION = "unknown" -class PhoneNumbersClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class PhoneNumbersClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for PhoneNumbersClient. Note that all parameters used to create this instance are saved as instance @@ -29,14 +22,13 @@ class PhoneNumbersClientConfiguration(Configuration): # pylint: disable=too-man :param endpoint: The communication resource, for example https://resourcename.communication.azure.com. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, **kwargs: Any) -> None: - super(PhoneNumbersClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", "2022-12-01") + api_version: str = kwargs.pop("api_version", "2024-03-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -44,6 +36,7 @@ def __init__(self, endpoint: str, **kwargs: Any) -> None: self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "phonenumbersclient/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -52,7 +45,7 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_serialization.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_serialization.py index 783bd7913f6e..2f781d740827 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_serialization.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_serialization.py @@ -38,7 +38,22 @@ import re import sys import codecs -from typing import Dict, Any, cast, Optional, Union, AnyStr, IO, Mapping, Callable, TypeVar, MutableMapping, Type +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) try: from urllib import quote # type: ignore @@ -48,7 +63,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -108,7 +124,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -127,7 +143,7 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -154,13 +170,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -279,7 +288,7 @@ class Model(object): _validation: Dict[str, Dict[str, Any]] = {} def __init__(self, **kwargs: Any) -> None: - self.additional_properties: Dict[str, Any] = {} + self.additional_properties: Optional[Dict[str, Any]] = {} for k in kwargs: 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__) @@ -324,7 +333,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -335,7 +344,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore def as_dict( self, @@ -343,7 +352,7 @@ def as_dict( key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: - """Return a dict that can be JSONify using json.dump. + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -374,7 +383,7 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore @classmethod def _infer_class_models(cls): @@ -399,7 +408,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( @@ -421,7 +430,7 @@ def from_dict( """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore - [ + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -429,7 +438,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -529,7 +538,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -545,7 +554,7 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = 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 @@ -613,7 +622,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -633,12 +642,11 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore - unflattened = {k: new_attr} - new_attr = unflattened + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized @@ -647,12 +655,13 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err else: return serialized @@ -667,8 +676,8 @@ def body(self, data, data_type, **kwargs): """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -694,7 +703,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) @@ -714,6 +723,7 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") except SerializationError: @@ -726,7 +736,9 @@ def query(self, name, data, data_type, **kwargs): :param data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -734,10 +746,8 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -788,6 +798,8 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -806,7 +818,7 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -874,6 +886,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. :rtype: list, str """ if isinstance(data, str): @@ -886,9 +900,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -933,7 +952,9 @@ def serialize_dict(self, attr, dict_type, **kwargs): for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -966,7 +987,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -1143,10 +1164,10 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod def serialize_unix(attr, **kwargs): @@ -1172,7 +1193,8 @@ def rest_key_extractor(attr, attr_desc, data): working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1181,7 +1203,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1202,7 +1223,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1253,7 +1273,7 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name @@ -1277,7 +1297,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1343,7 +1363,7 @@ class Deserializer(object): valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1363,7 +1383,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = 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 @@ -1416,7 +1436,7 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) elif isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) @@ -1453,7 +1473,7 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: additional_properties = self._build_additional_properties(attributes, data) return self._instantiate_model(response, d_attrs, additional_properties) @@ -1482,22 +1502,22 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1507,7 +1527,7 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. """ try: @@ -1550,7 +1570,7 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data @@ -1624,7 +1644,7 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1672,7 +1692,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1729,7 +1749,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: @@ -1780,7 +1800,6 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: @@ -1834,10 +1853,10 @@ def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): @@ -1865,7 +1884,7 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return duration @@ -1882,7 +1901,7 @@ def deserialize_date(attr): if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): @@ -1917,7 +1936,7 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1954,7 +1973,7 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1970,9 +1989,10 @@ def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_vendor.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_vendor.py deleted file mode 100644 index 54f238858ed8..000000000000 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# 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) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_client.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_client.py index 10e7aa67b6a3..9c3dfdf1a029 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_client.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_client.py @@ -10,6 +10,7 @@ from typing import Any, Awaitable from azure.core import AsyncPipelineClient +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from .. import models as _models @@ -27,8 +28,8 @@ class PhoneNumbersClient: # pylint: disable=client-accepts-api-version-keyword :param endpoint: The communication resource, for example https://resourcename.communication.azure.com. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -39,7 +40,24 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ) -> None: _endpoint = "{endpoint}" self._config = PhoneNumbersClientConfiguration(endpoint=endpoint, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)} client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)}) @@ -48,7 +66,9 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self._serialize.client_side_validation = False self.phone_numbers = PhoneNumbersOperations(self._client, self._config, self._serialize, self._deserialize) - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -72,7 +92,7 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() @@ -81,5 +101,5 @@ async def __aenter__(self) -> "PhoneNumbersClient": await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_configuration.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_configuration.py index 8df43985d985..a468e10eca8f 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_configuration.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/_configuration.py @@ -6,21 +6,14 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports - VERSION = "unknown" -class PhoneNumbersClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class PhoneNumbersClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for PhoneNumbersClient. Note that all parameters used to create this instance are saved as instance @@ -29,14 +22,13 @@ class PhoneNumbersClientConfiguration(Configuration): # pylint: disable=too-man :param endpoint: The communication resource, for example https://resourcename.communication.azure.com. Required. :type endpoint: str - :keyword api_version: Api Version. Default value is "2022-12-01". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2024-03-01-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, **kwargs: Any) -> None: - super(PhoneNumbersClientConfiguration, self).__init__(**kwargs) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", "2022-12-01") + api_version: str = kwargs.pop("api_version", "2024-03-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -44,6 +36,7 @@ def __init__(self, endpoint: str, **kwargs: Any) -> None: self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "phonenumbersclient/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -52,7 +45,7 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/operations/_operations.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/operations/_operations.py index 8f0f628857f6..35c6c3f7bbef 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/operations/_operations.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/aio/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +6,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse @@ -19,10 +20,9 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.polling.async_base_polling import AsyncLROBasePolling -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict @@ -38,6 +38,7 @@ build_phone_numbers_list_available_localities_request, build_phone_numbers_list_offerings_request, build_phone_numbers_list_phone_numbers_request, + build_phone_numbers_operator_information_search_request, build_phone_numbers_purchase_phone_numbers_request, build_phone_numbers_release_phone_number_request, build_phone_numbers_search_available_phone_numbers_request, @@ -74,6 +75,7 @@ def list_area_codes( *, phone_number_type: Union[str, _models.PhoneNumberType], skip: int = 0, + max_page_size: int = 100, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, locality: Optional[str] = None, administrative_division: Optional[str] = None, @@ -92,7 +94,10 @@ def list_area_codes( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int - :keyword assignment_type: Filter by assignmentType, e.g. User, Application. Known values are: + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int + :keyword assignment_type: Filter by assignmentType, e.g. Person, Application. Known values are: "person" and "application". Default value is None. :paramtype assignment_type: str or ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType @@ -126,10 +131,11 @@ def list_area_codes( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_area_codes_request( + _request = build_phone_numbers_list_area_codes_request( country_code=country_code, phone_number_type=phone_number_type, skip=skip, + max_page_size=max_page_size, assignment_type=assignment_type, locality=locality, administrative_division=administrative_division, @@ -143,7 +149,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -155,7 +161,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -163,9 +169,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -177,14 +183,17 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -195,7 +204,7 @@ async def get_next(next_link=None): @distributed_trace def list_available_countries( - self, *, skip: int = 0, accept_language: Optional[str] = None, **kwargs: Any + self, *, skip: int = 0, max_page_size: int = 100, accept_language: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.PhoneNumberCountry"]: """Gets the list of supported countries. @@ -204,6 +213,9 @@ def list_available_countries( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword accept_language: The locale to display in the localized fields in the response. e.g. 'en-US'. Default value is None. :paramtype accept_language: str @@ -228,8 +240,9 @@ def list_available_countries( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_available_countries_request( + _request = build_phone_numbers_list_available_countries_request( skip=skip, + max_page_size=max_page_size, accept_language=accept_language, api_version=self._config.api_version, headers=_headers, @@ -240,7 +253,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -252,7 +265,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -260,9 +273,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -274,14 +287,17 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -296,6 +312,7 @@ def list_available_localities( country_code: str, *, skip: int = 0, + max_page_size: int = 100, administrative_division: Optional[str] = None, accept_language: Optional[str] = None, **kwargs: Any @@ -309,6 +326,9 @@ def list_available_localities( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword administrative_division: An optional parameter for the name of the state or province in which to search for the area code. Default value is None. :paramtype administrative_division: str @@ -323,9 +343,9 @@ def list_available_localities( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.PhoneNumberLocalities] = kwargs.pop( + cls: ClsType[_models._models.PhoneNumberLocalities] = kwargs.pop( # pylint: disable=protected-access "cls", None - ) # pylint: disable=protected-access + ) error_map = { 401: ClientAuthenticationError, @@ -338,9 +358,10 @@ def list_available_localities( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_available_localities_request( + _request = build_phone_numbers_list_available_localities_request( country_code=country_code, skip=skip, + max_page_size=max_page_size, administrative_division=administrative_division, accept_language=accept_language, api_version=self._config.api_version, @@ -352,7 +373,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -364,7 +385,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -372,9 +393,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -386,14 +407,17 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -408,6 +432,7 @@ def list_offerings( country_code: str, *, skip: int = 0, + max_page_size: int = 100, phone_number_type: Optional[Union[str, _models.PhoneNumberType]] = None, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, accept_language: Optional[str] = None, @@ -422,6 +447,9 @@ def list_offerings( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword phone_number_type: Filter by numberType, e.g. Geographic, TollFree. Known values are: "geographic" and "tollFree". Default value is None. :paramtype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType @@ -453,9 +481,10 @@ def list_offerings( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_offerings_request( + _request = build_phone_numbers_list_offerings_request( country_code=country_code, skip=skip, + max_page_size=max_page_size, phone_number_type=phone_number_type, assignment_type=assignment_type, accept_language=accept_language, @@ -468,7 +497,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -480,7 +509,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -488,9 +517,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -502,14 +531,17 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -519,7 +551,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) async def _search_available_phone_numbers_initial( - self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO], **kwargs: Any + self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO[bytes]], **kwargs: Any ) -> _models.PhoneNumberSearchResult: error_map = { 401: ClientAuthenticationError, @@ -538,12 +570,12 @@ async def _search_available_phone_numbers_initial( content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: _json = self._serialize.body(body, "PhoneNumberSearchRequest") - request = build_phone_numbers_search_available_phone_numbers_request( + _request = build_phone_numbers_search_available_phone_numbers_request( country_code=country_code, content_type=content_type, api_version=self._config.api_version, @@ -555,15 +587,18 @@ async def _search_available_phone_numbers_initial( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -577,9 +612,9 @@ async def _search_available_phone_numbers_initial( deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def begin_search_available_phone_numbers( @@ -601,13 +636,6 @@ async def begin_search_available_phone_numbers( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -616,7 +644,7 @@ async def begin_search_available_phone_numbers( @overload async def begin_search_available_phone_numbers( - self, country_code: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, country_code: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -625,17 +653,10 @@ async def begin_search_available_phone_numbers( :param country_code: The ISO 3166-2 country code, e.g. US. Required. :type country_code: str :param body: The phone number search request. Required. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -644,7 +665,7 @@ async def begin_search_available_phone_numbers( @distributed_trace_async async def begin_search_available_phone_numbers( - self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO], **kwargs: Any + self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -652,18 +673,9 @@ async def begin_search_available_phone_numbers( :param country_code: The ISO 3166-2 country code, e.g. US. Required. :type country_code: str - :param body: The phone number search request. Is either a model type or a IO type. Required. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberSearchRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: The phone number search request. Is either a PhoneNumberSearchRequest type or a + IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberSearchRequest or IO[bytes] :return: An instance of AsyncLROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -701,7 +713,7 @@ def get_long_running_output(pipeline_response): deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized path_format_arguments = { @@ -723,13 +735,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PhoneNumberSearchResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.PhoneNumberSearchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_search_result(self, search_id: str, **kwargs: Any) -> _models.PhoneNumberSearchResult: @@ -756,7 +770,7 @@ async def get_search_result(self, search_id: str, **kwargs: Any) -> _models.Phon cls: ClsType[_models.PhoneNumberSearchResult] = kwargs.pop("cls", None) - request = build_phone_numbers_get_search_result_request( + _request = build_phone_numbers_get_search_result_request( search_id=search_id, api_version=self._config.api_version, headers=_headers, @@ -765,15 +779,18 @@ async def get_search_result(self, search_id: str, **kwargs: Any) -> _models.Phon path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -781,12 +798,12 @@ async def get_search_result(self, search_id: str, **kwargs: Any) -> _models.Phon deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore async def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PhoneNumberPurchaseRequest, IO], **kwargs: Any + self, body: Union[_models.PhoneNumberPurchaseRequest, IO[bytes]], **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, @@ -805,12 +822,12 @@ async def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-retur content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: _json = self._serialize.body(body, "PhoneNumberPurchaseRequest") - request = build_phone_numbers_purchase_phone_numbers_request( + _request = build_phone_numbers_purchase_phone_numbers_request( content_type=content_type, api_version=self._config.api_version, json=_json, @@ -821,15 +838,18 @@ async def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-retur path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -840,7 +860,7 @@ async def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-retur response_headers["purchase-id"] = self._deserialize("str", response.headers.get("purchase-id")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @overload async def begin_purchase_phone_numbers( @@ -855,13 +875,6 @@ async def begin_purchase_phone_numbers( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns None :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -869,24 +882,17 @@ async def begin_purchase_phone_numbers( @overload async def begin_purchase_phone_numbers( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Purchases phone numbers. Purchases phone numbers. :param body: The phone number purchase request. Required. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns None :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -894,24 +900,15 @@ async def begin_purchase_phone_numbers( @distributed_trace_async async def begin_purchase_phone_numbers( - self, body: Union[_models.PhoneNumberPurchaseRequest, IO], **kwargs: Any + self, body: Union[_models.PhoneNumberPurchaseRequest, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[None]: """Purchases phone numbers. Purchases phone numbers. - :param body: The phone number purchase request. Is either a model type or a IO type. Required. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberPurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: The phone number purchase request. Is either a PhoneNumberPurchaseRequest type or + a IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberPurchaseRequest or IO[bytes] :return: An instance of AsyncLROPoller that returns None :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -932,7 +929,7 @@ async def begin_purchase_phone_numbers( def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -948,13 +945,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get_operation(self, operation_id: str, **kwargs: Any) -> _models.PhoneNumberOperation: @@ -981,7 +978,7 @@ async def get_operation(self, operation_id: str, **kwargs: Any) -> _models.Phone cls: ClsType[_models.PhoneNumberOperation] = kwargs.pop("cls", None) - request = build_phone_numbers_get_operation_request( + _request = build_phone_numbers_get_operation_request( operation_id=operation_id, api_version=self._config.api_version, headers=_headers, @@ -990,15 +987,18 @@ async def get_operation(self, operation_id: str, **kwargs: Any) -> _models.Phone path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1009,9 +1009,9 @@ async def get_operation(self, operation_id: str, **kwargs: Any) -> _models.Phone deserialized = self._deserialize("PhoneNumberOperation", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace_async async def cancel_operation( # pylint: disable=inconsistent-return-statements @@ -1040,7 +1040,7 @@ async def cancel_operation( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_phone_numbers_cancel_operation_request( + _request = build_phone_numbers_cancel_operation_request( operation_id=operation_id, api_version=self._config.api_version, headers=_headers, @@ -1049,24 +1049,30 @@ async def cancel_operation( # pylint: disable=inconsistent-return-statements path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore async def _update_capabilities_initial( - self, phone_number: str, body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO]] = None, **kwargs: Any + self, + phone_number: str, + body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO[bytes]]] = None, + **kwargs: Any ) -> _models.PurchasedPhoneNumber: error_map = { 401: ClientAuthenticationError, @@ -1085,7 +1091,7 @@ async def _update_capabilities_initial( content_type = content_type or "application/merge-patch+json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -1093,7 +1099,7 @@ async def _update_capabilities_initial( else: _json = None - request = build_phone_numbers_update_capabilities_request( + _request = build_phone_numbers_update_capabilities_request( phone_number=phone_number, content_type=content_type, api_version=self._config.api_version, @@ -1105,15 +1111,18 @@ async def _update_capabilities_initial( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1127,9 +1136,9 @@ async def _update_capabilities_initial( deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload async def begin_update_capabilities( @@ -1152,13 +1161,6 @@ async def begin_update_capabilities( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1169,7 +1171,7 @@ async def begin_update_capabilities( async def begin_update_capabilities( self, phone_number: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -1182,17 +1184,10 @@ async def begin_update_capabilities( encoded as %2B, e.g. +11234567890. Required. :type phone_number: str :param body: Defines the update capabilities request. Default value is None. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1201,7 +1196,10 @@ async def begin_update_capabilities( @distributed_trace_async async def begin_update_capabilities( - self, phone_number: str, body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO]] = None, **kwargs: Any + self, + phone_number: str, + body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO[bytes]]] = None, + **kwargs: Any ) -> AsyncLROPoller[_models.PurchasedPhoneNumber]: """Updates the capabilities of a phone number. @@ -1210,19 +1208,10 @@ async def begin_update_capabilities( :param phone_number: The phone number id in E.164 format. The leading plus can be either + or encoded as %2B, e.g. +11234567890. Required. :type phone_number: str - :param body: Defines the update capabilities request. Is either a model type or a IO type. - Default value is None. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberCapabilitiesRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: - 'application/merge-patch+json'. Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: Defines the update capabilities request. Is either a + PhoneNumberCapabilitiesRequest type or a IO[bytes] type. Default value is None. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberCapabilitiesRequest or + IO[bytes] :return: An instance of AsyncLROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.AsyncLROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1260,7 +1249,7 @@ def get_long_running_output(pipeline_response): deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized path_format_arguments = { @@ -1282,13 +1271,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PurchasedPhoneNumber].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[_models.PurchasedPhoneNumber]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.PurchasedPhoneNumber: @@ -1316,7 +1307,7 @@ async def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.Purch cls: ClsType[_models.PurchasedPhoneNumber] = kwargs.pop("cls", None) - request = build_phone_numbers_get_by_number_request( + _request = build_phone_numbers_get_by_number_request( phone_number=phone_number, api_version=self._config.api_version, headers=_headers, @@ -1325,15 +1316,18 @@ async def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.Purch path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1341,9 +1335,9 @@ async def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.Purch deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore async def _release_phone_number_initial( # pylint: disable=inconsistent-return-statements self, phone_number: str, **kwargs: Any @@ -1361,7 +1355,7 @@ async def _release_phone_number_initial( # pylint: disable=inconsistent-return- cls: ClsType[None] = kwargs.pop("cls", None) - request = build_phone_numbers_release_phone_number_request( + _request = build_phone_numbers_release_phone_number_request( phone_number=phone_number, api_version=self._config.api_version, headers=_headers, @@ -1370,15 +1364,18 @@ async def _release_phone_number_initial( # pylint: disable=inconsistent-return- path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1389,7 +1386,7 @@ async def _release_phone_number_initial( # pylint: disable=inconsistent-return- response_headers["release-id"] = self._deserialize("str", response.headers.get("release-id")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async async def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> AsyncLROPoller[None]: @@ -1399,13 +1396,6 @@ async def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> :param phone_number: Phone number to be released, e.g. +11234567890. Required. :type phone_number: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False - for this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns None :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1425,7 +1415,7 @@ async def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -1441,13 +1431,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_phone_numbers( @@ -1471,9 +1461,9 @@ def list_phone_numbers( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.PurchasedPhoneNumbers] = kwargs.pop( + cls: ClsType[_models._models.PurchasedPhoneNumbers] = kwargs.pop( # pylint: disable=protected-access "cls", None - ) # pylint: disable=protected-access + ) error_map = { 401: ClientAuthenticationError, @@ -1486,7 +1476,7 @@ def list_phone_numbers( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_phone_numbers_request( + _request = build_phone_numbers_list_phone_numbers_request( skip=skip, top=top, api_version=self._config.api_version, @@ -1498,7 +1488,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -1510,7 +1500,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -1518,9 +1508,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -1532,14 +1522,17 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1547,3 +1540,112 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) + + @overload + async def operator_information_search( + self, body: _models.OperatorInformationRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Required. + :type body: ~azure.communication.phonenumbers.models.OperatorInformationRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def operator_information_search( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def operator_information_search( + self, body: Union[_models.OperatorInformationRequest, IO[bytes]], **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Is either a OperatorInformationRequest type or a IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.OperatorInformationRequest or IO[bytes] + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.OperatorInformationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "OperatorInformationRequest") + + _request = build_phone_numbers_operator_information_search_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("OperatorInformationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/__init__.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/__init__.py index b109c061782d..5f0ccddb2b81 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/__init__.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/__init__.py @@ -8,6 +8,11 @@ from ._models import CommunicationError from ._models import CommunicationErrorResponse +from ._models import OperatorDetails +from ._models import OperatorInformation +from ._models import OperatorInformationOptions +from ._models import OperatorInformationRequest +from ._models import OperatorInformationResult from ._models import PhoneNumberAdministrativeDivision from ._models import PhoneNumberAreaCode from ._models import PhoneNumberCapabilities @@ -23,10 +28,12 @@ from ._models import PurchasedPhoneNumber from ._enums import BillingFrequency +from ._enums import OperatorNumberType from ._enums import PhoneNumberAssignmentType from ._enums import PhoneNumberCapabilityType from ._enums import PhoneNumberOperationStatus from ._enums import PhoneNumberOperationType +from ._enums import PhoneNumberSearchResultError from ._enums import PhoneNumberType from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import @@ -35,6 +42,11 @@ __all__ = [ "CommunicationError", "CommunicationErrorResponse", + "OperatorDetails", + "OperatorInformation", + "OperatorInformationOptions", + "OperatorInformationRequest", + "OperatorInformationResult", "PhoneNumberAdministrativeDivision", "PhoneNumberAreaCode", "PhoneNumberCapabilities", @@ -49,10 +61,12 @@ "PhoneNumberSearchResult", "PurchasedPhoneNumber", "BillingFrequency", + "OperatorNumberType", "PhoneNumberAssignmentType", "PhoneNumberCapabilityType", "PhoneNumberOperationStatus", "PhoneNumberOperationType", + "PhoneNumberSearchResultError", "PhoneNumberType", ] __all__.extend([p for p in _patch_all if p not in __all__]) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_enums.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_enums.py index f05059af9f7f..eb5d3091762d 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_enums.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_enums.py @@ -16,6 +16,15 @@ class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): MONTHLY = "monthly" +class OperatorNumberType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of service associated with the phone number.""" + + UNKNOWN = "unknown" + OTHER = "other" + GEOGRAPHIC = "geographic" + MOBILE = "mobile" + + class PhoneNumberAssignmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents the assignment type of the offering.""" @@ -50,6 +59,28 @@ class PhoneNumberOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): UPDATE_PHONE_NUMBER_CAPABILITIES = "updatePhoneNumberCapabilities" +class PhoneNumberSearchResultError(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Mapping Error Messages to Codes.""" + + NO_ERROR = "NoError" + UNKNOWN_ERROR_CODE = "UnknownErrorCode" + OUT_OF_STOCK = "OutOfStock" + AUTHORIZATION_DENIED = "AuthorizationDenied" + MISSING_ADDRESS = "MissingAddress" + INVALID_ADDRESS = "InvalidAddress" + INVALID_OFFER_MODEL = "InvalidOfferModel" + NOT_ENOUGH_LICENSES = "NotEnoughLicenses" + NO_WALLET = "NoWallet" + NOT_ENOUGH_CREDIT = "NotEnoughCredit" + NUMBERS_PARTIALLY_ACQUIRED = "NumbersPartiallyAcquired" + ALL_NUMBERS_NOT_ACQUIRED = "AllNumbersNotAcquired" + RESERVATION_EXPIRED = "ReservationExpired" + PURCHASE_FAILED = "PurchaseFailed" + BILLING_UNAVAILABLE = "BillingUnavailable" + PROVISIONING_FAILED = "ProvisioningFailed" + UNKNOWN_SEARCH_ERROR = "UnknownSearchError" + + class PhoneNumberType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents the number type of the offering.""" diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_models.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_models.py index 041d9f785e92..a24195a88788 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_models.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/models/_models.py @@ -22,7 +22,7 @@ class CommunicationError(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar code: The error code. Required. :vartype code: str @@ -70,7 +70,7 @@ def __init__(self, *, code: str, message: str, **kwargs: Any) -> None: class CommunicationErrorResponse(_serialization.Model): """The Communication Services error. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar error: The Communication Services error. Required. :vartype error: ~azure.communication.phonenumbers.models.CommunicationError @@ -127,10 +127,210 @@ def __init__( self.next_link = next_link +class OperatorDetails(_serialization.Model): + """Represents metadata describing the operator of a phone number. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the phone operator. Required. + :vartype name: str + :ivar mobile_network_code: Mobile Network Code. + :vartype mobile_network_code: str + :ivar mobile_country_code: Mobile Country Code. + :vartype mobile_country_code: str + """ + + _validation = { + "name": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "mobile_network_code": {"key": "mobileNetworkCode", "type": "str"}, + "mobile_country_code": {"key": "mobileCountryCode", "type": "str"}, + } + + def __init__( + self, + *, + name: str, + mobile_network_code: Optional[str] = None, + mobile_country_code: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the phone operator. Required. + :paramtype name: str + :keyword mobile_network_code: Mobile Network Code. + :paramtype mobile_network_code: str + :keyword mobile_country_code: Mobile Country Code. + :paramtype mobile_country_code: str + """ + super().__init__(**kwargs) + self.name = name + self.mobile_network_code = mobile_network_code + self.mobile_country_code = mobile_country_code + + +class OperatorInformation(_serialization.Model): + """Represents metadata about a phone number that is controlled/provided by that phone number's + operator. + + All required parameters must be populated in order to send to server. + + :ivar phone_number: E.164 formatted string representation of the phone number. Required. + :vartype phone_number: str + :ivar national_format: National format of the phone number. + :vartype national_format: str + :ivar international_format: International format of the phone number. + :vartype international_format: str + :ivar iso_country_code: ISO 3166-1 two character ('alpha-2') code associated with the phone + number. + :vartype iso_country_code: str + :ivar number_type: Type of service associated with the phone number. Known values are: + "unknown", "other", "geographic", and "mobile". + :vartype number_type: str or ~azure.communication.phonenumbers.models.OperatorNumberType + :ivar operator_details: Represents metadata describing the operator of a phone number. + :vartype operator_details: ~azure.communication.phonenumbers.models.OperatorDetails + """ + + _validation = { + "phone_number": {"required": True}, + } + + _attribute_map = { + "phone_number": {"key": "phoneNumber", "type": "str"}, + "national_format": {"key": "nationalFormat", "type": "str"}, + "international_format": {"key": "internationalFormat", "type": "str"}, + "iso_country_code": {"key": "isoCountryCode", "type": "str"}, + "number_type": {"key": "numberType", "type": "str"}, + "operator_details": {"key": "operatorDetails", "type": "OperatorDetails"}, + } + + def __init__( + self, + *, + phone_number: str, + national_format: Optional[str] = None, + international_format: Optional[str] = None, + iso_country_code: Optional[str] = None, + number_type: Optional[Union[str, "_models.OperatorNumberType"]] = None, + operator_details: Optional["_models.OperatorDetails"] = None, + **kwargs: Any + ) -> None: + """ + :keyword phone_number: E.164 formatted string representation of the phone number. Required. + :paramtype phone_number: str + :keyword national_format: National format of the phone number. + :paramtype national_format: str + :keyword international_format: International format of the phone number. + :paramtype international_format: str + :keyword iso_country_code: ISO 3166-1 two character ('alpha-2') code associated with the phone + number. + :paramtype iso_country_code: str + :keyword number_type: Type of service associated with the phone number. Known values are: + "unknown", "other", "geographic", and "mobile". + :paramtype number_type: str or ~azure.communication.phonenumbers.models.OperatorNumberType + :keyword operator_details: Represents metadata describing the operator of a phone number. + :paramtype operator_details: ~azure.communication.phonenumbers.models.OperatorDetails + """ + super().__init__(**kwargs) + self.phone_number = phone_number + self.national_format = national_format + self.international_format = international_format + self.iso_country_code = iso_country_code + self.number_type = number_type + self.operator_details = operator_details + + +class OperatorInformationOptions(_serialization.Model): + """Represents options to modify a search request for operator information. + + :ivar include_additional_operator_details: Includes the fields operatorDetails, numberType, and + isoCountryCode in the response. Please note: use of this option will result in additional + costs. + :vartype include_additional_operator_details: bool + """ + + _attribute_map = { + "include_additional_operator_details": {"key": "includeAdditionalOperatorDetails", "type": "bool"}, + } + + def __init__(self, *, include_additional_operator_details: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword include_additional_operator_details: Includes the fields operatorDetails, numberType, + and isoCountryCode in the response. Please note: use of this option will result in additional + costs. + :paramtype include_additional_operator_details: bool + """ + super().__init__(**kwargs) + self.include_additional_operator_details = include_additional_operator_details + + +class OperatorInformationRequest(_serialization.Model): + """Represents a search request for operator information for the given phone numbers. + + All required parameters must be populated in order to send to server. + + :ivar phone_numbers: Phone number(s) whose operator information is being requested. Required. + :vartype phone_numbers: list[str] + :ivar options: Represents options to modify a search request for operator information. + :vartype options: ~azure.communication.phonenumbers.models.OperatorInformationOptions + """ + + _validation = { + "phone_numbers": {"required": True}, + } + + _attribute_map = { + "phone_numbers": {"key": "phoneNumbers", "type": "[str]"}, + "options": {"key": "options", "type": "OperatorInformationOptions"}, + } + + def __init__( + self, *, phone_numbers: List[str], options: Optional["_models.OperatorInformationOptions"] = None, **kwargs: Any + ) -> None: + """ + :keyword phone_numbers: Phone number(s) whose operator information is being requested. + Required. + :paramtype phone_numbers: list[str] + :keyword options: Represents options to modify a search request for operator information. + :paramtype options: ~azure.communication.phonenumbers.models.OperatorInformationOptions + """ + super().__init__(**kwargs) + self.phone_numbers = phone_numbers + self.options = options + + +class OperatorInformationResult(_serialization.Model): + """Represents a search result containing format and operator information associated with the + requested phone numbers. + + :ivar values: Results of a search. + This array will have one entry per requested phone number which will contain the relevant + operator information. + :vartype values: list[~azure.communication.phonenumbers.models.OperatorInformation] + """ + + _attribute_map = { + "values": {"key": "values", "type": "[OperatorInformation]"}, + } + + def __init__(self, *, values: Optional[List["_models.OperatorInformation"]] = None, **kwargs: Any) -> None: + """ + :keyword values: Results of a search. + This array will have one entry per requested phone number which will contain the relevant + operator information. + :paramtype values: list[~azure.communication.phonenumbers.models.OperatorInformation] + """ + super().__init__(**kwargs) + self.values = values + + class PhoneNumberAdministrativeDivision(_serialization.Model): """Represents an administrative division. e.g. state or province. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar localized_name: Represents the localized name of the administrative division of the locality. e.g. state or province localized name. Required. @@ -187,7 +387,7 @@ def __init__(self, *, area_code: Optional[str] = None, **kwargs: Any) -> None: class PhoneNumberAreaCodes(_serialization.Model): """The list of available area codes. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar area_codes: Represents a list of available toll-free area codes. Required. :vartype area_codes: list[~azure.communication.phonenumbers.models.PhoneNumberAreaCode] @@ -221,7 +421,7 @@ def __init__( class PhoneNumberCapabilities(_serialization.Model): """Capabilities of a phone number. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar calling: Capability value for calling. Required. Known values are: "none", "inbound", "outbound", and "inbound+outbound". @@ -300,7 +500,7 @@ def __init__( class PhoneNumberCost(_serialization.Model): """The incurred cost for a single phone number. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar amount: The cost amount. Required. :vartype amount: float @@ -379,7 +579,7 @@ def __init__( class PhoneNumberCountry(_serialization.Model): """Represents a country. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar localized_name: Represents the name of the country. Required. :vartype localized_name: str @@ -448,7 +648,7 @@ def __init__( class PhoneNumberLocality(_serialization.Model): """Represents a locality. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar localized_name: Represents the localized name of the locality. Required. :vartype localized_name: str @@ -489,7 +689,7 @@ def __init__( class PhoneNumberOffering(_serialization.Model): """Represents a phone number capability offering. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar phone_number_type: Represents the number type of the offering. Known values are: "geographic" and "tollFree". @@ -551,7 +751,7 @@ class PhoneNumberOperation(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar operation_type: The type of operation, e.g. Search. Required. Known values are: "purchase", "releasePhoneNumber", "search", and "updatePhoneNumberCapabilities". @@ -652,7 +852,7 @@ class PhoneNumberSearchRequest(_serialization.Model): """Represents a phone number search request to find phone numbers. Found phone numbers are temporarily held for a following purchase. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar phone_number_type: The type of phone numbers to search for, e.g. geographic, or tollFree. Required. Known values are: "geographic" and "tollFree". @@ -722,7 +922,7 @@ def __init__( class PhoneNumberSearchResult(_serialization.Model): """The result of a phone number search operation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar search_id: The search id. Required. :vartype search_id: str @@ -744,6 +944,14 @@ class PhoneNumberSearchResult(_serialization.Model): longer on hold. A search result expires in less than 15min, e.g. 2020-11-19T16:31:49.048Z. Required. :vartype search_expires_by: ~datetime.datetime + :ivar error_code: The error code of the search. + :vartype error_code: int + :ivar error: Mapping Error Messages to Codes. Known values are: "NoError", "UnknownErrorCode", + "OutOfStock", "AuthorizationDenied", "MissingAddress", "InvalidAddress", "InvalidOfferModel", + "NotEnoughLicenses", "NoWallet", "NotEnoughCredit", "NumbersPartiallyAcquired", + "AllNumbersNotAcquired", "ReservationExpired", "PurchaseFailed", "BillingUnavailable", + "ProvisioningFailed", and "UnknownSearchError". + :vartype error: str or ~azure.communication.phonenumbers.models.PhoneNumberSearchResultError """ _validation = { @@ -764,6 +972,8 @@ class PhoneNumberSearchResult(_serialization.Model): "capabilities": {"key": "capabilities", "type": "PhoneNumberCapabilities"}, "cost": {"key": "cost", "type": "PhoneNumberCost"}, "search_expires_by": {"key": "searchExpiresBy", "type": "iso-8601"}, + "error_code": {"key": "errorCode", "type": "int"}, + "error": {"key": "error", "type": "str"}, } def __init__( @@ -776,6 +986,8 @@ def __init__( capabilities: "_models.PhoneNumberCapabilities", cost: "_models.PhoneNumberCost", search_expires_by: datetime.datetime, + error_code: Optional[int] = None, + error: Optional[Union[str, "_models.PhoneNumberSearchResultError"]] = None, **kwargs: Any ) -> None: """ @@ -799,6 +1011,14 @@ def __init__( longer on hold. A search result expires in less than 15min, e.g. 2020-11-19T16:31:49.048Z. Required. :paramtype search_expires_by: ~datetime.datetime + :keyword error_code: The error code of the search. + :paramtype error_code: int + :keyword error: Mapping Error Messages to Codes. Known values are: "NoError", + "UnknownErrorCode", "OutOfStock", "AuthorizationDenied", "MissingAddress", "InvalidAddress", + "InvalidOfferModel", "NotEnoughLicenses", "NoWallet", "NotEnoughCredit", + "NumbersPartiallyAcquired", "AllNumbersNotAcquired", "ReservationExpired", "PurchaseFailed", + "BillingUnavailable", "ProvisioningFailed", and "UnknownSearchError". + :paramtype error: str or ~azure.communication.phonenumbers.models.PhoneNumberSearchResultError """ super().__init__(**kwargs) self.search_id = search_id @@ -808,12 +1028,14 @@ def __init__( self.capabilities = capabilities self.cost = cost self.search_expires_by = search_expires_by + self.error_code = error_code + self.error = error class PurchasedPhoneNumber(_serialization.Model): """Represents a purchased phone number. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: The id of the phone number, e.g. 11234567890. Required. :vartype id: str @@ -909,7 +1131,7 @@ def __init__( class PurchasedPhoneNumbers(_serialization.Model): """The list of purchased phone numbers. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar phone_numbers: Represents a list of phone numbers. Required. :vartype phone_numbers: list[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/operations/_operations.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/operations/_operations.py index 7b299a67dd5c..5c94c4588389 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/operations/_operations.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_generated/operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +6,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload import urllib.parse @@ -20,21 +20,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.polling.base_polling import LROBasePolling -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from .. import models as _models from .._serialization import Serializer -from .._vendor import _format_url_section -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -42,21 +36,22 @@ _SERIALIZER.client_side_validation = False -def build_phone_numbers_list_area_codes_request( +def build_phone_numbers_list_area_codes_request( # pylint: disable=name-too-long country_code: str, *, phone_number_type: Union[str, _models.PhoneNumberType], skip: int = 0, + max_page_size: int = 100, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, locality: Optional[str] = None, administrative_division: Optional[str] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -65,12 +60,14 @@ def build_phone_numbers_list_area_codes_request( "countryCode": _SERIALIZER.url("country_code", country_code, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["phoneNumberType"] = _SERIALIZER.query("phone_number_type", phone_number_type, "str") if skip is not None: _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if max_page_size is not None: + _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") if assignment_type is not None: _params["assignmentType"] = _SERIALIZER.query("assignment_type", assignment_type, "str") if locality is not None: @@ -87,13 +84,13 @@ def build_phone_numbers_list_area_codes_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_list_available_countries_request( - *, skip: int = 0, accept_language: Optional[str] = None, **kwargs: Any +def build_phone_numbers_list_available_countries_request( # pylint: disable=name-too-long + *, skip: int = 0, max_page_size: int = 100, accept_language: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -102,6 +99,8 @@ def build_phone_numbers_list_available_countries_request( # Construct parameters if skip is not None: _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if max_page_size is not None: + _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -112,18 +111,19 @@ def build_phone_numbers_list_available_countries_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_list_available_localities_request( +def build_phone_numbers_list_available_localities_request( # pylint: disable=name-too-long country_code: str, *, skip: int = 0, + max_page_size: int = 100, administrative_division: Optional[str] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -132,11 +132,13 @@ def build_phone_numbers_list_available_localities_request( "countryCode": _SERIALIZER.url("country_code", country_code, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if skip is not None: _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if max_page_size is not None: + _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") if administrative_division is not None: _params["administrativeDivision"] = _SERIALIZER.query("administrative_division", administrative_division, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -149,19 +151,20 @@ def build_phone_numbers_list_available_localities_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_list_offerings_request( +def build_phone_numbers_list_offerings_request( # pylint: disable=name-too-long country_code: str, *, skip: int = 0, + max_page_size: int = 100, phone_number_type: Optional[Union[str, _models.PhoneNumberType]] = None, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -170,11 +173,13 @@ def build_phone_numbers_list_offerings_request( "countryCode": _SERIALIZER.url("country_code", country_code, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if skip is not None: _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if max_page_size is not None: + _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") if phone_number_type is not None: _params["phoneNumberType"] = _SERIALIZER.query("phone_number_type", phone_number_type, "str") if assignment_type is not None: @@ -189,12 +194,14 @@ def build_phone_numbers_list_offerings_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_search_available_phone_numbers_request(country_code: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_search_available_phone_numbers_request( # pylint: disable=name-too-long + country_code: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -203,7 +210,7 @@ def build_phone_numbers_search_available_phone_numbers_request(country_code: str "countryCode": _SERIALIZER.url("country_code", country_code, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -216,11 +223,13 @@ def build_phone_numbers_search_available_phone_numbers_request(country_code: str return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_get_search_result_request(search_id: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_get_search_result_request( # pylint: disable=name-too-long + search_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -229,7 +238,7 @@ def build_phone_numbers_get_search_result_request(search_id: str, **kwargs: Any) "searchId": _SERIALIZER.url("search_id", search_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -240,12 +249,12 @@ def build_phone_numbers_get_search_result_request(search_id: str, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_purchase_phone_numbers_request(**kwargs: Any) -> HttpRequest: +def build_phone_numbers_purchase_phone_numbers_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 {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -262,11 +271,13 @@ def build_phone_numbers_purchase_phone_numbers_request(**kwargs: Any) -> HttpReq return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_get_operation_request(operation_id: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_get_operation_request( # pylint: disable=name-too-long + operation_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -275,7 +286,7 @@ def build_phone_numbers_get_operation_request(operation_id: str, **kwargs: Any) "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -286,11 +297,13 @@ def build_phone_numbers_get_operation_request(operation_id: str, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_cancel_operation_request(operation_id: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_cancel_operation_request( # pylint: disable=name-too-long + operation_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -299,7 +312,7 @@ def build_phone_numbers_cancel_operation_request(operation_id: str, **kwargs: An "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -310,12 +323,14 @@ def build_phone_numbers_cancel_operation_request(operation_id: str, **kwargs: An return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_update_capabilities_request(phone_number: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_update_capabilities_request( # pylint: disable=name-too-long + phone_number: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -324,7 +339,7 @@ def build_phone_numbers_update_capabilities_request(phone_number: str, **kwargs: "phoneNumber": _SERIALIZER.url("phone_number", phone_number, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -337,11 +352,13 @@ def build_phone_numbers_update_capabilities_request(phone_number: str, **kwargs: return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_get_by_number_request(phone_number: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_get_by_number_request( # pylint: disable=name-too-long + phone_number: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -350,7 +367,7 @@ def build_phone_numbers_get_by_number_request(phone_number: str, **kwargs: Any) "phoneNumber": _SERIALIZER.url("phone_number", phone_number, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -361,11 +378,13 @@ def build_phone_numbers_get_by_number_request(phone_number: str, **kwargs: Any) return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_release_phone_number_request(phone_number: str, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_release_phone_number_request( # pylint: disable=name-too-long + phone_number: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -374,7 +393,7 @@ def build_phone_numbers_release_phone_number_request(phone_number: str, **kwargs "phoneNumber": _SERIALIZER.url("phone_number", phone_number, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -385,11 +404,13 @@ def build_phone_numbers_release_phone_number_request(phone_number: str, **kwargs return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_phone_numbers_list_phone_numbers_request(*, skip: int = 0, top: int = 100, **kwargs: Any) -> HttpRequest: +def build_phone_numbers_list_phone_numbers_request( # pylint: disable=name-too-long + *, skip: int = 0, top: int = 100, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2022-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2022-12-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -408,6 +429,30 @@ def build_phone_numbers_list_phone_numbers_request(*, skip: int = 0, top: int = return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) +def build_phone_numbers_operator_information_search_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + 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-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/operatorInformation/:search" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # 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) + + class PhoneNumbersOperations: """ .. warning:: @@ -434,11 +479,12 @@ def list_area_codes( *, phone_number_type: Union[str, _models.PhoneNumberType], skip: int = 0, + max_page_size: int = 100, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, locality: Optional[str] = None, administrative_division: Optional[str] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Iterable["_models.PhoneNumberAreaCode"]: """Gets the list of available area codes. @@ -452,7 +498,10 @@ def list_area_codes( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int - :keyword assignment_type: Filter by assignmentType, e.g. User, Application. Known values are: + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int + :keyword assignment_type: Filter by assignmentType, e.g. Person, Application. Known values are: "person" and "application". Default value is None. :paramtype assignment_type: str or ~azure.communication.phonenumbers.models.PhoneNumberAssignmentType @@ -486,10 +535,11 @@ def list_area_codes( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_area_codes_request( + _request = build_phone_numbers_list_area_codes_request( country_code=country_code, phone_number_type=phone_number_type, skip=skip, + max_page_size=max_page_size, assignment_type=assignment_type, locality=locality, administrative_division=administrative_division, @@ -503,7 +553,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -515,7 +565,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -523,9 +573,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -537,14 +587,17 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -555,7 +608,7 @@ def get_next(next_link=None): @distributed_trace def list_available_countries( - self, *, skip: int = 0, accept_language: Optional[str] = None, **kwargs: Any + self, *, skip: int = 0, max_page_size: int = 100, accept_language: Optional[str] = None, **kwargs: Any ) -> Iterable["_models.PhoneNumberCountry"]: """Gets the list of supported countries. @@ -564,6 +617,9 @@ def list_available_countries( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword accept_language: The locale to display in the localized fields in the response. e.g. 'en-US'. Default value is None. :paramtype accept_language: str @@ -588,8 +644,9 @@ def list_available_countries( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_available_countries_request( + _request = build_phone_numbers_list_available_countries_request( skip=skip, + max_page_size=max_page_size, accept_language=accept_language, api_version=self._config.api_version, headers=_headers, @@ -600,7 +657,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -612,7 +669,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -620,9 +677,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -634,14 +691,17 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -656,9 +716,10 @@ def list_available_localities( country_code: str, *, skip: int = 0, + max_page_size: int = 100, administrative_division: Optional[str] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Iterable["_models.PhoneNumberLocality"]: """Gets the list of cities or towns with available phone numbers. @@ -669,6 +730,9 @@ def list_available_localities( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword administrative_division: An optional parameter for the name of the state or province in which to search for the area code. Default value is None. :paramtype administrative_division: str @@ -683,9 +747,9 @@ def list_available_localities( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.PhoneNumberLocalities] = kwargs.pop( + cls: ClsType[_models._models.PhoneNumberLocalities] = kwargs.pop( # pylint: disable=protected-access "cls", None - ) # pylint: disable=protected-access + ) error_map = { 401: ClientAuthenticationError, @@ -698,9 +762,10 @@ def list_available_localities( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_available_localities_request( + _request = build_phone_numbers_list_available_localities_request( country_code=country_code, skip=skip, + max_page_size=max_page_size, administrative_division=administrative_division, accept_language=accept_language, api_version=self._config.api_version, @@ -712,7 +777,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -724,7 +789,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -732,9 +797,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -746,14 +811,17 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -768,10 +836,11 @@ def list_offerings( country_code: str, *, skip: int = 0, + max_page_size: int = 100, phone_number_type: Optional[Union[str, _models.PhoneNumberType]] = None, assignment_type: Optional[Union[str, _models.PhoneNumberAssignmentType]] = None, accept_language: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Iterable["_models.PhoneNumberOffering"]: """List available offerings of capabilities with rates for the given country. @@ -782,6 +851,9 @@ def list_offerings( :keyword skip: An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. Default value is 0. :paramtype skip: int + :keyword max_page_size: An optional parameter for how many entries to return, for pagination + purposes. The default value is 100. Default value is 100. + :paramtype max_page_size: int :keyword phone_number_type: Filter by numberType, e.g. Geographic, TollFree. Known values are: "geographic" and "tollFree". Default value is None. :paramtype phone_number_type: str or ~azure.communication.phonenumbers.models.PhoneNumberType @@ -813,9 +885,10 @@ def list_offerings( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_offerings_request( + _request = build_phone_numbers_list_offerings_request( country_code=country_code, skip=skip, + max_page_size=max_page_size, phone_number_type=phone_number_type, assignment_type=assignment_type, accept_language=accept_language, @@ -828,7 +901,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -840,7 +913,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -848,9 +921,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -862,14 +935,17 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -879,7 +955,7 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) def _search_available_phone_numbers_initial( - self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO], **kwargs: Any + self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO[bytes]], **kwargs: Any ) -> _models.PhoneNumberSearchResult: error_map = { 401: ClientAuthenticationError, @@ -898,12 +974,12 @@ def _search_available_phone_numbers_initial( content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: _json = self._serialize.body(body, "PhoneNumberSearchRequest") - request = build_phone_numbers_search_available_phone_numbers_request( + _request = build_phone_numbers_search_available_phone_numbers_request( country_code=country_code, content_type=content_type, api_version=self._config.api_version, @@ -915,15 +991,18 @@ def _search_available_phone_numbers_initial( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -937,9 +1016,9 @@ def _search_available_phone_numbers_initial( deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload def begin_search_available_phone_numbers( @@ -948,7 +1027,7 @@ def begin_search_available_phone_numbers( body: _models.PhoneNumberSearchRequest, *, content_type: str = "application/json", - **kwargs: Any + **kwargs: Any, ) -> LROPoller[_models.PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -961,13 +1040,6 @@ def begin_search_available_phone_numbers( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -976,7 +1048,7 @@ def begin_search_available_phone_numbers( @overload def begin_search_available_phone_numbers( - self, country_code: str, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, country_code: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -985,17 +1057,10 @@ def begin_search_available_phone_numbers( :param country_code: The ISO 3166-2 country code, e.g. US. Required. :type country_code: str :param body: The phone number search request. Required. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -1004,7 +1069,7 @@ def begin_search_available_phone_numbers( @distributed_trace def begin_search_available_phone_numbers( - self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO], **kwargs: Any + self, country_code: str, body: Union[_models.PhoneNumberSearchRequest, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.PhoneNumberSearchResult]: """Search for available phone numbers to purchase. @@ -1012,18 +1077,9 @@ def begin_search_available_phone_numbers( :param country_code: The ISO 3166-2 country code, e.g. US. Required. :type country_code: str - :param body: The phone number search request. Is either a model type or a IO type. Required. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberSearchRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: The phone number search request. Is either a PhoneNumberSearchRequest type or a + IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberSearchRequest or IO[bytes] :return: An instance of LROPoller that returns PhoneNumberSearchResult :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PhoneNumberSearchResult] @@ -1045,7 +1101,7 @@ def begin_search_available_phone_numbers( cls=lambda x, y, z: x, headers=_headers, params=_params, - **kwargs + **kwargs, ) kwargs.pop("error_map", None) @@ -1061,7 +1117,7 @@ def get_long_running_output(pipeline_response): deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized path_format_arguments = { @@ -1075,7 +1131,7 @@ def get_long_running_output(pipeline_response): lro_delay, lro_options={"final-state-via": "location"}, path_format_arguments=path_format_arguments, - **kwargs + **kwargs, ), ) elif polling is False: @@ -1083,13 +1139,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PhoneNumberSearchResult].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.PhoneNumberSearchResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_search_result(self, search_id: str, **kwargs: Any) -> _models.PhoneNumberSearchResult: @@ -1116,7 +1174,7 @@ def get_search_result(self, search_id: str, **kwargs: Any) -> _models.PhoneNumbe cls: ClsType[_models.PhoneNumberSearchResult] = kwargs.pop("cls", None) - request = build_phone_numbers_get_search_result_request( + _request = build_phone_numbers_get_search_result_request( search_id=search_id, api_version=self._config.api_version, headers=_headers, @@ -1125,15 +1183,18 @@ def get_search_result(self, search_id: str, **kwargs: Any) -> _models.PhoneNumbe path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1141,12 +1202,12 @@ def get_search_result(self, search_id: str, **kwargs: Any) -> _models.PhoneNumbe deserialized = self._deserialize("PhoneNumberSearchResult", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-return-statements - self, body: Union[_models.PhoneNumberPurchaseRequest, IO], **kwargs: Any + self, body: Union[_models.PhoneNumberPurchaseRequest, IO[bytes]], **kwargs: Any ) -> None: error_map = { 401: ClientAuthenticationError, @@ -1165,12 +1226,12 @@ def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-return-stat content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: _json = self._serialize.body(body, "PhoneNumberPurchaseRequest") - request = build_phone_numbers_purchase_phone_numbers_request( + _request = build_phone_numbers_purchase_phone_numbers_request( content_type=content_type, api_version=self._config.api_version, json=_json, @@ -1181,15 +1242,18 @@ def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-return-stat path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1200,7 +1264,7 @@ def _purchase_phone_numbers_initial( # pylint: disable=inconsistent-return-stat response_headers["purchase-id"] = self._deserialize("str", response.headers.get("purchase-id")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @overload def begin_purchase_phone_numbers( @@ -1215,13 +1279,6 @@ def begin_purchase_phone_numbers( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns None :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1229,24 +1286,17 @@ def begin_purchase_phone_numbers( @overload def begin_purchase_phone_numbers( - self, body: IO, *, content_type: str = "application/json", **kwargs: Any + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Purchases phone numbers. Purchases phone numbers. :param body: The phone number purchase request. Required. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns None :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1254,24 +1304,15 @@ def begin_purchase_phone_numbers( @distributed_trace def begin_purchase_phone_numbers( - self, body: Union[_models.PhoneNumberPurchaseRequest, IO], **kwargs: Any + self, body: Union[_models.PhoneNumberPurchaseRequest, IO[bytes]], **kwargs: Any ) -> LROPoller[None]: """Purchases phone numbers. Purchases phone numbers. - :param body: The phone number purchase request. Is either a model type or a IO type. Required. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberPurchaseRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: The phone number purchase request. Is either a PhoneNumberPurchaseRequest type or + a IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberPurchaseRequest or IO[bytes] :return: An instance of LROPoller that returns None :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1292,7 +1333,7 @@ def begin_purchase_phone_numbers( def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -1307,13 +1348,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get_operation(self, operation_id: str, **kwargs: Any) -> _models.PhoneNumberOperation: @@ -1340,7 +1381,7 @@ def get_operation(self, operation_id: str, **kwargs: Any) -> _models.PhoneNumber cls: ClsType[_models.PhoneNumberOperation] = kwargs.pop("cls", None) - request = build_phone_numbers_get_operation_request( + _request = build_phone_numbers_get_operation_request( operation_id=operation_id, api_version=self._config.api_version, headers=_headers, @@ -1349,15 +1390,18 @@ def get_operation(self, operation_id: str, **kwargs: Any) -> _models.PhoneNumber path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1368,9 +1412,9 @@ def get_operation(self, operation_id: str, **kwargs: Any) -> _models.PhoneNumber deserialized = self._deserialize("PhoneNumberOperation", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @distributed_trace def cancel_operation( # pylint: disable=inconsistent-return-statements @@ -1399,7 +1443,7 @@ def cancel_operation( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - request = build_phone_numbers_cancel_operation_request( + _request = build_phone_numbers_cancel_operation_request( operation_id=operation_id, api_version=self._config.api_version, headers=_headers, @@ -1408,24 +1452,30 @@ def cancel_operation( # pylint: disable=inconsistent-return-statements path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [204]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore def _update_capabilities_initial( - self, phone_number: str, body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO]] = None, **kwargs: Any + self, + phone_number: str, + body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO[bytes]]] = None, + **kwargs: Any, ) -> _models.PurchasedPhoneNumber: error_map = { 401: ClientAuthenticationError, @@ -1444,7 +1494,7 @@ def _update_capabilities_initial( content_type = content_type or "application/merge-patch+json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -1452,7 +1502,7 @@ def _update_capabilities_initial( else: _json = None - request = build_phone_numbers_update_capabilities_request( + _request = build_phone_numbers_update_capabilities_request( phone_number=phone_number, content_type=content_type, api_version=self._config.api_version, @@ -1464,15 +1514,18 @@ def _update_capabilities_initial( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1486,9 +1539,9 @@ def _update_capabilities_initial( deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + return deserialized # type: ignore @overload def begin_update_capabilities( @@ -1497,7 +1550,7 @@ def begin_update_capabilities( body: Optional[_models.PhoneNumberCapabilitiesRequest] = None, *, content_type: str = "application/merge-patch+json", - **kwargs: Any + **kwargs: Any, ) -> LROPoller[_models.PurchasedPhoneNumber]: """Updates the capabilities of a phone number. @@ -1511,13 +1564,6 @@ def begin_update_capabilities( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1528,10 +1574,10 @@ def begin_update_capabilities( def begin_update_capabilities( self, phone_number: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/merge-patch+json", - **kwargs: Any + **kwargs: Any, ) -> LROPoller[_models.PurchasedPhoneNumber]: """Updates the capabilities of a phone number. @@ -1541,17 +1587,10 @@ def begin_update_capabilities( encoded as %2B, e.g. +11234567890. Required. :type phone_number: str :param body: Defines the update capabilities request. Default value is None. - :type body: IO + :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/merge-patch+json". :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1560,7 +1599,10 @@ def begin_update_capabilities( @distributed_trace def begin_update_capabilities( - self, phone_number: str, body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO]] = None, **kwargs: Any + self, + phone_number: str, + body: Optional[Union[_models.PhoneNumberCapabilitiesRequest, IO[bytes]]] = None, + **kwargs: Any, ) -> LROPoller[_models.PurchasedPhoneNumber]: """Updates the capabilities of a phone number. @@ -1569,19 +1611,10 @@ def begin_update_capabilities( :param phone_number: The phone number id in E.164 format. The leading plus can be either + or encoded as %2B, e.g. +11234567890. Required. :type phone_number: str - :param body: Defines the update capabilities request. Is either a model type or a IO type. - Default value is None. - :type body: ~azure.communication.phonenumbers.models.PhoneNumberCapabilitiesRequest or IO - :keyword content_type: Body Parameter content-type. Known values are: - 'application/merge-patch+json'. Default value is None. - :paramtype content_type: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param body: Defines the update capabilities request. Is either a + PhoneNumberCapabilitiesRequest type or a IO[bytes] type. Default value is None. + :type body: ~azure.communication.phonenumbers.models.PhoneNumberCapabilitiesRequest or + IO[bytes] :return: An instance of LROPoller that returns PurchasedPhoneNumber :rtype: ~azure.core.polling.LROPoller[~azure.communication.phonenumbers.models.PurchasedPhoneNumber] @@ -1603,7 +1636,7 @@ def begin_update_capabilities( cls=lambda x, y, z: x, headers=_headers, params=_params, - **kwargs + **kwargs, ) kwargs.pop("error_map", None) @@ -1619,7 +1652,7 @@ def get_long_running_output(pipeline_response): deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized path_format_arguments = { @@ -1633,7 +1666,7 @@ def get_long_running_output(pipeline_response): lro_delay, lro_options={"final-state-via": "location"}, path_format_arguments=path_format_arguments, - **kwargs + **kwargs, ), ) elif polling is False: @@ -1641,13 +1674,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PurchasedPhoneNumber].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[_models.PurchasedPhoneNumber]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.PurchasedPhoneNumber: @@ -1675,7 +1710,7 @@ def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.PurchasedPh cls: ClsType[_models.PurchasedPhoneNumber] = kwargs.pop("cls", None) - request = build_phone_numbers_get_by_number_request( + _request = build_phone_numbers_get_by_number_request( phone_number=phone_number, api_version=self._config.api_version, headers=_headers, @@ -1684,15 +1719,18 @@ def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.PurchasedPh path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1700,9 +1738,9 @@ def get_by_number(self, phone_number: str, **kwargs: Any) -> _models.PurchasedPh deserialized = self._deserialize("PurchasedPhoneNumber", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore def _release_phone_number_initial( # pylint: disable=inconsistent-return-statements self, phone_number: str, **kwargs: Any @@ -1720,7 +1758,7 @@ def _release_phone_number_initial( # pylint: disable=inconsistent-return-statem cls: ClsType[None] = kwargs.pop("cls", None) - request = build_phone_numbers_release_phone_number_request( + _request = build_phone_numbers_release_phone_number_request( phone_number=phone_number, api_version=self._config.api_version, headers=_headers, @@ -1729,15 +1767,18 @@ def _release_phone_number_initial( # pylint: disable=inconsistent-return-statem path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [202]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1748,7 +1789,7 @@ def _release_phone_number_initial( # pylint: disable=inconsistent-return-statem response_headers["release-id"] = self._deserialize("str", response.headers.get("release-id")) if cls: - return cls(pipeline_response, None, response_headers) + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> LROPoller[None]: @@ -1758,13 +1799,6 @@ def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> LROPol :param phone_number: Phone number to be released, e.g. +11234567890. Required. :type phone_number: str - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns None :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -1784,7 +1818,7 @@ def begin_release_phone_number(self, phone_number: str, **kwargs: Any) -> LROPol def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), @@ -1799,13 +1833,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[None].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_phone_numbers( @@ -1829,9 +1863,9 @@ def list_phone_numbers( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.PurchasedPhoneNumbers] = kwargs.pop( + cls: ClsType[_models._models.PurchasedPhoneNumbers] = kwargs.pop( # pylint: disable=protected-access "cls", None - ) # pylint: disable=protected-access + ) error_map = { 401: ClientAuthenticationError, @@ -1844,7 +1878,7 @@ def list_phone_numbers( def prepare_request(next_link=None): if not next_link: - request = build_phone_numbers_list_phone_numbers_request( + _request = build_phone_numbers_list_phone_numbers_request( skip=skip, top=top, api_version=self._config.api_version, @@ -1856,7 +1890,7 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version @@ -1868,7 +1902,7 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { @@ -1876,9 +1910,9 @@ def prepare_request(next_link=None): "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -1890,14 +1924,17 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) @@ -1905,3 +1942,112 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) + + @overload + def operator_information_search( + self, body: _models.OperatorInformationRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Required. + :type body: ~azure.communication.phonenumbers.models.OperatorInformationRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def operator_information_search( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def operator_information_search( + self, body: Union[_models.OperatorInformationRequest, IO[bytes]], **kwargs: Any + ) -> _models.OperatorInformationResult: + """Searches for number format and operator information for a given list of phone numbers. + + Searches for number format and operator information for a given list of phone numbers. + + :param body: The phone number(s) whose number format and operator information should be + searched. Is either a OperatorInformationRequest type or a IO[bytes] type. Required. + :type body: ~azure.communication.phonenumbers.models.OperatorInformationRequest or IO[bytes] + :return: OperatorInformationResult + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.OperatorInformationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "OperatorInformationRequest") + + _request = build_phone_numbers_operator_information_search_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.CommunicationErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("OperatorInformationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py index 7eff7ad9e207..3c7f17935f26 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_phone_numbers_client.py @@ -4,7 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Optional, Union from azure.core.tracing.decorator import distributed_trace from azure.core.exceptions import HttpResponseError from ._generated._client import PhoneNumbersClient as PhoneNumbersClientGen @@ -13,6 +13,9 @@ PhoneNumberCapabilitiesRequest, PhoneNumberPurchaseRequest, PhoneNumberType, + OperatorInformationRequest, + OperatorInformationOptions, + OperatorInformationResult, ) from ._shared.auth_policy_utils import get_authentication_policy from ._shared.utils import parse_connection_str @@ -36,7 +39,6 @@ PurchasedPhoneNumber, ) - class PhoneNumbersClient(object): """A client to interact with the AzureCommunicationService Phone Numbers gateway. @@ -423,3 +425,29 @@ def list_available_area_codes( "administrative_division", None), **kwargs ) + + @distributed_trace + def search_operator_information( + self, + phone_numbers, # type: Union[ str, list[str] ] + options:Optional[OperatorInformationOptions]=None, #type: OperatorInformationOptions + **kwargs # type: Any + ) -> OperatorInformationResult: + """Searches for operator information for a given list of phone numbers. + + :param phone_numbers: The phone number(s) whose operator information should be searched + :type phone_numbers: str or list[str] + :param options: Options to modify the search. Please note: use of options can affect the cost of the search. + :type options: OperatorInformationOptions + :return: A search result containing operator information associated with the requested phone numbers + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + """ + if not isinstance(phone_numbers, list): + phone_numbers = [ phone_numbers ] + if options is None: + options = OperatorInformationOptions(include_additional_operator_details=False) + request = OperatorInformationRequest(phone_numbers = phone_numbers, options=options) + return self._phone_number_client.phone_numbers.operator_information_search( + request, + **kwargs + ) diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_version.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_version.py index c7ec790f1ffa..b8f009265c85 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_version.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/_version.py @@ -4,6 +4,6 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "1.1.1" +VERSION = "1.2.0b2" SDK_MONIKER = "communication-phonenumbers/{}".format(VERSION) # type: str diff --git a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py index e4cdf43274fe..7e5de5257fed 100644 --- a/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py +++ b/sdk/communication/azure-communication-phonenumbers/azure/communication/phonenumbers/aio/_phone_numbers_client_async.py @@ -4,7 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING, Union +from typing import TYPE_CHECKING, Optional, Union from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from .._generated.aio._client import PhoneNumbersClient as PhoneNumbersClientGen @@ -13,6 +13,9 @@ PhoneNumberCapabilitiesRequest, PhoneNumberPurchaseRequest, PhoneNumberType, + OperatorInformationOptions, + OperatorInformationRequest, + OperatorInformationResult, ) from .._shared.auth_policy_utils import get_authentication_policy from .._shared.utils import parse_connection_str @@ -36,7 +39,6 @@ PurchasedPhoneNumber, ) - class PhoneNumbersClient(object): """A client to interact with the AzureCommunicationService Phone Numbers gateway. @@ -421,6 +423,32 @@ def list_available_area_codes( **kwargs ) + @distributed_trace + def search_operator_information( + self, + phone_numbers, # type: Union [ str, List[str] ] + options:Optional[OperatorInformationOptions]=None, #type: OperatorInformationOptions + **kwargs # type: Any + ) -> OperatorInformationResult: + """Searches for operator information for a given list of phone numbers. + + :param phone_numbers: The phone number(s) whose operator information should be searched + :type phone_numbers: str or list[str] + :param options: Options to modify the search. Please note: use of options can affect the cost of the search. + :type options: OperatorInformationOptions + :return: A search result containing operator information associated with the requested phone numbers + :rtype: ~azure.communication.phonenumbers.models.OperatorInformationResult + """ + if not isinstance(phone_numbers, list): + phone_numbers = [ phone_numbers ] + if options is None: + options = OperatorInformationOptions(include_additional_operator_details=False) + request = OperatorInformationRequest(phone_numbers = phone_numbers, options = options) + return self._phone_number_client.phone_numbers.operator_information_search( + request, + **kwargs + ) + async def __aenter__(self) -> "PhoneNumbersClient": await self._phone_number_client.__aenter__() return self diff --git a/sdk/communication/azure-communication-phonenumbers/setup.py b/sdk/communication/azure-communication-phonenumbers/setup.py index 0c8171f86964..dd9d04d0f9ef 100644 --- a/sdk/communication/azure-communication-phonenumbers/setup.py +++ b/sdk/communication/azure-communication-phonenumbers/setup.py @@ -69,7 +69,7 @@ python_requires=">=3.8", install_requires=[ "msrest>=0.7.1", - 'azure-core>=1.24.0', + 'azure-core<2.0.0,>=1.28.0', ], extras_require={ ":python_version<'3.8'": ["typing-extensions"] @@ -78,4 +78,4 @@ 'Bug Reports': 'https://github.com/Azure/azure-sdk-for-python/issues', 'Source': 'https://github.com/Azure/azure-sdk-for-python', } -) \ No newline at end of file +) diff --git a/sdk/communication/azure-communication-phonenumbers/swagger/PHONE_NUMBER_SWAGGER.md b/sdk/communication/azure-communication-phonenumbers/swagger/PHONE_NUMBER_SWAGGER.md index 9cbde226df04..6f64eaa011e7 100644 --- a/sdk/communication/azure-communication-phonenumbers/swagger/PHONE_NUMBER_SWAGGER.md +++ b/sdk/communication/azure-communication-phonenumbers/swagger/PHONE_NUMBER_SWAGGER.md @@ -10,8 +10,8 @@ autorest ./PHONE_NUMBER_SWAGGER.md ### Settings ``` yaml -tag: package-phonenumber-2022-12-01 -require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/edf1d7365a436f0b124c0cecbefd63499e049af0/specification/communication/data-plane/PhoneNumbers/readme.md +tag: package-phonenumber-2024-03-01-preview +require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/b56afb26c5450157006a3a1d9be57bae429051a2/specification/communication/data-plane/PhoneNumbers/readme.md output-folder: ../azure/communication/phonenumbers/_generated namespace: azure.communication.phonenumbers license-header: MICROSOFT_MIT_NO_VERSION @@ -22,4 +22,20 @@ v3: true python: true title: Phone Numbers Client models-mode: msrest +``` + +``` yaml +directive: + from: swagger-document + where: $.definitions.PhoneNumberSearchResult.properties.error.x-ms-enum + transform: > + $["name"] = "PhoneNumberSearchResultError"; +``` + +``` yaml +directive: + from: swagger-document + where: $.parameters.Endpoint + transform: > + $["format"] = ""; ``` \ No newline at end of file diff --git a/sdk/communication/azure-communication-phonenumbers/test/conftest.py b/sdk/communication/azure-communication-phonenumbers/test/conftest.py index f44bdbb91462..1a3a61aee77c 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/conftest.py +++ b/sdk/communication/azure-communication-phonenumbers/test/conftest.py @@ -49,7 +49,7 @@ def add_sanitizers(test_proxy): add_general_regex_sanitizer( regex=r"-[0-9a-fA-F]{32}\.[0-9a-zA-Z\.]*(\.com|\.net|\.test)", value=".sanitized.com") - add_general_regex_sanitizer(regex=r"[%2B\d]{10,15}", value="sanitized") + add_general_regex_sanitizer(regex=r"(?:(?:%2B)|\+)\d{10,15}", value="sanitized") add_general_regex_sanitizer( regex=r"phoneNumbers/[%2B\d]{10,15}", value="phoneNumbers/sanitized") diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py index 9eeecfbe79d3..fc13ad8d8159 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client.py @@ -383,3 +383,39 @@ def test_list_offerings_from_managed_identity(self): def test_list_offerings(self): offerings = self.phone_number_client.list_available_offerings("US") assert offerings.next() + + @recorded_by_proxy + def test_search_operator_information_with_too_many_phone_numbers(self): + if self.is_playback(): + phone_numbers = [ "sanitized", "sanitized" ] + else: + phone_numbers = [ self.phone_number, self.phone_number ] + + with pytest.raises(Exception) as ex: + self.phone_number_client.search_operator_information(phone_numbers) + + assert is_client_error_status_code( + ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ex.value.message is not None # type: ignore + + @recorded_by_proxy + def test_search_operator_information_with_list(self): + if self.is_playback(): + phone_number = "sanitized" + else: + phone_number = self.phone_number + + results = self.phone_number_client.search_operator_information([ phone_number ]) + assert len(results.values) == 1 + assert results.values[0].phone_number == self.phone_number + + @recorded_by_proxy + def test_search_operator_information_with_single_string(self): + if self.is_playback(): + phone_number = "sanitized" + else: + phone_number = self.phone_number + + results = self.phone_number_client.search_operator_information(phone_number) + assert len(results.values) == 1 + assert results.values[0].phone_number == self.phone_number diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py index d69951f77481..fefd3ec7517b 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_administration_client_async.py @@ -461,3 +461,42 @@ async def test_list_offerings(self): async for item in offerings: items.append(item) assert len(items) > 0 + + @recorded_by_proxy_async + async def test_search_operator_information_with_too_many_phone_numbers(self): + if self.is_playback(): + phone_numbers = [ "sanitized", "sanitized" ] + else: + phone_numbers = [ self.phone_number, self.phone_number ] + + with pytest.raises(Exception) as ex: + async with self.phone_number_client: + await self.phone_number_client.search_operator_information(phone_numbers) + + assert is_client_error_status_code( + ex.value.status_code) is True, 'Status code {ex.value.status_code} does not indicate a client error' # type: ignore + assert ex.value.message is not None # type: ignore + + @recorded_by_proxy_async + async def test_search_operator_information_with_list(self): + if self.is_playback(): + phone_number = "sanitized" + else: + phone_number = self.phone_number + + async with self.phone_number_client: + results = await self.phone_number_client.search_operator_information([ phone_number ]) + assert len(results.values) == 1 + assert results.values[0].phone_number == self.phone_number + + @recorded_by_proxy_async + async def test_search_operator_information_with_single_string(self): + if self.is_playback(): + phone_number = "sanitized" + else: + phone_number = self.phone_number + + async with self.phone_number_client: + results = await self.phone_number_client.search_operator_information(phone_number) + assert len(results.values) == 1 + assert results.values[0].phone_number == self.phone_number diff --git a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py index 5699cbc2700f..cccc676616e8 100644 --- a/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py +++ b/sdk/communication/azure-communication-phonenumbers/test/test_phone_number_operations.py @@ -7,10 +7,11 @@ import pytest from azure.core.rest import HttpRequest from azure.communication.phonenumbers._generated.operations._operations import ( -build_phone_numbers_get_search_result_request, +build_phone_numbers_get_search_result_request, build_phone_numbers_purchase_phone_numbers_request, build_phone_numbers_get_operation_request, -build_phone_numbers_cancel_operation_request +build_phone_numbers_cancel_operation_request, +build_phone_numbers_operator_information_search_request, ) test_id = "test_id" @@ -21,7 +22,7 @@ def test_build_phone_numbers_get_search_result_request(): assert isinstance(request, HttpRequest) assert request.method == "GET" assert test_id in request.url - assert "api-version=2022-12-01" in request.url + assert "api-version=2024-03-01-preview" in request.url assert request.headers["Accept"] == "application/json" def test_build_phone_numbers_purchase_phone_numbers_request(): @@ -46,4 +47,13 @@ def test_build_phone_numbers_cancel_operation_request(): assert isinstance(request, HttpRequest) assert request.method == "DELETE" assert test_id in request.url + assert request.headers["Accept"] == "application/json" + +def test_build_phone_numbers_operator_information_search_request(): + request = build_phone_numbers_operator_information_search_request() + + assert isinstance(request, HttpRequest) + assert request.method == "POST" + assert "api-version=2024-03-01-preview" in request.url + assert "operatorInformation/:search" in request.url assert request.headers["Accept"] == "application/json" \ No newline at end of file