Skip to content

Commit 1032b65

Browse files
Improve exception handlers []
1 parent 68cbd6a commit 1032b65

5 files changed

Lines changed: 112 additions & 12 deletions

File tree

‎dev_tools/bin/edgy‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,7 @@ def _diagnose_bad_expectations_file(file_path: Path) -> None:
648648
line_ctr += 1
649649
try:
650650
parse_test_status(line_text)
651-
except:
651+
except Exception:
652652
if len(line_text) != 0:
653653
edgutil.eprint(
654654
f"{file_path_str}, line {line_ctr}: "
@@ -689,7 +689,7 @@ def _construct_replay_filters(
689689
)
690690
for key in comparison:
691691
desired_tests.add(parsed_test_status_key_to_name(key))
692-
except:
692+
except Exception:
693693
edgutil.eprint(
694694
f"Failed to compare the previous run of the {test_suite.name} "
695695
'suite to its expectations.'
@@ -712,7 +712,7 @@ def _construct_replay_filters(
712712
elif (args.replay == 'output-mismatch' and
713713
parsed_test_status.is_output_mismatch()):
714714
desired_tests.add(parsed_test_status_key_to_name(key))
715-
except:
715+
except Exception:
716716
edgutil.eprint(
717717
f"Failed to parse test statuses in previous run of {test_suite.name}."
718718
)
@@ -1254,7 +1254,7 @@ class TestStatusChecker:
12541254
encountered_lines: List[str]) -> Optional['TestStatusChecker']:
12551255
try:
12561256
return TestStatusChecker(expected_lines, encountered_lines)
1257-
except:
1257+
except Exception:
12581258
return None
12591259

12601260
def _get_status_for_comparison(

‎dev_tools/bin/ifc-qt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ class PartitionNodeFormatter:
383383
values.append(template_string.format(value.description))
384384
else:
385385
values.append(format_fn(value))
386-
except:
386+
except Exception:
387387
traceback.print_exc()
388388
values.append(edgifc.decoration.UNKNOWN_VALUE)
389389

@@ -428,7 +428,7 @@ class PartitionNodeFormatter:
428428
stream_reader,
429429
tacit_field.name()
430430
)
431-
except:
431+
except Exception:
432432
traceback.print_exc()
433433
field_value = 0
434434

‎dev_tools/pylibs/edgacknowledg/client/__init__.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,8 @@ async def add_section(self, handler: ReviewClientHandler) -> None:
500500
await self.subscribe_section(handler)
501501
except NotConnectedError:
502502
pass
503-
except Exception:
503+
except BaseException:
504+
# Failed or cancelled: not added.
504505
self._review.discard_handler(handler)
505506
raise
506507

@@ -676,7 +677,8 @@ async def add_section(self, handler: ReviewClientHandler) -> None:
676677
self._review.register_handler(handler)
677678
try:
678679
await self.subscribe_section(handler)
679-
except Exception:
680+
except BaseException:
681+
# Failed or cancelled: not added.
680682
self._review.discard_handler(handler)
681683
raise
682684

@@ -1096,7 +1098,8 @@ async def _subscribe(self, payload: Dict[str, Any]) -> uuid.UUID:
10961098
SUBSCRIBE_TIMEOUT_S,
10971099
f"subscribe {key[1]}/{key[2]}"
10981100
)
1099-
except Exception:
1101+
except BaseException:
1102+
# Failed or cancelled: no longer awaited.
11001103
self._pending_subscribe.pop(key, None)
11011104
if not future.done():
11021105
future.cancel()
@@ -1118,7 +1121,8 @@ async def _unsubscribe(self, subscription_id: uuid.UUID) -> None:
11181121
UNSUBSCRIBE_TIMEOUT_S,
11191122
f"unsubscribe {subscription_id}"
11201123
)
1121-
except Exception:
1124+
except BaseException:
1125+
# Failed or cancelled: no longer awaited.
11221126
self._pending_unsubscribe.pop(subscription_id, None)
11231127
if not future.done():
11241128
future.cancel()

‎dev_tools/pylibs/edgifc/decoration/__init__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def name(self):
111111
def decorate(self, ifc_reader, value):
112112
try:
113113
return ifc_reader.get_decomposed_index_sort(self.sort_name, value)[0]
114-
except:
114+
except Exception:
115115
sort, _ = ifc_reader.get_decomposed_index_sort_values(
116116
self.sort_name, value
117117
)
@@ -127,7 +127,7 @@ def name(self):
127127
def decorate(self, ifc_reader, value):
128128
try:
129129
return ifc_reader.get_decomposed_index_sort(self.sort_name, value)[1]
130-
except:
130+
except Exception:
131131
_, idx = ifc_reader.get_decomposed_index_sort_values(
132132
self.sort_name, value
133133
)
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Part of the EDG Compiler Project, under the Apache License v2.0 with LLVM
2+
# Exceptions.
3+
# See https://edgcpp.org/LICENSE.txt for license information.
4+
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5+
6+
'''Cancelling AcknowlEDG client requests undoes them, as failing does.'''
7+
8+
import asyncio
9+
import uuid
10+
11+
from typing import Any
12+
13+
from edgacknowledg.client import (
14+
BatchClientSession,
15+
_BatchClientReview,
16+
_DirectClientReview,
17+
)
18+
19+
20+
class _Unanswered:
21+
'''A batch connection the server never answers on.'''
22+
23+
def __init__(self) -> None:
24+
self.sent: list[Any] = []
25+
26+
async def send(self, data: Any) -> None:
27+
self.sent.append(data)
28+
29+
30+
class _Handler:
31+
subscription_type = 'test.src'
32+
slug = 'test-changes'
33+
34+
35+
def _session() -> BatchClientSession:
36+
session = BatchClientSession(
37+
status_listener = None,
38+
api_host = '127.0.0.1',
39+
api_port = 1,
40+
api_key = None,
41+
open_timeout = None
42+
)
43+
session._connection = _Unanswered() # type: ignore[assignment]
44+
session._session_ready.set()
45+
return session
46+
47+
48+
async def _cancel_once_sent(session: BatchClientSession,
49+
request: 'asyncio.Task[Any]') -> None:
50+
connection = session._connection
51+
assert isinstance(connection, _Unanswered)
52+
while len(connection.sent) == 0:
53+
await asyncio.sleep(0.01)
54+
request.cancel()
55+
await asyncio.gather(request, return_exceptions = True)
56+
assert request.cancelled()
57+
58+
59+
async def test_cancelled_subscribes_are_not_awaited() -> None:
60+
session = _session()
61+
subscribing = asyncio.create_task(session._subscribe({
62+
'id': str(uuid.uuid4()), 'type': 'test.src', 'slug': 'test-changes',
63+
}))
64+
await _cancel_once_sent(session, subscribing)
65+
assert session._pending_subscribe == {}
66+
67+
unsubscribing = asyncio.create_task(session._unsubscribe(uuid.uuid4()))
68+
session._connection = _Unanswered() # type: ignore[assignment]
69+
await _cancel_once_sent(session, unsubscribing)
70+
assert session._pending_unsubscribe == {}
71+
72+
73+
async def test_cancelled_batch_sections_are_not_added() -> None:
74+
session = _session()
75+
review = _BatchClientReview(session, uuid.uuid4(), [], '')
76+
adding = asyncio.create_task(review.add_section(_Handler())) # type: ignore
77+
await _cancel_once_sent(session, adding)
78+
# Not left to be subscribed on reconnecting.
79+
assert review.sections() == []
80+
assert session._pending_subscribe == {}
81+
82+
83+
async def test_cancelled_direct_sections_are_not_added() -> None:
84+
review = _DirectClientReview(None, uuid.uuid4(), [], '') # type: ignore
85+
subscribing = asyncio.Event()
86+
87+
async def subscribe_section(handler: Any) -> None:
88+
subscribing.set()
89+
await asyncio.Event().wait()
90+
91+
review.subscribe_section = subscribe_section # type: ignore[method-assign]
92+
adding = asyncio.create_task(review.add_section(_Handler())) # type: ignore
93+
await subscribing.wait()
94+
adding.cancel()
95+
await asyncio.gather(adding, return_exceptions = True)
96+
assert review.sections() == []

0 commit comments

Comments
 (0)