Skip to content

refactor: streamline request processing by extracting to a separate method#524

Merged
firstof9 merged 5 commits intomainfrom
suggested-changes
Mar 4, 2026
Merged

refactor: streamline request processing by extracting to a separate method#524
firstof9 merged 5 commits intomainfrom
suggested-changes

Conversation

@firstof9
Copy link
Owner

@firstof9 firstof9 commented Mar 3, 2026

Summary by CodeRabbit

  • Refactor
    • Centralized request/session processing to remove duplicated logic and improve reuse and readability.
  • Bug Fixes
    • More consistent handling and clearer reporting of HTTP errors (400/401/404/405/500) and edge cases for decoding and JSON parsing, while preserving timeout and authentication behavior.
  • Tests
    • Added coverage for additional parse-error scenarios to ensure invalid JSON shapes are detected.

@coderabbitai
Copy link

coderabbitai bot commented Mar 3, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3eb5944 and 9ad24e4.

📒 Files selected for processing (1)
  • tests/test_main.py

📝 Walkthrough

Walkthrough

Centralizes HTTP request processing in openevsehttp/__main__.py by adding _process_request_with_session and routing both external and internal session flows through it; consolidates dispatch, Unicode fallback, JSON parsing, and HTTP status/error handling. Adds tests for additional parse-error scenarios.

Changes

Cohort / File(s) Summary
Core refactor
openevsehttp/__main__.py
Added _process_request_with_session and refactored request handling to delegate all request/response processing to it; unified external/internal session usage, tightened JSON decoding fallback, and consolidated HTTP status/error logging and handling (400/401/404/405/500, timeouts, content-type).
Tests - parse error coverage
tests/test_main.py
Added two parse-error test cases to test_send_command_parse_err covering a 400 response with an unrelated JSON object key and a 400 response that is a JSON string, asserting ParseJSONError is raised.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Caller
    participant Helper as _process_request_with_session
    participant Server
    participant JSONParser
    Caller->>Helper: call request (with external or internal session)
    Helper->>Server: send HTTP request
    Server-->>Helper: return HTTP response (status, headers, body)
    Helper->>JSONParser: attempt JSON parse (Unicode fallback if needed)
    alt parsed JSON
        JSONParser-->>Helper: parsed object
        Helper-->>Caller: return parsed response / handle specific HTTP status
    else parse error or timeout
        JSONParser-->>Helper: parse error / timeout
        Helper-->>Caller: raise/log appropriate error (e.g., ParseJSONError)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through lines both new and neat,
Collected sessions, made the flow complete,
JSON peeks and Unicode tries,
Tests to catch odd, sneaky replies,
A tidy hop — the refactor's sweet.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring: extracting request processing logic into a separate helper method (_process_request_with_session) to streamline and consolidate the handling pattern.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch suggested-changes

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (4.0.5)
tests/test_main.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@firstof9 firstof9 marked this pull request as ready for review March 3, 2026 22:17
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openevsehttp/__main__.py`:
- Around line 167-188: The 400-response handler assumes message is a dict and
directly accesses message.keys() and message[index], which can raise
AttributeError/KeyError if JSON parsing failed or payload is a string; update
the resp.status == 400 branch in __main__.py to first verify isinstance(message,
dict) (or similar truthy mapping check) before looking for "msg" or "error", log
the raw message when it is not a dict or when neither key exists, and then raise
ParseJSONError; keep ParseJSONError and AuthenticationError behavior intact and
ensure other branches (resp status checks and the method == "post"
config_version handling that calls self.update()) remain unchanged.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7354ff and a95a2eb.

📒 Files selected for processing (1)
  • openevsehttp/__main__.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
openevsehttp/__main__.py (1)

186-188: ⚠️ Potential issue | 🟡 Minor

Add isinstance guard for config_version check.

When JSON parsing fails, message remains a string. The in operator on a string performs substring matching rather than dict key lookup, which could trigger unintended self.update() calls if the response text happens to contain "config_version".

🛡️ Proposed fix
-                if method == "post" and "config_version" in message:
+                if method == "post" and isinstance(message, dict) and "config_version" in message:
                     await self.update()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openevsehttp/__main__.py` around lines 186 - 188, The code checks
"config_version" in message without ensuring message is a dict, so when JSON
parsing fails and message is a string the substring check can incorrectly
trigger await self.update(); add an isinstance guard to verify message is a dict
(or Mapping) before the "config_version" membership test so that in the branch
where method == "post" you only call await self.update() when message is
actually a parsed object (refer to variables method and message and the method
update on self).
🧹 Nitpick comments (1)
openevsehttp/__main__.py (1)

