Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HomeWizardEnergy base class which is implemented in v1 and v2 #452

Merged
merged 3 commits into from
Jan 1, 2025

Conversation

DCSBL
Copy link
Collaborator

@DCSBL DCSBL commented Jan 1, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a base class HomeWizardEnergy for interacting with the HomeWizard Energy API
    • Enhanced support for asynchronous operations and session management
    • Improved API interaction methods for device, measurement, system, and state
  • Refactor

    • Restructured HomeWizardEnergyV1 and HomeWizardEnergyV2 classes to inherit from new base class
    • Updated method names and session handling across API versions
  • Tests

    • Added comprehensive test coverage for new base class and API version implementations
    • Updated test cases to reflect new method signatures and behaviors

Copy link

coderabbitai bot commented Jan 1, 2025

Walkthrough

The pull request introduces a new base class HomeWizardEnergy in the homewizard_energy module, which serves as a foundational class for interacting with the HomeWizard Energy API. This base class provides a standardized structure for API interactions, including asynchronous methods for device, measurement, system, state, identify, and reboot operations. The existing V1 and V2 classes are refactored to inherit from this base class, simplifying session management and providing a more consistent interface across different API versions.

Changes

File Change Summary
homewizard_energy/homewizard_energy.py Added HomeWizardEnergy base class with async methods, session management, and context management
homewizard_energy/v1/__init__.py Updated HomeWizardEnergyV1 to inherit from HomeWizardEnergy, renamed data() method to measurement()
homewizard_energy/v2/__init__.py Updated HomeWizardEnergyV2 to inherit from HomeWizardEnergy, modified constructor and session handling
tests/test_homewizard_energy.py Added new test to verify NotImplementedError is raised for base class methods
tests/v1/test_v1_homewizard_energy.py Updated tests to use measurement() instead of data() method
tests/v2/test_v2_homewizard_energy.py Updated session variable from _clientsession to _session

Sequence Diagram

sequenceDiagram
    participant Client
    participant BaseClass as HomeWizardEnergy
    participant V1Class as HomeWizardEnergyV1
    participant V2Class as HomeWizardEnergyV2
    participant API as HomeWizard API

    Client->>BaseClass: Create instance
    BaseClass-->>Client: Base class instance
    Client->>V1Class: Create V1 instance
    V1Class-->>Client: V1 instance
    Client->>V2Class: Create V2 instance
    V2Class-->>Client: V2 instance

    Client->>V1Class: measurement()
    V1Class->>API: Fetch measurement
    API-->>V1Class: Return measurement
    V1Class-->>Client: Return measurement

    Client->>V2Class: device()
    V2Class->>API: Fetch device info
    API-->>V2Class: Return device info
    V2Class-->>Client: Return device info
Loading

Possibly related PRs


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

codecov bot commented Jan 1, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.95%. Comparing base (59b6de0) to head (8d87a39).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #452      +/-   ##
==========================================
+ Coverage   96.90%   96.95%   +0.05%     
==========================================
  Files           8        9       +1     
  Lines         484      492       +8     
  Branches       34       33       -1     
==========================================
+ Hits          469      477       +8     
  Misses         11       11              
  Partials        4        4              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 (8)
homewizard_energy/homewizard_energy.py (3)

13-14: Consider using an abstract base class for mandatory methods.
You're raising NotImplementedError in the derived methods, which is a valid approach. However, it might be clearer to mark HomeWizardEnergy as abstract via Python's abc module to explicitly communicate that classes must override these methods.


16-19: Add type annotations or docstrings for private attributes.
Including brief docstrings or type annotations for the _session, _close_session, _request_timeout, and _host attributes helps ensure readability and consistency with the rest of the codebase, especially if multiple contributors are involved.


83-88: Validate session usage before closing.
This code only checks that _session is non-None before closing, but you may want to confirm the session is still open or ensure no subsequent calls use it. Providing a small safeguard or logging at the call sites would help diagnose potential usage after close.

homewizard_energy/v1/__init__.py (1)

