Skip to content

Commit

Permalink
[SB] next-pylint (Azure#38860)
Browse files Browse the repository at this point in the history
* next-pylint

* pylint

* pylint2

* remove diff

* nit

* fix

* kashif

* mypy

* Update sdk/servicebus/azure-servicebus/azure/servicebus/_pyamqp/utils.py

Co-authored-by: Kashif Khan <[email protected]>

* Revert "Update sdk/servicebus/azure-servicebus/azure/servicebus/_pyamqp/utils.py"

This reverts commit 85b80d4.

* fix

* fix

---------

Co-authored-by: Kashif Khan <[email protected]>
  • Loading branch information
l0lawrence and kashifkhan authored Dec 17, 2024
1 parent 9b941a1 commit ae4f530
Show file tree
Hide file tree
Showing 38 changed files with 166 additions and 178 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from .exceptions import ServiceBusError

try:
# pylint:disable=unused-import
from uamqp import AMQPClient as uamqp_AMQPClientSync
except ImportError:
pass
Expand Down Expand Up @@ -372,7 +371,6 @@ def _check_live(self):
def _do_retryable_operation( # pylint: disable=inconsistent-return-statements
self, operation: Callable, timeout: Optional[float] = None, **kwargs: Any
) -> Any:
# pylint: disable=protected-access
require_last_exception = kwargs.pop("require_last_exception", False)
operation_requires_timeout = kwargs.pop("operation_requires_timeout", False)
retried_times = 0
Expand Down Expand Up @@ -435,7 +433,7 @@ def _backoff(
)
if backoff <= self._config.retry_backoff_max and (
abs_timeout_time is None or (backoff + time.time()) <= abs_timeout_time
): # pylint:disable=no-else-return
):
time.sleep(backoff)
_LOGGER.info(
"%r has an exception (%r). Retrying...",
Expand Down Expand Up @@ -517,7 +515,7 @@ def _mgmt_request_response(
timeout=timeout,
callback=callback,
)
except Exception as exp: # pylint: disable=broad-except
except Exception as exp:
if isinstance(exp, self._amqp_transport.TIMEOUT_ERROR):
raise OperationTimeoutError(error=exp) from exp
raise
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@

if TYPE_CHECKING:
try:
# pylint:disable=unused-import
from uamqp import Message, BatchMessage
except ImportError:
pass
Expand All @@ -59,7 +58,7 @@
PrimitiveTypes = Union[int, float, bytes, bool, str, uuid.UUID]


class ServiceBusMessage(object): # pylint: disable=too-many-public-methods,too-many-instance-attributes
class ServiceBusMessage(object): # pylint: disable=too-many-instance-attributes
"""A Service Bus Message.
:param body: The data to send in a single message.
Expand Down Expand Up @@ -671,7 +670,7 @@ def _add(self, add_message: Union[ServiceBusMessage, Mapping[str, Any], AmqpAnno
raise MessageSizeExceededError(
message=f"ServiceBusMessageBatch has reached its size limit: {self.max_size_in_bytes}"
)
self._amqp_transport.add_batch(self, outgoing_sb_message) # pylint: disable=protected-access
self._amqp_transport.add_batch(self, outgoing_sb_message)
self._size = size_after_add
self._count += 1
self._messages.append(outgoing_sb_message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def default(status_code, message, description, amqp_transport): # pylint: disab
if status_code == 200:
return message.value

amqp_transport.handle_amqp_mgmt_error( # pylint: disable=protected-access
amqp_transport.handle_amqp_mgmt_error(
_LOGGER, "Service request failed.", condition, description, status_code
)

Expand All @@ -29,7 +29,7 @@ def session_lock_renew_op( # pylint: disable=inconsistent-return-statements
if status_code == 200:
return message.value

amqp_transport.handle_amqp_mgmt_error( # pylint: disable=protected-access
amqp_transport.handle_amqp_mgmt_error(
_LOGGER, "Session lock renew failed.", condition, description, status_code
)

Expand All @@ -42,7 +42,7 @@ def message_lock_renew_op( # pylint: disable=inconsistent-return-statements
# TODO: will this always be body type ValueType?
return message.value

amqp_transport.handle_amqp_mgmt_error( # pylint: disable=protected-access
amqp_transport.handle_amqp_mgmt_error(
_LOGGER, "Message lock renew failed.", condition, description, status_code
)

Expand All @@ -58,7 +58,7 @@ def peek_op( # pylint: disable=inconsistent-return-statements
if status_code in [202, 204]:
return []

amqp_transport.handle_amqp_mgmt_error( # pylint: disable=protected-access
amqp_transport.handle_amqp_mgmt_error(
_LOGGER, "Message peek failed.", condition, description, status_code
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,13 @@ def _populate_attributes(self, **kwargs):
)

def _get_source(self):
# pylint: disable=protected-access
if self._session:
session_filter = None if self._session_id == NEXT_AVAILABLE_SESSION else self._session_id
return self._amqp_transport.create_source(self._entity_uri, session_filter)
return self._entity_uri

def _check_message_alive(self, message, action):
# pylint: disable=no-member, protected-access
# pylint: disable=protected-access
if message._is_peeked_message:
raise ValueError(
f"The operation {action} is not supported for peeked messages."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

if TYPE_CHECKING:
try:
# pylint:disable=unused-import
from uamqp import Message as uamqp_Message
except ImportError:
uamqp_Message = None
Expand Down Expand Up @@ -229,7 +228,7 @@ def get_receive_links(messages: Union[ServiceBusReceivedMessage, Iterable[Servic

trace_messages = (
messages
if isinstance(messages, Iterable) # pylint:disable=isinstance-second-argument-not-valid-type
if isinstance(messages, Iterable)
else (messages,)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@

if TYPE_CHECKING:
try:
# pylint:disable=unused-import
from uamqp import types as uamqp_types
from uamqp.authentication import JWTTokenAuth as uamqp_JWTTokenAuth
except ImportError:
Expand Down Expand Up @@ -95,6 +94,9 @@ def create_properties(
:param str user_agent: If specified,
this will be added in front of the built-in user agent string.
:keyword amqp_transport: The AMQP transport type.
:paramtype amqp_transport: ~azure.servicebus._transport._base.AmqpTransport
:return: The properties to add to the connection.
:rtype: dict
"""
Expand Down Expand Up @@ -131,7 +133,6 @@ def get_renewable_start_time(renewable):


def get_renewable_lock_duration(renewable: Union["ServiceBusReceivedMessage", "BaseSession"]) -> datetime.timedelta:
# pylint: disable=protected-access
try:
return max(renewable.locked_until_utc - utc_now(), datetime.timedelta(seconds=0))
except AttributeError:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class Connection: # pylint:disable=too-many-instance-attributes
and 1 for transport type AmqpOverWebsocket.
"""

def __init__( # pylint:disable=too-many-locals,too-many-statements
def __init__( # pylint:disable=too-many-locals
self,
endpoint: str,
*,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: disable=redefined-builtin, import-error

import struct
import uuid
import logging
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,9 @@ def encode_map(
count = len(cast(Sized, value)) * 2
encoded_size = 0
encoded_values = bytearray()
items: Iterable[Any]
if isinstance(value, dict):
items: Iterable[Any] = value.items()
items = value.items()
elif isinstance(value, Iterable):
items = value

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

# pylint: disable=too-many-lines
from enum import Enum
from typing import (
Callable,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# ------------------------------------------------------------------------- # pylint: disable=file-needs-copyright-header
# ------------------------------------------------------------------------- # pylint: disable=file-needs-copyright-header,useless-suppression
# This is a fork of the transport.py which was originally written by Barry Pederson and
# maintained by the Celery project: https://github.com/celery/py-amqp.
#
Expand Down Expand Up @@ -746,7 +746,7 @@ def connect(self):
self.close()
raise

def _read(self, n, initial=False, buffer=None, _errnos=None): # pylint: disable=unused-argument
def _read(self, n, initial=False, buffer=None, _errnos=None):
"""Read exactly n bytes from the peer.
:param int n: The number of bytes to read.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ async def update_token(self) -> None:
if self._token and token_type:
await self._put_token(self._token, token_type, self._auth.audience, utc_from_timestamp(self._expires_on))

async def handle_token(self) -> bool: # pylint: disable=inconsistent-return-statements
async def handle_token(self) -> bool:
if not await self._cbs_link_ready():
return False
await self._update_status()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# ------------------------------------------------------------------------- # pylint: disable=client-suffix-needed
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# TODO: Check types of kwargs (issue exists for this)
# pylint: disable=too-many-lines
import asyncio
import logging
import time
Expand Down Expand Up @@ -499,7 +498,6 @@ async def _client_ready_async(self):
:return: Whether or not the client is ready to start sending messages.
:rtype: bool
"""
# pylint: disable=protected-access
if not self._link:
self._link = self._session.create_sender_link(
target_address=self.target,
Expand Down Expand Up @@ -708,7 +706,6 @@ async def _client_ready_async(self):
:return: Whether the client is ready to start receiving messages.
:rtype: bool
"""
# pylint: disable=protected-access
if not self._link:
self._link = self._session.create_receiver_link(
source_address=self.source,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class Connection: # pylint:disable=too-many-instance-attributes
and 1 for transport type AmqpOverWebsocket.
"""

def __init__( # pylint:disable=too-many-locals,too-many-statements
def __init__( # pylint:disable=too-many-locals
self,
endpoint: str,
*,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ async def execute(self, message, operation=None, operation_type=None, timeout: f

if self._mgmt_error:
self._responses.pop(operation_id)
raise self._mgmt_error # pylint: disable=raising-bad-type
raise self._mgmt_error

response = self._responses.pop(operation_id)
return response
Expand All @@ -105,7 +105,7 @@ async def open(self):

async def ready(self):
try:
raise self._mgmt_error # pylint: disable=raising-bad-type
raise self._mgmt_error
except TypeError:
pass

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def start(self):
return b""


class SASLTransportMixinAsync: # pylint: disable=no-member
class SASLTransportMixinAsync:
async def _negotiate(self):
await self.write(SASL_HEADER_FRAME)
_, returned_header = await self.receive_frame()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# ------------------------------------------------------------------------- # pylint: disable=file-needs-copyright-header
# ------------------------------------------------------------------------- # pylint: disable=file-needs-copyright-header,useless-suppression
# This is a fork of the transport.py which was originally written by Barry Pederson and
# maintained by the Celery project: https://github.com/celery/py-amqp.
#
Expand Down Expand Up @@ -217,7 +217,7 @@ def __init__(
socket_settings=None,
raise_on_initial_eintr=True,
use_tls: bool = True,
**kwargs, # pylint: disable=unused-argument
**kwargs,
):
self.connected = False
self.sock = None
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# ------------------------------------------------------------------------- # pylint: disable=client-suffix-needed
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
Expand Down Expand Up @@ -590,7 +590,6 @@ def _client_ready(self):
:return: Whether the client is ready to start receiving messages.
:rtype: bool
"""
# pylint: disable=protected-access
if not self._link:
self._link = self._session.create_sender_link(
target_address=self.target,
Expand Down Expand Up @@ -826,7 +825,6 @@ def _client_ready(self):
:return: True if the client is ready to start receiving messages.
:rtype: bool
"""
# pylint: disable=protected-access
if not self._link:
self._link = self._session.create_receiver_link(
source_address=self.source,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def execute(self, message, operation=None, operation_type=None, timeout=0):

if self._mgmt_error:
self._responses.pop(operation_id)
raise self._mgmt_error # pylint: disable=raising-bad-type
raise self._mgmt_error

response = self._responses.pop(operation_id)
return response
Expand All @@ -105,7 +105,7 @@ def open(self):

def ready(self):
try:
raise self._mgmt_error # pylint: disable=raising-bad-type
raise self._mgmt_error
except TypeError:
pass

Expand Down
41 changes: 2 additions & 39 deletions sdk/servicebus/azure-servicebus/azure/servicebus/_pyamqp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,48 +9,11 @@
from hmac import HMAC
from urllib.parse import urlencode, quote_plus
import time

from datetime import timezone
from .types import TYPE, VALUE, AMQPTypes
from ._encode import encode_payload


class UTC(datetime.tzinfo):
"""Time Zone info for handling UTC"""

def utcoffset(self, dt):
"""UTF offset for UTC is 0.
:param datetime.datetime dt: Ignored.
:return: The UTC offset of UTC
:rtype: datetime.timedelta
"""
return datetime.timedelta(0)

def tzname(self, dt):
"""Timestamp representation.
:param datetime.datetime dt: Ignored.
:return: The timestamp representation of UTC
:rtype: str
"""
return "Z"

def dst(self, dt):
"""No daylight saving for UTC.
:param datetime.datetime dt: Ignored.
:return: The daylight saving time of UTC
:rtype: datetime.timedelta
"""
return datetime.timedelta(hours=1)


try:
from datetime import timezone # pylint: disable=ungrouped-imports

TZ_UTC = timezone.utc # type: ignore
except ImportError:
TZ_UTC = UTC() # type: ignore
TZ_UTC: timezone = timezone.utc


def utc_from_timestamp(timestamp):
Expand Down
Loading

0 comments on commit ae4f530

Please sign in to comment.