Skip to content

Commit 8559eb9

Browse files
author
Erik Cederstrand
committed
chore: Fix some Deepsource suggestions
1 parent c74b153 commit 8559eb9

File tree

13 files changed

+58
-78
lines changed

13 files changed

+58
-78
lines changed

exchangelib/autodiscover/cache.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,8 @@ def __delitem__(self, key):
116116
# Empty both local and persistent cache. Don't fail on non-existing entries because we could end here
117117
# multiple times due to race conditions.
118118
domain = key[0]
119-
with shelve_open_with_failover(self._storage_file) as db:
120-
with suppress(KeyError):
121-
del db[str(domain)]
119+
with shelve_open_with_failover(self._storage_file) as db, suppress(KeyError):
120+
del db[str(domain)]
122121
with suppress(KeyError):
123122
del self._protocols[key]
124123

exchangelib/credentials.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,8 @@ def session_params(self):
166166
)
167167
return res
168168

169-
def token_params(self):
169+
@staticmethod
170+
def token_params():
170171
"""Extra parameters when requesting the token"""
171172
return {"include_client_id": True}
172173

exchangelib/fields.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,6 @@ def __init__(
293293
is_searchable=True,
294294
is_attribute=False,
295295
default=None,
296-
*args,
297296
**kwargs,
298297
):
299298
self.name = name # Usually set by the EWSMeta metaclass
@@ -310,7 +309,7 @@ def __init__(
310309
self.is_searchable = is_searchable
311310
# When true, this field is treated as an XML attribute instead of an element
312311
self.is_attribute = is_attribute
313-
super().__init__(*args, **kwargs)
312+
super().__init__(**kwargs)
314313

315314
def clean(self, value, version=None):
316315
if version and not self.supports_version(version):

exchangelib/folders/collections.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def exclude(self, *args, **kwargs):
9191
def people(self):
9292
return QuerySet(self).people()
9393

94-
def view(self, start, end, max_items=None, *args, **kwargs):
94+
def view(self, start, end, max_items=None):
9595
"""Implement the CalendarView option to FindItem. The difference between 'filter' and 'view' is that 'filter'
9696
only returns the master CalendarItem for recurring items, while 'view' unfolds recurring items and returns all
9797
CalendarItem occurrences as one would normally expect when presenting a calendar.
@@ -109,7 +109,7 @@ def view(self, start, end, max_items=None, *args, **kwargs):
109109
:param max_items: (Default value = None)
110110
:return:
111111
"""
112-
qs = QuerySet(self).filter(*args, **kwargs)
112+
qs = QuerySet(self)
113113
qs.calendar_view = CalendarView(start=start, end=end, max_items=max_items)
114114
return qs
115115

exchangelib/services/common.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ def _elems_to_objs(self, elems):
221221
yield self._elem_to_obj(elem)
222222

223223
def _elem_to_obj(self, elem):
224+
"""Convert a single XML element to a single Python object"""
224225
if not self.returns_elements:
225226
raise RuntimeError("Incorrect call to method when 'returns_elements' is False")
226227
raise NotImplementedError()
@@ -335,7 +336,7 @@ def _get_elements(self, payload):
335336
self.stop_streaming()
336337

337338
def _handle_response_cookies(self, session):
338-
pass
339+
"""Code to react on response cookies"""
339340

340341
def _get_response(self, payload, api_version):
341342
"""Send the actual HTTP request and get the response."""
@@ -375,13 +376,13 @@ def _api_versions_to_try(self):
375376
v for v in self.supported_api_versions() if v != self._version_hint.api_version
376377
)
377378

378-
def _get_response_xml(self, payload, **parse_opts):
379+
def _get_response_xml(self, payload):
379380
"""Send the payload to the server and return relevant elements from the result. Several things happen here:
380-
* The payload is wrapped in SOAP headers and sent to the server
381-
* The Exchange API version is negotiated and stored in the protocol object
382-
* Connection errors are handled and possibly reraised as ErrorServerBusy
383-
* SOAP errors are raised
384-
* EWS errors are raised, or passed on to the caller
381+
* Wraps the payload is wrapped in SOAP headers and sends to the server
382+
* Negotiates the Exchange API version and stores it in the protocol object
383+
* Handles connection errors and possibly re-raises them as ErrorServerBusy
384+
* Raises SOAP errors
385+
* Raises EWS errors or passes them on to the caller
385386
386387
:param payload: The request payload, as an XML object
387388
:return: A generator of XML objects or None if the service does not return a result
@@ -397,15 +398,15 @@ def _get_response_xml(self, payload, **parse_opts):
397398
# Let 'requests' decode raw data automatically
398399
r.raw.decode_content = True
399400
try:
400-
header, body = self._get_soap_parts(response=r, **parse_opts)
401+
header, body = self._get_soap_parts(response=r)
401402
except Exception:
402403
r.close() # Release memory
403404
raise
404405
# The body may contain error messages from Exchange, but we still want to collect version info
405406
if header is not None:
406-
self._update_api_version(api_version=api_version, header=header, **parse_opts)
407+
self._update_api_version(api_version=api_version, header=header)
407408
try:
408-
return self._get_soap_messages(body=body, **parse_opts)
409+
return self._get_soap_messages(body=body)
409410
except (
410411
ErrorInvalidServerVersion,
411412
ErrorIncorrectSchemaVersion,
@@ -438,7 +439,7 @@ def _handle_backoff(self, e):
438439
self.protocol.retry_policy.back_off(e.back_off)
439440
# We'll warn about this later if we actually need to sleep
440441

441-
def _update_api_version(self, api_version, header, **parse_opts):
442+
def _update_api_version(self, api_version, header):
442443
"""Parse the server version contained in SOAP headers and update the version hint stored by the caller, if
443444
necessary.
444445
"""
@@ -471,7 +472,7 @@ def _response_message_tag(cls):
471472
return f"{{{MNS}}}{cls.SERVICE_NAME}ResponseMessage"
472473

473474
@classmethod
474-
def _get_soap_parts(cls, response, **parse_opts):
475+
def _get_soap_parts(cls, response):
475476
"""Split the SOAP response into its headers and body elements."""
476477
try:
477478
root = to_xml(response.iter_content())
@@ -486,7 +487,7 @@ def _get_soap_parts(cls, response, **parse_opts):
486487
raise MalformedResponseError("No Body element in SOAP response")
487488
return header, body
488489

489-
def _get_soap_messages(self, body, **parse_opts):
490+
def _get_soap_messages(self, body):
490491
"""Return the elements in the response containing the response messages. Raises any SOAP exceptions."""
491492
response = body.find(self._response_tag())
492493
if response is None:

exchangelib/services/get_attachment.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -65,23 +65,20 @@ def get_payload(self, items, include_mime_content, body_type, filter_html_conten
6565
payload.append(attachment_ids_element(items=items, version=self.account.version))
6666
return payload
6767

68-
def _update_api_version(self, api_version, header, **parse_opts):
69-
if not parse_opts.get("stream_file_content", False):
70-
super()._update_api_version(api_version, header, **parse_opts)
68+
def _update_api_version(self, api_version, header):
69+
if not self.streaming:
70+
super()._update_api_version(api_version, header)
7171
# TODO: We're skipping this part in streaming mode because StreamingBase64Parser cannot parse the SOAP header
7272

73-
@classmethod
74-
def _get_soap_parts(cls, response, **parse_opts):
75-
if not parse_opts.get("stream_file_content", False):
76-
return super()._get_soap_parts(response, **parse_opts)
77-
73+
def _get_soap_parts(self, response):
74+
if not self.streaming:
75+
return super()._get_soap_parts(response)
7876
# Pass the response unaltered. We want to use our custom streaming parser
7977
return None, response
8078

81-
def _get_soap_messages(self, body, **parse_opts):
82-
if not parse_opts.get("stream_file_content", False):
83-
return super()._get_soap_messages(body, **parse_opts)
84-
79+
def _get_soap_messages(self, body):
80+
if not self.streaming:
81+
return super()._get_soap_messages(body)
8582
# 'body' is actually the raw response passed on by '_get_soap_parts'
8683
r = body
8784
parser = StreamingBase64Parser()
@@ -101,13 +98,14 @@ def stream_file_content(self, attachment_id):
10198
)
10299
self.streaming = True
103100
try:
104-
yield from self._get_response_xml(payload=payload, stream_file_content=True)
101+
yield from self._get_response_xml(payload=payload)
105102
except ElementNotFound as enf:
106103
# When the returned XML does not contain a Content element, ElementNotFound is thrown by parser.parse().
107104
# Let the non-streaming SOAP parser parse the response and hook into the normal exception handling.
108105
# Wrap in DummyResponse because _get_soap_parts() expects an iter_content() method.
109106
response = DummyResponse(content=enf.data)
110107
_, body = super()._get_soap_parts(response=response)
108+
# TODO: We're skipping ._update_api_version() here because we don't have access to the 'api_version' used.
111109
res = super()._get_soap_messages(body=body)
112110
for e in self._get_elements_in_response(response=res):
113111
if isinstance(e, Exception):

exchangelib/services/get_streaming_events.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@ def _elem_to_obj(self, elem):
4848
return Notification.from_xml(elem=elem, account=None)
4949

5050
@classmethod
51-
def _get_soap_parts(cls, response, **parse_opts):
51+
def _get_soap_parts(cls, response):
5252
# Pass the response unaltered. We want to use our custom document yielder
5353
return None, response
5454

55-
def _get_soap_messages(self, body, **parse_opts):
55+
def _get_soap_messages(self, body):
5656
# 'body' is actually the raw response passed on by '_get_soap_parts'. We want to continuously read the content,
5757
# looking for complete XML documents. When we have a full document, we want to parse it as if it was a normal
5858
# XML response.
@@ -61,13 +61,13 @@ def _get_soap_messages(self, body, **parse_opts):
6161
xml_log.debug("Response XML (docs counter: %(i)s): %(xml_response)s", dict(i=i, xml_response=doc))
6262
response = DummyResponse(content=doc)
6363
try:
64-
_, body = super()._get_soap_parts(response=response, **parse_opts)
64+
_, body = super()._get_soap_parts(response=response)
6565
except Exception:
6666
r.close() # Release memory
6767
raise
6868
# TODO: We're skipping ._update_api_version() here because we don't have access to the 'api_version' used.
6969
# TODO: We should be doing a lot of error handling for ._get_soap_messages().
70-
yield from super()._get_soap_messages(body=body, **parse_opts)
70+
yield from super()._get_soap_messages(body=body)
7171
if self.connection_status == self.CLOSED:
7272
# Don't wait for the TCP connection to timeout
7373
break
@@ -97,9 +97,6 @@ def get_payload(self, subscription_ids, connection_timeout):
9797
subscriptions_elem = create_element("m:SubscriptionIds")
9898
for subscription_id in subscription_ids:
9999
add_xml_child(subscriptions_elem, "t:SubscriptionId", subscription_id)
100-
if not len(subscriptions_elem):
101-
raise ValueError("'subscription_ids' must not be empty")
102-
103100
payload.append(subscriptions_elem)
104101
add_xml_child(payload, "m:ConnectionTimeout", connection_timeout)
105102
return payload

exchangelib/services/get_user_settings.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,10 @@ def get_payload(self, users, settings):
5353
mailbox = create_element("a:Mailbox")
5454
set_xml_value(mailbox, user)
5555
add_xml_child(users_elem, "a:User", mailbox)
56-
if not len(users_elem):
57-
raise ValueError("'users' must not be empty")
5856
request.append(users_elem)
5957
requested_settings = create_element("a:RequestedSettings")
6058
for setting in settings:
6159
add_xml_child(requested_settings, "a:Setting", UserResponse.SETTINGS_MAP[setting])
62-
if not len(requested_settings):
63-
raise ValueError("'requested_settings' must not be empty")
6460
request.append(requested_settings)
6561
payload.append(request)
6662
return payload

exchangelib/services/subscribe.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,6 @@ def _partial_payload(self, folders, event_types):
5151
event_types_elem = create_element("t:EventTypes")
5252
for event_type in event_types:
5353
add_xml_child(event_types_elem, "t:EventType", event_type)
54-
if not len(event_types_elem):
55-
raise ValueError("'event_types' must not be empty")
5654
request_elem.append(event_types_elem)
5755
return request_elem
5856

exchangelib/util.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -422,10 +422,8 @@ def tell(self):
422422
return self._tell
423423

424424
def read(self, size=-1):
425-
# requests `iter_content()` auto-adjusts the number of bytes based on bandwidth
426-
# can't assume how many bytes next returns so stash any extra in `self._next`
427-
if self.closed:
428-
raise ValueError("read from a closed file")
425+
# requests `iter_content()` auto-adjusts the number of bytes based on bandwidth.
426+
# We can't assume how many bytes next returns so stash any extra in `self._next`.
429427
if self._next is None:
430428
return b""
431429
if size is None:
@@ -534,10 +532,9 @@ def to_xml(bytes_content):
534532
offending_line = stream.read().splitlines()[e.lineno - 1]
535533
except (IndexError, io.UnsupportedOperation):
536534
raise ParseError(str(e), "<not from file>", e.lineno, e.offset)
537-
else:
538-
offending_excerpt = offending_line[max(0, e.offset - 20) : e.offset + 20]
539-
msg = f'{e}\nOffending text: [...]{offending_excerpt.decode("utf-8", errors="ignore")}[...]'
540-
raise ParseError(msg, "<not from file>", e.lineno, e.offset)
535+
offending_excerpt = offending_line[max(0, e.offset - 20) : e.offset + 20]
536+
msg = f'{e}\nOffending text: [...]{offending_excerpt.decode("utf-8", errors="ignore")}[...]'
537+
raise ParseError(msg, "<not from file>", e.lineno, e.offset)
541538
except TypeError:
542539
with suppress(IndexError, io.UnsupportedOperation):
543540
stream.seek(0)
@@ -576,7 +573,8 @@ def is_xml(text):
576573
class PrettyXmlHandler(logging.StreamHandler):
577574
"""A steaming log handler that prettifies log statements containing XML when output is a terminal."""
578575

579-
def parse_bytes(self, xml_bytes):
576+
@staticmethod
577+
def parse_bytes(xml_bytes):
580578
return to_xml(xml_bytes)
581579

582580
def prettify_xml(self, xml_bytes):
@@ -671,7 +669,7 @@ def iter_content(self):
671669
return self.content
672670

673671
def close(self):
674-
pass
672+
"""We don't have an actual socket to close"""
675673

676674

677675
def get_domain(email):

0 commit comments

Comments
 (0)