Skip to content

Commit 91de6c7

Browse files
authored
[Service Bus] Enable pylint and mypy (#11316)
1 parent dc99329 commit 91de6c7

27 files changed

+321
-297
lines changed

eng/tox/allowed_pylint_failures.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
"azure-eventgrid",
4040
"azure-graphrbac",
4141
"azure-loganalytics",
42-
"azure-servicebus",
4342
"azure-servicefabric",
4443
"azure-template",
4544
"azure-keyvault",

eng/tox/mypy_hard_failure_packages.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
MYPY_HARD_FAILURE_OPTED = [
99
"azure-core",
1010
"azure-eventhub",
11+
"azure-servicebus",
1112
"azure-ai-textanalytics",
1213
"azure-ai-formrecognizer"
1314
]
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore

sdk/servicebus/azure-servicebus/azure/servicebus/_base_handler.py

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import uuid
88
import time
99
from datetime import timedelta
10-
from typing import cast, Optional, Tuple, TYPE_CHECKING, Dict, Any
10+
from typing import cast, Optional, Tuple, TYPE_CHECKING, Dict, Any, Callable, Type
1111

1212
try:
1313
from urllib import quote_plus # type: ignore
@@ -90,6 +90,31 @@ def _generate_sas_token(uri, policy, key, expiry=None):
9090
return _AccessToken(token=token, expires_on=abs_expiry)
9191

9292

93+
def _convert_connection_string_to_kwargs(conn_str, shared_key_credential_type, **kwargs):
94+
# type: (str, Type, Any) -> Dict[str, Any]
95+
host, policy, key, entity_in_conn_str = _parse_conn_str(conn_str)
96+
queue_name = kwargs.get("queue_name")
97+
topic_name = kwargs.get("topic_name")
98+
if not (queue_name or topic_name or entity_in_conn_str):
99+
raise ValueError("Entity name is missing. Please specify `queue_name` or `topic_name`"
100+
" or use a connection string including the entity information.")
101+
102+
if queue_name and topic_name:
103+
raise ValueError("`queue_name` and `topic_name` can not be specified simultaneously.")
104+
105+
entity_in_kwargs = queue_name or topic_name
106+
if entity_in_conn_str and entity_in_kwargs and (entity_in_conn_str != entity_in_kwargs):
107+
raise ServiceBusAuthorizationError(
108+
"Entity names do not match, the entity name in connection string is {};"
109+
" the entity name in parameter is {}.".format(entity_in_conn_str, entity_in_kwargs)
110+
)
111+
112+
kwargs["fully_qualified_namespace"] = host
113+
kwargs["entity_name"] = entity_in_conn_str or entity_in_kwargs
114+
kwargs["credential"] = shared_key_credential_type(policy, key)
115+
return kwargs
116+
117+
93118
class ServiceBusSharedKeyCredential(object):
94119
"""The shared access key credential used for authentication.
95120
@@ -110,14 +135,15 @@ def get_token(self, *scopes, **kwargs): # pylint:disable=unused-argument
110135
return _generate_sas_token(scopes[0], self.policy, self.key)
111136

112137

113-
class BaseHandler(object): # pylint:disable=too-many-instance-attributes
138+
class BaseHandler: # pylint:disable=too-many-instance-attributes
114139
def __init__(
115140
self,
116141
fully_qualified_namespace,
117142
entity_name,
118143
credential,
119144
**kwargs
120145
):
146+
# type: (str, str, TokenCredential, Any) -> None
121147
self.fully_qualified_namespace = fully_qualified_namespace
122148
self._entity_name = entity_name
123149

@@ -128,7 +154,7 @@ def __init__(
128154
self._container_id = CONTAINER_PREFIX + str(uuid.uuid4())[:8]
129155
self._config = Configuration(**kwargs)
130156
self._running = False
131-
self._handler = None
157+
self._handler = None # type: uamqp.AMQPClient
132158
self._auth_uri = None
133159
self._properties = create_properties()
134160

@@ -140,6 +166,7 @@ def __exit__(self, *args):
140166
self.close()
141167

142168
def _handle_exception(self, exception):
169+
# type: (BaseException) -> ServiceBusError
143170
error, error_need_close_handler, error_need_raise = _create_servicebus_exception(_LOGGER, exception, self)
144171
if error_need_close_handler:
145172
self._close_handler()
@@ -148,38 +175,14 @@ def _handle_exception(self, exception):
148175

149176
return error
150177

151-
@staticmethod
152-
def _from_connection_string(conn_str, **kwargs):
153-
# type: (str, Any) -> Dict[str, Any]
154-
host, policy, key, entity_in_conn_str = _parse_conn_str(conn_str)
155-
queue_name = kwargs.get("queue_name")
156-
topic_name = kwargs.get("topic_name")
157-
if not (queue_name or topic_name or entity_in_conn_str):
158-
raise ValueError("Entity name is missing. Please specify `queue_name` or `topic_name`"
159-
" or use a connection string including the entity information.")
160-
161-
if queue_name and topic_name:
162-
raise ValueError("`queue_name` and `topic_name` can not be specified simultaneously.")
163-
164-
entity_in_kwargs = queue_name or topic_name
165-
if entity_in_conn_str and entity_in_kwargs and (entity_in_conn_str != entity_in_kwargs):
166-
raise ServiceBusAuthorizationError(
167-
"Entity names do not match, the entity name in connection string is {};"
168-
" the entity name in parameter is {}.".format(entity_in_conn_str, entity_in_kwargs)
169-
)
170-
171-
kwargs["fully_qualified_namespace"] = host
172-
kwargs["entity_name"] = entity_in_conn_str or entity_in_kwargs
173-
kwargs["credential"] = ServiceBusSharedKeyCredential(policy, key)
174-
return kwargs
175-
176178
def _backoff(
177179
self,
178180
retried_times,
179181
last_exception,
180182
timeout=None,
181183
entity_name=None
182184
):
185+
# type: (int, Exception, Optional[float], str) -> None
183186
entity_name = entity_name or self._container_id
184187
backoff = self._config.retry_backoff_factor * 2 ** retried_times
185188
if backoff <= self._config.retry_backoff_max and (
@@ -200,40 +203,39 @@ def _backoff(
200203
raise last_exception
201204

202205
def _do_retryable_operation(self, operation, timeout=None, **kwargs):
206+
# type: (Callable, Optional[float], Any) -> Any
203207
require_last_exception = kwargs.pop("require_last_exception", False)
204208
require_timeout = kwargs.pop("require_timeout", False)
205209
retried_times = 0
206-
last_exception = None
207210
max_retries = self._config.retry_total
208211

209212
while retried_times <= max_retries:
210213
try:
211-
if require_last_exception:
212-
kwargs["last_exception"] = last_exception
213214
if require_timeout:
214215
kwargs["timeout"] = timeout
215216
return operation(**kwargs)
216217
except StopIteration:
217218
raise
218219
except Exception as exception: # pylint: disable=broad-except
219220
last_exception = self._handle_exception(exception)
221+
if require_last_exception:
222+
kwargs["last_exception"] = last_exception
220223
retried_times += 1
221224
if retried_times > max_retries:
222-
break
225+
_LOGGER.info(
226+
"%r operation has exhausted retry. Last exception: %r.",
227+
self._container_id,
228+
last_exception,
229+
)
230+
raise last_exception
223231
self._backoff(
224232
retried_times=retried_times,
225233
last_exception=last_exception,
226234
timeout=timeout
227235
)
228236

229-
_LOGGER.info(
230-
"%r operation has exhausted retry. Last exception: %r.",
231-
self._container_id,
232-
last_exception,
233-
)
234-
raise last_exception
235-
236237
def _mgmt_request_response(self, mgmt_operation, message, callback, keep_alive_associated_link=True, **kwargs):
238+
# type: (str, uamqp.Message, Callable, bool, Any) -> uamqp.Message
237239
self._open()
238240
application_properties = {}
239241
# Some mgmt calls do not support an associated link name (such as list_sessions). Most do, so on by default.
@@ -265,6 +267,7 @@ def _mgmt_request_response(self, mgmt_operation, message, callback, keep_alive_a
265267
raise ServiceBusError("Management request failed: {}".format(exp), exp)
266268

267269
def _mgmt_request_response_with_retry(self, mgmt_operation, message, callback, **kwargs):
270+
# type: (bytes, Dict[str, Any], Callable, Any) -> Any
268271
return self._do_retryable_operation(
269272
self._mgmt_request_response,
270273
mgmt_operation=mgmt_operation,

sdk/servicebus/azure-servicebus/azure/servicebus/_common/client_mixins.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
import uuid
99
import requests
1010
try:
11-
from urlparse import urlparse
12-
from urllib import unquote_plus
11+
from urlparse import urlparse # type: ignore
12+
from urllib import unquote_plus # type: ignore
1313
except ImportError:
1414
from urllib.parse import urlparse
1515
from urllib.parse import unquote_plus

0 commit comments

Comments
 (0)