190-195: Consider simplifying re-raise statements.

Static analysis suggests using bare raise instead of raise err when re-raising the caught exception, which is slightly more idiomatic in Python.

♻️ Optional simplification
         except (TimeoutError, ServerTimeoutError) as err:
             _LOGGER.error("%s: %s", ERROR_TIMEOUT, url)
-            raise err
+            raise
         except ContentTypeError as err:
             _LOGGER.error("Content error: %s", err.message)
-            raise err
+            raise
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openevsehttp/__main__.py` around lines 190 - 195, Replace the explicit "raise
err" with a bare "raise" in the except handlers to re-raise the original
exception while preserving the traceback; specifically update the except blocks
catching (TimeoutError, ServerTimeoutError) and ContentTypeError that log via
_LOGGER and ERROR_TIMEOUT to use "raise" instead of "raise err". Ensure the
logging still references err where needed (e.g., in the ContentTypeError
handler) but do not change the logged messages or exception classes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@openevsehttp/__main__.py`:
- Around line 186-188: The code checks "config_version" in message without
ensuring message is a dict, so when JSON parsing fails and message is a string
the substring check can incorrectly trigger await self.update(); add an
isinstance guard to verify message is a dict (or Mapping) before the
"config_version" membership test so that in the branch where method == "post"
you only call await self.update() when message is actually a parsed object
(refer to variables method and message and the method update on self).

---

Nitpick comments:
In `@openevsehttp/__main__.py`:
- Around line 190-195: Replace the explicit "raise err" with a bare "raise" in
the except handlers to re-raise the original exception while preserving the
traceback; specifically update the except blocks catching (TimeoutError,
ServerTimeoutError) and ContentTypeError that log via _LOGGER and ERROR_TIMEOUT
to use "raise" instead of "raise err". Ensure the logging still references err
where needed (e.g., in the ContentTypeError handler) but do not change the
logged messages or exception classes.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a95a2eb and 0b5cdbf.

📒 Files selected for processing (1)
  • openevsehttp/__main__.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
openevsehttp/__main__.py (1)

194-199: Consider using logging.exception for error context (optional).

Static analysis suggests using logging.exception instead of logging.error when handling exceptions. Since these exceptions are re-raised immediately, the current approach is acceptable. However, logging.exception would capture the stack trace at the logging point, which can aid debugging if logs are reviewed independently of exception propagation.

♻️ Optional: Use logging.exception for richer context
         except (TimeoutError, ServerTimeoutError):
-            _LOGGER.error("%s: %s", ERROR_TIMEOUT, url)
+            _LOGGER.exception("%s: %s", ERROR_TIMEOUT, url)
             raise
         except ContentTypeError as err:
-            _LOGGER.error("Content error: %s", err.message)
+            _LOGGER.exception("Content error: %s", err.message)
             raise
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openevsehttp/__main__.py` around lines 194 - 199, Replace the plain error
logs with exception-aware logging so the stack trace is captured when these
exceptions are handled: in the except block that catches (TimeoutError,
ServerTimeoutError) use _LOGGER.exception (including ERROR_TIMEOUT and url)
instead of _LOGGER.error, and in the except ContentTypeError as err block use
_LOGGER.exception (including a descriptive message and err) rather than
_LOGGER.error; keep re-raising the exceptions unchanged so behavior is
preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@openevsehttp/__main__.py`:
- Around line 194-199: Replace the plain error logs with exception-aware logging
so the stack trace is captured when these exceptions are handled: in the except
block that catches (TimeoutError, ServerTimeoutError) use _LOGGER.exception
(including ERROR_TIMEOUT and url) instead of _LOGGER.error, and in the except
ContentTypeError as err block use _LOGGER.exception (including a descriptive
message and err) rather than _LOGGER.error; keep re-raising the exceptions
unchanged so behavior is preserved.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b5cdbf and 3eb5944.

📒 Files selected for processing (1)
  • openevsehttp/__main__.py

@firstof9 firstof9 added the code quality Improves code quality label Mar 3, 2026
@firstof9 firstof9 merged commit 40edceb into main Mar 4, 2026
5 checks passed
@firstof9 firstof9 deleted the suggested-changes branch March 4, 2026 00:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code quality Improves code quality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant