Skip to content

Conversation

ludeeus
Copy link
Owner

@ludeeus ludeeus commented Jul 5, 2025

No description provided.

@Copilot Copilot AI review requested due to automatic review settings July 5, 2025 17:02
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances WebSocket subscription handling in ApiClient by introducing a configurable heartbeat interval, refactoring the subscription loop for cleaner async context management, and updating tests to align with the new behavior.

  • Add ws_heartbeat parameter to ApiClient.__init__ and pass it to ws_connect
  • Refactor subscribe to use async with and async for for WebSocket handling
  • Update tests to handle WSMsgType.CLOSING and optional exception message matching

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
tests/test_subscription.py Include CLOSING in message sequence, adjust exception test to accept None
tests/conftest.py Add from __future__ import annotations, implement async context & iteration
pytraccar/client.py Introduce ws_heartbeat, refactor subscribe with async with/async for
Comments suppressed due to low confidence (3)

tests/test_subscription.py:180

  • [nitpick] Rename the parameter raises to expected_exception for clarity and to avoid confusion with pytest's raises context manager.
async def test_subscription_exceptions(

tests/test_subscription.py:184

  • [nitpick] Consider renaming with_message to expected_message to clearly convey its role in matching the exception message.
    with_message: str | None,

pytraccar/client.py:51

  • Add a test to verify that the ws_heartbeat parameter is correctly forwarded to ws_connect when subscribing to ensure the new feature is covered.
        ws_heartbeat: int = 120,

Copy link

coderabbitai bot commented Jul 5, 2025

📝 Walkthrough

Walkthrough

The changes introduce a configurable WebSocket heartbeat interval to the ApiClient class and refactor its subscription logic to use asynchronous context management and iteration. Corresponding updates enhance the WebSocket mock in tests to support async context and iteration, and test cases are adjusted to reflect new message type handling and exception matching logic.

Changes

File(s) Change Summary
pytraccar/client.py Added ws_heartbeat parameter to ApiClient constructor; refactored subscribe to use async context and iteration, handle more WebSocket message types.
tests/conftest.py Enhanced MockedWSContext with async context manager and iterator methods; added from __future__ import annotations.
tests/test_subscription.py Updated tests for new WebSocket message type handling (CLOSING), refined exception message matching in parameterized tests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ApiClient
    participant WebSocket

    User->>ApiClient: subscribe(callback)
    ApiClient->>WebSocket: async with ws_connect(heartbeat=ws_heartbeat)
    loop For each message
        WebSocket-->>ApiClient: msg
        ApiClient->>ApiClient: Check msg.type
        alt msg.type is TEXT
            ApiClient->>callback: await callback(data)
        else msg.type is CLOSE/CLOSED/CLOSING/ERROR
            ApiClient->>User: Raise TraccarConnectionException
        end
    end
Loading
sequenceDiagram
    participant Test
    participant MockedWSContext

    Test->>MockedWSContext: async with (context manager)
    MockedWSContext-->>Test: __aenter__ returns self
    loop For each message
        MockedWSContext-->>Test: __anext__ yields next message
    end
    MockedWSContext-->>Test: __aexit__ on exit
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 0

🧹 Nitpick comments (1)
tests/conftest.py (1)

55-68: Consider improving type annotations for the async methods.

The async context manager and iterator implementation is correct and properly mocks the WebSocket behavior. However, the type annotations could be improved.

Apply this diff to improve type annotations:

+from typing import Self
+
 class MockedWSContext:
     # ... existing code ...
 
-    async def __aenter__(self) -> MockedWSContext:
+    async def __aenter__(self) -> Self:
         return self
 
-    async def __aexit__(self, *args: Any) -> None:
+    async def __aexit__(self, *args: object) -> None:
         pass
 
-    def __aiter__(self) -> MockedWSContext:
+    def __aiter__(self) -> Self:
         return self

Note: Self requires Python 3.11+ or from typing_extensions import Self for earlier versions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between d6dec0f and e2050c7.

📒 Files selected for processing (3)
  • pytraccar/client.py (3 hunks)
  • tests/conftest.py (2 hunks)
  • tests/test_subscription.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
tests/test_subscription.py (4)
tests/common.py (1)
  • WSMessage (13-23)
tests/conftest.py (1)
  • api_client (89-98)
pytraccar/client.py (2)
  • subscription_status (63-65)
  • subscribe (158-236)
pytraccar/models/subscription.py (1)
  • SubscriptionStatus (14-20)
tests/conftest.py (1)
tests/common.py (1)
  • get (49-55)
pytraccar/client.py (2)
pytraccar/models/subscription.py (1)
  • SubscriptionStatus (14-20)
pytraccar/exceptions.py (1)
  • TraccarConnectionException (12-13)
🪛 Ruff (0.11.9)
tests/conftest.py

55-55: __aenter__ methods in classes like MockedWSContext usually return self at runtime

Use Self as return type

(PYI034)


58-58: Star-args in __aexit__ should be annotated with object

Annotate star-args with object

(PYI036)

🪛 Pylint (3.3.7)
tests/conftest.py

[error] 55-55: Undefined variable 'MockedWSContext'

(E0602)


[error] 61-61: Undefined variable 'MockedWSContext'

(E0602)

🔇 Additional comments (5)
tests/test_subscription.py (2)

81-81: LGTM!

Adding CLOSING to the stopping messages is consistent with the updated WebSocket handling in client.py.


175-175: Good improvement to exception testing flexibility.

The change to allow None for with_message enables testing exceptions without requiring message matching, which is useful for cases where the exception is raised without a message.

Also applies to: 184-194

tests/conftest.py (1)

3-3: LGTM!

Adding from __future__ import annotations enables forward reference support for type annotations.

pytraccar/client.py (2)

51-51: Good addition of configurable WebSocket heartbeat.

The ws_heartbeat parameter with a default of 120 seconds provides flexibility for WebSocket connection management while maintaining a sensible default.

Also applies to: 60-60


165-201: Excellent refactoring to use async context management and iteration.

The changes improve the WebSocket handling by:

  • Using async with for proper resource management
  • Replacing manual receive() loop with async for iteration
  • Including the heartbeat parameter in the connection
  • Adding CLOSING to the stopping message types for comprehensive connection closure handling

@ludeeus ludeeus added the refactor For refactoring changes that does not impact any behavior label Jul 5, 2025
@ludeeus ludeeus merged commit 3919398 into main Jul 5, 2025
7 of 8 checks passed
@ludeeus ludeeus deleted the enhance-sub branch July 5, 2025 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor For refactoring changes that does not impact any behavior
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant