Skip to content

Commit 163a0da

Browse files
committed
refactor: improve exception handling and type hints across modules
- Simplified exception handling in `bridge.py`, `connection.py`, and `suite_leasing.py`. - Updated type hints in `suite_leasing.py` for better clarity. - Refactored `find_revit_path` in `discovery.py` to use `Path` for file existence checks. - Enhanced readability by cleaning up commented-out code and improving function definitions in `dialog_resolver.py` and `plugin.py`.
1 parent eb50c4d commit 163a0da

6 files changed

Lines changed: 27 additions & 29 deletions

File tree

src/revitdevtool_pytest/bridge.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def connect(self) -> None:
6666
self._handle, win32pipe.PIPE_READMODE_BYTE, None, None,
6767
)
6868
return
69-
except Exception:
69+
except Exception: # noqa
7070
if time.monotonic() >= deadline:
7171
raise ConnectionError(
7272
f"Cannot connect to pipe '{self._pipe_name}' "
@@ -82,11 +82,11 @@ def disconnect(self) -> None:
8282

8383
try:
8484
win32file.FlushFileBuffers(handle)
85-
except Exception: # noqa: BLE001
85+
except Exception: # noqa
8686
pass
8787
try:
8888
win32file.CloseHandle(handle)
89-
except Exception: # noqa: BLE001
89+
except Exception: # noqa
9090
pass
9191

9292
@property
@@ -98,7 +98,7 @@ def connected(self) -> bool:
9898

9999
win32pipe.PeekNamedPipe(self._handle, 0)
100100
return True
101-
except Exception: # noqa: BLE001
101+
except Exception: # noqa
102102
log.debug("Pipe health check failed, marking as disconnected")
103103
return False
104104

@@ -120,7 +120,7 @@ def run_tests(
120120
nodeids=nodeids,
121121
pytest_args=pytest_args or [],
122122
)
123-
response = self._request(
123+
response: BridgeResponse = self._request(
124124
BridgeRequest(method=BRIDGE_METHOD_TESTS_RUN, params=request.to_params()),
125125
timeout_s,
126126
on_notification=on_notification,
@@ -138,20 +138,17 @@ def _request(
138138
) -> BridgeResponse:
139139
self._write_frame(req.to_json_bytes())
140140
deadline = time.monotonic() + timeout_s
141-
while True:
142-
remaining = deadline - time.monotonic()
143-
if remaining <= 0:
144-
raise TimeoutError(f"Timed out waiting for response to {req.id}")
145-
data = self._read_frame(remaining)
141+
while time.monotonic() < deadline:
142+
data = self._read_frame(deadline - time.monotonic())
146143
parsed = json.loads(data)
147144

148145
if parsed.get("type") == BRIDGE_MSG_TYPE_NOTIFICATION:
149146
_dispatch_notification(parsed, on_notification)
150147
continue
151148

152-
resp = BridgeResponse.from_json(parsed)
153-
if resp.id == req.id:
154-
return resp
149+
return BridgeResponse.from_json(parsed)
150+
151+
raise TimeoutError(f"Timed out waiting for response to {req.id}")
155152

156153
def _write_frame(self, body: bytes) -> None:
157154
import win32file # type: ignore[import-untyped]
@@ -211,5 +208,5 @@ def _dispatch_notification(
211208
params = parsed.get("params")
212209
try:
213210
callback(method, params)
214-
except Exception: # noqa: BLE001
211+
except Exception: # noqa
215212
log.debug("Notification callback error for method=%s", method, exc_info=True)

src/revitdevtool_pytest/connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ def _resolve_launch_version(
294294
if version is not None:
295295
return version
296296
if instances:
297-
return max(instances, key=lambda i: i.version).version
297+
return max(instances, key=lambda i: i.version).version # noqa
298298
pytest.exit(
299299
f"{PLUGIN_NAME}: --revit-version is required when no existing instances are available.",
300300
returncode=EXIT_CODE_CONFIG_ERROR,

src/revitdevtool_pytest/dialog_resolver.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,7 @@ def _is_whitelisted(self, title: str) -> bool:
112112
def _find_button(self, parent: int) -> int | None:
113113
result: list[tuple[int, int]] = []
114114

115-
@_EnumWindowsProc
116-
def _cb(child: int, _: int) -> bool:
115+
def _enum_cb(child: int, _: int) -> bool:
117116
score = _get_button_score(
118117
child,
119118
self._opts.preferred_button_keywords,
@@ -123,7 +122,7 @@ def _cb(child: int, _: int) -> bool:
123122
result.append((score, child))
124123
return True
125124

126-
_user32.EnumChildWindows(parent, _cb, 0)
125+
_user32.EnumChildWindows(parent, _EnumWindowsProc(_enum_cb), 0)
127126
if not result:
128127
return None
129128

@@ -133,13 +132,12 @@ def _cb(child: int, _: int) -> bool:
133132
def _enum_dialog_windows(self) -> list[int]:
134133
windows: list[int] = []
135134

136-
@_EnumWindowsProc
137-
def _cb(hwnd: int, _: int) -> bool:
135+
def _enum_cb(hwnd: int, _: int) -> bool:
138136
if _is_target_dialog(hwnd, self._pid):
139137
windows.append(hwnd)
140138
return True
141139

142-
_user32.EnumWindows(_cb, 0)
140+
_user32.EnumWindows(_EnumWindowsProc(_enum_cb), 0)
143141
return windows
144142

145143

src/revitdevtool_pytest/discovery.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import time
99
import winreg
1010
from dataclasses import dataclass
11+
from pathlib import Path
1112

1213
from .constants import (
1314
DEFAULT_LAUNCH_TIMEOUT_S,
@@ -70,7 +71,7 @@ def find_revit_path(version: int) -> str | None:
7071
if path:
7172
return path
7273
default = f"C:\\Program Files\\Autodesk\\Revit {version}\\Revit.exe"
73-
return default if os.path.isfile(default) else None
74+
return default if Path(default).is_file() else None
7475

7576

7677
def start_revit(version: int) -> int:

src/revitdevtool_pytest/plugin.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def pytest_runtestloop(session: pytest.Session) -> bool:
117117

118118

119119
@pytest.hookimpl(tryfirst=True)
120-
def pytest_runtest_protocol(item: pytest.Item, nextitem: pytest.Item | None) -> bool: # noqa: ARG001
120+
def pytest_runtest_protocol(item: pytest.Item, nextitem: pytest.Item | None) -> bool: # noqa
121121
results_by_nodeid = item.session.stash.get(_remote_results_key, None)
122122
if results_by_nodeid is None:
123123
return False
@@ -145,8 +145,8 @@ def _count_failures(item: pytest.Item, results: list[CaseResult]) -> None:
145145
item.session.testsfailed += 1
146146

147147

148-
def pytest_unconfigure(config: pytest.Config) -> None: # noqa: ARG001
149-
global _bridge, _dialog_resolver, _lease_store # noqa: PLW0603
148+
def pytest_unconfigure(config: pytest.Config) -> None: # noqa
149+
global _bridge, _dialog_resolver, _lease_store
150150
_suite_mutex.release()
151151
if _dialog_resolver is not None:
152152
_dialog_resolver.stop()

src/revitdevtool_pytest/suite_leasing.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import time
99
from dataclasses import dataclass
1010
from pathlib import Path
11+
from typing import Any
1112

1213
from .discovery import RevitInstance
1314

@@ -28,7 +29,7 @@ class SuiteLease:
2829
assigned_at: float
2930
last_seen_at: float
3031

31-
def to_dict(self) -> dict[str, object]:
32+
def to_dict(self) -> dict[str, Any]:
3233
return {
3334
"suite_key": self.suite_key,
3435
"suite_path": self.suite_path,
@@ -39,7 +40,7 @@ def to_dict(self) -> dict[str, object]:
3940
}
4041

4142
@classmethod
42-
def from_dict(cls, data: dict[str, object]) -> SuiteLease:
43+
def from_dict(cls, data: dict[str, Any]) -> SuiteLease:
4344
return cls(
4445
suite_key=str(data.get("suite_key", "")),
4546
suite_path=str(data.get("suite_path", "")),
@@ -115,7 +116,7 @@ def _load_leases(self) -> dict[str, SuiteLease]:
115116
return {}
116117
try:
117118
payload = json.loads(self._state_file.read_text(encoding="utf-8"))
118-
except Exception:
119+
except Exception: # noqa
119120
return {}
120121

121122
if not isinstance(payload, dict):
@@ -145,7 +146,8 @@ def _save_leases(self) -> None:
145146
content = json.dumps(payload, ensure_ascii=False, indent=2)
146147
base_tmp = self._state_file.with_suffix(".tmp")
147148

148-
for attempt, delay in enumerate((*_SAVE_RETRY_DELAYS_S, None), start=1):
149+
delays: tuple[float | None, ...] = (*_SAVE_RETRY_DELAYS_S, None)
150+
for attempt, delay in enumerate(delays, start=1):
149151
tmp_file = base_tmp.with_name(f"{base_tmp.stem}.{os.getpid()}.{random.randint(1000, 9999)}{base_tmp.suffix}")
150152
try:
151153
tmp_file.write_text(content, encoding="utf-8")

0 commit comments

Comments
 (0)