44-45: Confirm no missing overridden methods.
You disable the abstract-method warning here, but the base class defines several methods that raise NotImplementedError. Since you're actually implementing them (device, measurement, etc.), verify that all relevant methods are covered if future expansions occur.

homewizard_energy/v2/__init__.py (3)

58-65: Recommend clarifying docstring for clientsession.
Since you’re now accepting clientsession, add documentation that clarifies if you expect an already-open session and how the class handles session closure.


220-221: Ensure proper session creation.
When _session is None, you await _get_session(). This is fine, but watch for race conditions if _request can be called from multiple tasks at once before _session is set.


235-235: Log request data carefully.
You’re using LOGGER.debug to print request status and response text. Double-check that no sensitive data (like tokens) are ever logged.

tests/v1/test_v1_homewizard_energy.py (1)

233-235: Consider consolidating repeated test logic

Lines 233–235 and later lines (278–280) perform nearly identical assertions on measurement. You could reduce duplication by factoring out the common logic into a shared helper or parameterizing the test. This improvement can make the test suite more concise and easier to maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59b6de0 and 8d87a39.

📒 Files selected for processing (6)
  • homewizard_energy/homewizard_energy.py (1 hunks)
  • homewizard_energy/v1/__init__.py (3 hunks)
  • homewizard_energy/v2/__init__.py (6 hunks)
  • tests/test_homewizard_energy.py (1 hunks)
  • tests/v1/test_v1_homewizard_energy.py (2 hunks)
  • tests/v2/test_v2_homewizard_energy.py (1 hunks)
🔇 Additional comments (11)
homewizard_energy/homewizard_energy.py (2)

21-38: Ensure that user-provided timeouts are handled consistently.
Your constructor sets a default 10-second timeout. Double-check that all future overridden methods or HTTP request logic correctly utilize _request_timeout, so that user-specified timeouts apply uniformly.


89-103: Consider handling exceptions in __aexit__.
Currently, __aexit__ always calls await self.close() regardless of whether an exception occurred. You might want to handle or log exceptions here to diagnose failures, especially if a finalized closure after an error might complicate debugging.

homewizard_energy/v1/__init__.py (2)

23-23: Validate consistent imports.
You’re now importing HomeWizardEnergy from ..homewizard_energy. Ensure that other references (e.g., session creation or method overrides) match the base class usage in this file.


60-60: Method name aligns well with the base class.
Renaming data to measurement keeps the API consistent with HomeWizardEnergy. Good job on maintaining consistency.

homewizard_energy/v2/__init__.py (3)

32-32: Inheritance from HomeWizardEnergy.
Using the new base class promotes code reuse and consistency. Verify that v2-specific quirks (like token handling) are covered properly.


54-55: Same recommendation as v1: confirm abstract methods coverage.
Ensure that all relevant methods from HomeWizardEnergy are fully implemented or intentionally left for overriding in the future.


185-185: Check concurrency if _get_session can be called multiple times.
If _get_session may be invoked concurrently, ensure you prevent creating multiple sessions or overwriting the _session while another request is using it.

tests/test_homewizard_energy.py (1)

1-25: Test coverage for base class methods is excellent.
You verify that each of the abstract-like methods in HomeWizardEnergy raises NotImplementedError. As a possible future step, consider adding coverage for the close/context-manager usage to ensure resource cleanup works as expected.

tests/v2/test_v2_homewizard_energy.py (2)

522-523: Use _session consistently.
Great update from _clientsession to _session. This ensures consistency with the base class. Also verify test coverage for other methods that might rely on the session.


528-528: Check exponential backoff behavior.
The test asserts the request retries five times. Since you’re combining backoff with your request approach, confirm that repeated retries are truly desired in all production scenarios to avoid possible resource overuse if the device is offline.

tests/v1/test_v1_homewizard_energy.py (1)

278-280: Validation steps for measurement correctness look good

The updated assertion structure blends well with snapshot matching, ensuring the measurement() method returns valid data. The logic aligns with typical test best practices.

@DCSBL DCSBL merged commit 10805f4 into main Jan 1, 2025
32 checks passed
@DCSBL DCSBL deleted the base-class branch January 1, 2025 19:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant