Simulate the client's response parsing logic. This replicates the logic from RpcClient._wait_for_response() to test edge cases without needing a real serial connection.
(json_str: str, expected_id: int)
| 196 | |
| 197 | |
| 198 | def parse_response_like_client(json_str: str, expected_id: int) -> RpcResponse: |
| 199 | """Simulate the client's response parsing logic. |
| 200 | |
| 201 | This replicates the logic from RpcClient._wait_for_response() |
| 202 | to test edge cases without needing a real serial connection. |
| 203 | """ |
| 204 | data = json.loads(json_str) |
| 205 | |
| 206 | # Check ID matching (from _wait_for_response) |
| 207 | response_id = data.get("id") |
| 208 | if response_id is None: |
| 209 | raise ValueError("Response without ID") |
| 210 | if response_id != expected_id: |
| 211 | raise ValueError(f"ID mismatch: expected {expected_id}, got {response_id}") |
| 212 | |
| 213 | # Extract result/error field for JSON-RPC 2.0 responses |
| 214 | # Priority: result > error > empty dict (no protocol fields) |
| 215 | if "result" in data: |
| 216 | response_data = data["result"] |
| 217 | elif "error" in data: |
| 218 | response_data = data["error"] |
| 219 | else: |
| 220 | # No result or error - empty response |
| 221 | response_data = {} |
| 222 | |
| 223 | # Determine success: void functions return null, treat as success |
| 224 | if "success" in data: |
| 225 | success = data.get("success", True) |
| 226 | elif isinstance(response_data, dict): |
| 227 | success = response_data.get("success", True) |
| 228 | else: |
| 229 | # Void functions return null - treat as successful execution |
| 230 | success = True |
| 231 | |
| 232 | # Ensure response_data is always a dict for consistent API |
| 233 | if response_data is None or not isinstance(response_data, dict): |
| 234 | response_data = {} |
| 235 | |
| 236 | return RpcResponse( |
| 237 | success=success, data=response_data, raw_line=json_str, _id=response_id |
| 238 | ) |
| 239 | |
| 240 | |
| 241 | def run_tests() -> tuple[int, int]: |
no test coverage detected