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

Enable mypy part 1 (addons and api) #5759

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

Enable mypy part 1 (addons and api) #5759

wants to merge 3 commits into from

Conversation

mdegat01
Copy link
Contributor

@mdegat01 mdegat01 commented Mar 17, 2025

Proposed change

On a quest to enable mypy in CI to help us catch more issues before they become bugs. As we've had it off for so long there are quite a few issues so this will take several PRs. This PR covers the addons and api modules.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (which adds functionality to the supervisor)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to cli pull request:
  • Link to client library pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • The code has been formatted using Ruff (ruff format supervisor tests)
  • Tests have been added to verify that the new code works.

If API endpoints or add-on configuration are added/changed:

Summary by CodeRabbit

  • Refactor

    • Consolidated error handling and state management to improve stability.
    • Streamlined API interfaces with clearer type annotations and default handling.
    • Updated methods for adding unsupported reasons, suggestions, issues, and unhealthy reasons to use dedicated methods instead of direct assignments.
  • Chore

    • Enhanced default parameter usage for more robust request processing.
    • Updated internal tests to align with improved error tracking and resolution methods.

@mdegat01 mdegat01 added the refactor A code change that neither fixes a bug nor adds a feature label Mar 17, 2025
@mdegat01 mdegat01 requested a review from agners March 17, 2025 17:26
Copy link
Contributor

coderabbitai bot commented Mar 17, 2025

📝 Walkthrough

Walkthrough

This update introduces wide-ranging improvements across multiple modules. Changes include enhanced type annotations, stricter error handling, and refined control flows. Notably, properties in the Addon classes now use additional conditions; version properties now return an instance of a dedicated version class; and many direct assignments to unhealthy states are replaced with method calls such as add_unhealthy_reason. API endpoints have been renamed for clarity and async support improved, while tests are updated to reflect these changes. Overall, these modifications focus on improving consistency, type safety, and robustness throughout the codebase.

Changes

File(s) Change Summary
supervisor/addons/{addon.py, build.py, manager.py, model.py, options.py} Updated property logic with addon_store checks; version properties now return AwesomeVersion; improved error handling in install/update methods; enhanced type hints.
supervisor/api/{__init__.py, addons.py, audio.py, auth.py, backups.py, discovery.py, hardware.py, host.py, ingress.py, jobs.py, middleware/security.py, mounts.py, network.py, proxy.py, resolution.py, services.py, store.py, supervisor.py, utils.py} Renamed and clarified API endpoint handlers; updated method signatures for async support; provided default fallback values for request parameters; refined type annotations.
supervisor/auth.py Modified check_login to accept None for username/password and raise an error when password is missing.
supervisor/{core.py, coresys.py}
supervisor/host/apparmor.py
supervisor/plugins/{audio.py, dns.py}
supervisor/backups/manager.py
supervisor/supervisor.py
supervisor/store/data.py
Replaced direct assignment of unhealthy states with calls to add_unhealthy_reason, standardizing error handling.
supervisor/discovery/__init__.py
supervisor/docker/interface.py
supervisor/utils/systemd_journal.py
Adjusted type annotations: changed uuid from UUID to str, explicitly typed MAP_ARCH, and updated generator return types.
supervisor/homeassistant/{api.py, module.py} Updated request parameter types, return types, and error handling using add_unhealthy_reason for improved robustness.
supervisor/jobs/decorator.py Changed the on_condition parameter type to expect a JobException type rather than an instance.
supervisor/resolution/* Refactored resolution management by replacing direct assignments of issues, suggestions, unsupported and unhealthy reasons with corresponding add_* methods.
tests/{api, jobs, misc, resolution/...} Updated test cases to use dedicated methods (add_issue, add_suggestion, add_unhealthy_reason, add_unsupported_reason) instead of direct property assignments.

Sequence Diagram(s)

sequenceDiagram
    participant Module as Affected Module
    participant SysRes as System Resolution
    participant Log as Logger

    Module->>SysRes: Encounter error (e.g. EBADMSG)
    Note right of SysRes: Instead of direct assignment,\\call add_unhealthy_reason(reason)
    SysRes-->>Module: Unhealthy state updated
    Module->>Log: Log error message
Loading
sequenceDiagram
    participant Request as API Request
    participant AM as AddonManager
    participant Scheduler as Job Scheduler

    Request->>AM: Call uninstall(addon_slug, remove_config)
    AM->>Scheduler: @Job decorator triggers job scheduling
    Scheduler-->>AM: Execute uninstall asynchronously
    AM-->>Request: Return response
Loading

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9496317 and 7c8ef05.

📒 Files selected for processing (1)
  • supervisor/resolution/module.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build armv7 supervisor
  • GitHub Check: Build armhf supervisor
  • GitHub Check: Build aarch64 supervisor
🔇 Additional comments (6)
supervisor/resolution/module.py (6)

95-113: Code refactoring improves type safety and clarity

The new add_suggestion method replaces the removed setter, providing better encapsulation and type safety. This change aligns with the PR's goal of enabling mypy by making the code more explicit and type-friendly.


119-127: Good encapsulation with explicit method naming

Replacing the setter with add_unsupported_reason makes the code more maintainable and improves type safety. The method clearly communicates its purpose and maintains the same validation logic as before.


129-131: Docstring format improvement

Minor improvement to docstring formatting for consistency.


133-140: Enhanced type safety with dedicated method

Adding the add_unhealthy_reason method follows the same pattern as the other changes, improving type safety and code clarity. The method properly handles duplicate checking and event notifications.


183-185: Updated method call for consistency

Updated to use the new add_suggestion method instead of direct property assignment, maintaining consistency with the new pattern.


187-197: Consolidated issue handling logic

The add_issue method now incorporates the functionality previously in the removed setter. This consolidation improves code organization by keeping related logic together and makes the code more amenable to static type checking.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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 or @coderabbitai title 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
Contributor

@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 (2)
supervisor/addons/addon.py (1)

288-289: Improved property guard conditions.

Added an additional check for addon_store availability alongside the existing is_detached check. This prevents potential attribute access errors when the addon store reference is missing or not properly initialized.

Consider adding a helper method to check for both conditions since this pattern is repeated across multiple properties.

+def _use_local_data(self) -> bool:
+    """Return whether to use local data instead of store data."""
+    return self.is_detached or not self.addon_store
+
 @property
 def with_icon(self) -> bool:
     """Return True if an icon exists."""
-    if self.is_detached or not self.addon_store:
+    if self._use_local_data():
         return super().with_icon
     return self.addon_store.with_icon

Also applies to: 295-296, 302-303, 309-310

supervisor/resolution/module.py (1)

133-140: Improved unhealthy reason management with dedicated method.

The add_unhealthy_reason method provides better encapsulation of the logic for adding unhealthy reasons, including duplicate checking and event notification.

Note the small typo in the docstring: "unhrealthy" should be "unhealthy".

Fix the typo in the docstring:

-"""Add a reason for unhrealthy."""
+"""Add a reason for unhealthy."""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac5f9dc and 9496317.

📒 Files selected for processing (62)
  • supervisor/addons/addon.py (14 hunks)
  • supervisor/addons/build.py (4 hunks)
  • supervisor/addons/manager.py (2 hunks)
  • supervisor/addons/model.py (2 hunks)
  • supervisor/addons/options.py (3 hunks)
  • supervisor/api/__init__.py (7 hunks)
  • supervisor/api/addons.py (7 hunks)
  • supervisor/api/audio.py (3 hunks)
  • supervisor/api/auth.py (3 hunks)
  • supervisor/api/backups.py (9 hunks)
  • supervisor/api/discovery.py (6 hunks)
  • supervisor/api/hardware.py (1 hunks)
  • supervisor/api/host.py (3 hunks)
  • supervisor/api/ingress.py (5 hunks)
  • supervisor/api/jobs.py (2 hunks)
  • supervisor/api/middleware/security.py (6 hunks)
  • supervisor/api/mounts.py (5 hunks)
  • supervisor/api/network.py (4 hunks)
  • supervisor/api/proxy.py (5 hunks)
  • supervisor/api/resolution.py (1 hunks)
  • supervisor/api/services.py (1 hunks)
  • supervisor/api/store.py (7 hunks)
  • supervisor/api/supervisor.py (1 hunks)
  • supervisor/api/utils.py (6 hunks)
  • supervisor/auth.py (1 hunks)
  • supervisor/backups/manager.py (4 hunks)
  • supervisor/core.py (2 hunks)
  • supervisor/coresys.py (3 hunks)
  • supervisor/discovery/__init__.py (2 hunks)
  • supervisor/docker/interface.py (1 hunks)
  • supervisor/hardware/monitor.py (1 hunks)
  • supervisor/homeassistant/api.py (3 hunks)
  • supervisor/homeassistant/module.py (1 hunks)
  • supervisor/host/apparmor.py (3 hunks)
  • supervisor/jobs/decorator.py (1 hunks)
  • supervisor/os/manager.py (1 hunks)
  • supervisor/plugins/audio.py (2 hunks)
  • supervisor/plugins/dns.py (4 hunks)
  • supervisor/resolution/checks/supervisor_trust.py (1 hunks)
  • supervisor/resolution/evaluate.py (1 hunks)
  • supervisor/resolution/evaluations/base.py (1 hunks)
  • supervisor/resolution/evaluations/container.py (1 hunks)
  • supervisor/resolution/evaluations/source_mods.py (1 hunks)
  • supervisor/resolution/module.py (4 hunks)
  • supervisor/store/data.py (1 hunks)
  • supervisor/supervisor.py (1 hunks)
  • supervisor/utils/systemd_journal.py (1 hunks)
  • tests/api/test_resolution.py (6 hunks)
  • tests/jobs/test_job_decorator.py (1 hunks)
  • tests/misc/test_filter_data.py (2 hunks)
  • tests/resolution/fixup/test_addon_execute_remove.py (1 hunks)
  • tests/resolution/fixup/test_fixup.py (1 hunks)
  • tests/resolution/fixup/test_store_execute_reload.py (1 hunks)
  • tests/resolution/fixup/test_store_execute_remove.py (1 hunks)
  • tests/resolution/fixup/test_store_execute_reset.py (1 hunks)
  • tests/resolution/fixup/test_system_adopt_data_disk.py (4 hunks)
  • tests/resolution/fixup/test_system_clear_full_backup.py (1 hunks)
  • tests/resolution/fixup/test_system_create_full_backup.py (1 hunks)
  • tests/resolution/fixup/test_system_execute_integrity.py (2 hunks)
  • tests/resolution/fixup/test_system_execute_reboot.py (1 hunks)
  • tests/resolution/fixup/test_system_rename_data_disk.py (3 hunks)
  • tests/resolution/test_resolution_manager.py (12 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
`*/**(html|markdown|md)`: - For instructional content in doc...

*/**(html|markdown|md): - For instructional content in documentation, use a direct and authoritative tone. Avoid expressions of politeness such as 'may' or 'please', and ensure the goal of the instruction is fronted.

  • Apply the Microsoft Style Guide to ensure documentation maintains clarity and conciseness.
  • In step-by-step instructions, front the location phrase in the instructional sentence.
  • In step-by-step instructions, front the 'goal' in the instructional sentence.
  • In step-by-step instructions, if in doubt what to front, front the 'goal' before the location phrase in the instructional sentence.
  • do not hyphenate terms like 'top-right' or 'bottom-left' with 'corner'
  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
`*/**(html|markdown|md)`: - Use bold to mark UI strings. - I...

*/**(html|markdown|md): - Use bold to mark UI strings.

  • If "" are used to mark UI strings, replace them by bold.
  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
`*/**(html|markdown|md)`: - Be brief in your replies and don...

*/**(html|markdown|md): - Be brief in your replies and don't add fluff like "thank you for..." and "Please let me know if"

  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
`*/**(html|markdown|md)`: - Use sentence-style capitalizatio...

*/**(html|markdown|md): - Use sentence-style capitalization also in headings.

  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
`*/**(html|markdown|md)`: do not comment on HTML used for ic...

*/**(html|markdown|md): do not comment on HTML used for icons

  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
`*/**(html|markdown|md)`: Avoid flagging inline HTML for emb...

*/**(html|markdown|md): Avoid flagging inline HTML for embedding videos in future reviews for this repository.

  • supervisor/auth.py
  • supervisor/supervisor.py
  • supervisor/core.py
  • supervisor/coresys.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run the Supervisor
  • GitHub Check: Run tests Python 3.13.2
🔇 Additional comments (192)
supervisor/jobs/decorator.py (1)

38-38: Improved type annotation for on_condition parameter

The changed type annotation from JobException | None to type[JobException] | None now correctly indicates that the parameter should be a class type rather than an instance. This matches the actual usage in the code (e.g., at lines 185, 245, and 292), where on_condition is instantiated with parameters.

supervisor/api/resolution.py (3)

36-36: Added default value for robust error handling

Adding a default empty string ensures that get_issue always receives a string value even if the "issue" key is missing from match_info. This prevents potential None values being passed to methods expecting strings.


44-44: Added default value for robust error handling

Adding a default empty string ensures that get_suggestion always receives a string value even if the "suggestion" key is missing from match_info. This is consistent with the other similar changes in this file.


52-52: Added default value for robust error handling

Adding a default empty string ensures that the get method always receives a string value even if the "check" key is missing from match_info. This follows the same pattern as the other similar changes in this file.

supervisor/homeassistant/module.py (1)

332-334: Improved unhealthy state management

Replacing direct assignment with a method call to add_unhealthy_reason() allows tracking multiple unhealthy reasons simultaneously instead of overwriting with a single reason. This provides better diagnostics and follows proper OOP principles of encapsulating state changes behind methods.

supervisor/discovery/__init__.py (1)

8-8: Corrected type annotation for uuid attribute

The type annotation for uuid has been changed from UUID to str, which matches how it's actually used throughout the code. The factory function already returns uuid4().hex (a string representation), and all usages (in dictionary keys, logging, API paths) treat it as a string. The import has also been simplified to only include what's needed.

Also applies to: 34-34

supervisor/api/hardware.py (1)

71-74: Improved error handling for missing filesystems.

This change adds a null-check that prevents potential AttributeError exceptions when fs_block.filesystem is None. Using a conditional expression to fallback to an empty list is appropriate here.

supervisor/resolution/checks/supervisor_trust.py (1)

33-33: Good refactoring to use the dedicated method instead of direct assignment.

Changing from direct assignment to self.sys_resolution.unhealthy to using the add_unhealthy_reason method is a better approach, as it allows accumulating multiple reasons rather than replacing the existing value.

supervisor/addons/manager.py (2)

197-197: Good addition of Job decorator for better tracking.

Adding the job decorator to the uninstall method provides better management, tracking, and potentially cancellation capabilities for uninstall operations. This is consistent with other operations like install, update, and rebuild.


317-317: Type annotation improved to represent possible states.

The updated type annotation bool | None more accurately represents the possible states of the variable, even though the current initialization is False. This improves type safety and code readability.

supervisor/auth.py (1)

71-73: Improved type annotation to match actual function behavior.

The parameter types have been updated to correctly reflect that both username and password can be None. This is important for mypy type checking and matches the existing error handling logic at line 75 that already checks for None password.

supervisor/utils/systemd_journal.py (1)

64-64: Return type signature improved for clarity and type safety

The return type annotation has been updated to better reflect the actual values yielded by this generator. The function yields tuples with both the cursor and formatted entry, which is now properly documented in the type signature.

supervisor/host/apparmor.py (3)

93-95: Improved error handling with structured approach

Replacing direct assignment to unhealthy with add_unhealthy_reason allows for tracking multiple issues rather than just a binary unhealthy state, providing better diagnostics and resolving capabilities.


120-122: Consistent structured error handling

The approach of using add_unhealthy_reason is consistently applied here, improving error tracking capabilities.


138-140: Maintaining systematic error handling

The same pattern of structured error handling is applied here, completing the consistent approach throughout the file.

supervisor/addons/model.py (2)

297-297: Better property naming for improved clarity

Renaming from watchdog to watchdog_url clarifies that this property returns a URL string, not a boolean or other watchdog-related object.


609-609: Fixed type annotation with proper capitalization

Updated the type hint to use proper Any from typing module rather than lowercase any, which isn't a valid type annotation. This ensures mypy will correctly process this type hint.

supervisor/api/mounts.py (6)

3-3: Added cast for proper type handling

Added the cast function import from the typing module to enable explicit type casting of validated request data to MountData.


13-13: Imported MountData type for better type annotations

Added the import of MountData type to improve type checking when validating request data.


29-29: Added default value for safer error handling

Added default empty string when getting the mount name from request match info, preventing potential KeyError exceptions if the key is missing.


74-74: Added explicit type cast for improved type safety

Using cast() ensures that mypy correctly understands that body is of type MountData after validation, improving type checking throughout the function.


76-77: Consistent key access for mount name

Changed from using the ATTR_NAME constant to using the string literal "name" directly, ensuring consistent access to the name field in the validated data.


100-103: Added explicit type cast with improved formatting

The type cast to MountData ensures mypy understands the type of body after validation, maintaining type safety throughout the function.

supervisor/api/jobs.py (2)

29-29: Good defensive programming.

Adding a default empty string when getting UUID from match_info prevents potential NoneType errors in the get_job method if the UUID is missing.


72-78: Good defensive programming.

Using .get(current_job.uuid, []) instead of just .get(current_job.uuid) prevents potential NoneType errors by ensuring an empty list is returned when no jobs are associated with the current job's UUID.

supervisor/addons/options.py (4)

140-140: Good type annotation addition.

Adding the dict[str, Any] type annotation for range_args helps with type checking and code clarity.


393-398: Good type annotation improvement.

Updating the type annotation for ui_node to dict[str, Any] properly represents that the dictionary can contain values of different types, not just strings.


400-400: Good type annotation addition.

Adding the list[dict[str, Any]] type annotation for nested_schema helps with type checking and code clarity.


416-416: Good type annotation addition.

Adding the dict[str, Any] type annotation for clean_filter helps with type checking and code clarity.

supervisor/api/auth.py (3)

4-4: Good import addition for typing.

Adding the Awaitable import from collections.abc supports the return type annotations in the methods below.


46-46: Correct return type annotation.

The method returns self.sys_auth.check_login() which is a coroutine, so changing the return type from bool to Awaitable[bool] is correct. This also matches how the method is used on line 76 with await self._process_basic().


55-57: Correct return type annotation.

The method returns self.sys_auth.check_login() which is a coroutine, so changing the return type from bool to Awaitable[bool] is correct. This also matches how the method is used on lines 83 and 88 with await self._process_dict().

supervisor/api/proxy.py (5)

4-4: Good import addition for typing.

Adding the AsyncIterator import from collections.abc supports the return type annotation in the _api_client method.


44-44: Good defensive programming.

Adding a default empty string when getting the supervisor token prevents potential NoneType errors if the HEADER_HA_ACCESS header is missing.


58-60: Improved method signature with explicit typing.

The updated signature properly indicates that timeout can be either an int or None, and that the method returns an AsyncIterator of ClientResponse objects. This provides better type safety and documentation.


99-99: Good defensive programming.

Adding a default empty string when getting the content type prevents potential NoneType errors if the CONTENT_TYPE header is missing.


187-198: Improved code readability with match statement.

Replacing the if-elif-else chain with a Python 3.10+ match statement makes the code more readable and maintainable. The exhaustive case handling with proper error raising for unsupported types is a good practice.

supervisor/api/network.py (5)

135-140: Improved robustness with null-safety checks

The conditional expressions ensure that ipconfig_struct is only called when both the IP configuration and its settings exist, preventing potential null reference errors during serialization.


197-197: Enhanced parameter safety with default values

Adding a default empty string to match_info.get() ensures the method never passes None to _get_interface, improving type safety.


204-204: Enhanced parameter safety with default values

Same improvement as in the interface_info method - adding default empty string to prevent None values.


250-250: Enhanced parameter safety with default values

Same pattern applied consistently across all methods that call _get_interface.


263-266: Added validation for VLAN parameter

This validation check prevents invalid VLAN numbers, enhancing the robustness of the API by failing early with a clear error message instead of potentially propagating invalid values.

supervisor/api/ingress.py (5)

86-86: Enhanced parameter safety with default values

Using an empty string as default prevents None values when the token isn't present in the request's match info.


135-135: Updated return type annotation to match implementation

The return type has been updated from dict[str, Any] to None to accurately reflect that this method doesn't return a value, improving type correctness.


150-150: Enhanced parameter safety with default values

Using an empty string as default for the session cookie ensures consistent handling when the cookie is missing.


157-157: Enhanced parameter safety with default values

Consistent use of the default value pattern for path parameters.


186-186: Improved type consistency for protocol handling

Changed the initialization of req_protocols to use an empty list instead of what was likely a tuple, ensuring consistent typing throughout the method.

supervisor/homeassistant/api.py (2)

4-5: Updated imports for better type handling

Changed imports to support the updated type annotations in the make_request method. Added AsyncIterator and MultiMapping to properly type the method parameters and return value.

Also applies to: 14-14


89-92: Enhanced type annotations for make_request method

Improved type safety through several changes:

  1. Changed timeout from int to int | None to explicitly allow None values
  2. Updated params from dict[str, str] | None to MultiMapping[str] | None for more flexible parameter mapping
  3. Changed return type from AbstractAsyncContextManager[aiohttp.ClientResponse] to AsyncIterator[aiohttp.ClientResponse] to better match the actual implementation

These changes provide more precise type information for mypy validation.

supervisor/api/middleware/security.py (3)

3-3: Corrected imports and fixed function name typo

The changes improve code correctness by:

  1. Adding specific import for Callable from collections.abc
  2. Importing necessary types directly from aiohttp.web
  3. Fixing the typo in the function name from excract_supervisor_token to extract_supervisor_token

Also applies to: 9-9, 27-27


183-183: Updated handler parameter types for middleware methods

Changed the type annotation for handler from RequestHandler to Callable in multiple middleware methods, providing more flexibility for handler implementations while maintaining type safety.

Also applies to: 201-201, 215-215, 286-286


217-218: Added type annotation for request_from variable

Added an explicit type annotation for the request_from variable as CoreSysAttributes | None, improving type clarity and consistency.

supervisor/api/backups.py (7)

191-191: Method renamed for clarity and Python naming best practices.

The method has been renamed from list to list_backups. This is a good change as it avoids potential confusion with Python's built-in list type and more clearly communicates the method's purpose.


299-304: Type casting added to ensure type safety with job scheduling.

Adding explicit type casting with cast() ensures the correct types are used in type checking and helps mypy identify potential issues. This promotes type safety and clearer code.


501-504: Added type casting to ensure type safety for location validation.

The cast to list[str | None] ensures type compatibility with the _validate_cloud_backup_location method. This change improves type safety for the validation function.


515-515: Type casting added to clarify Mount type access.

Adding cast(Mount, location) ensures that the .local_where attribute is safely accessed after type checking. This improves type safety when working with different location types.


546-548: Added explicit type check to prevent processing invalid uploads.

This change adds a critical validation to ensure the uploaded content is of the expected type before processing. This helps prevent errors from incorrectly formatted API requests.


551-554: Added type casting for file operations to ensure type safety.

The explicit casting of backup_file_stream to IOBase ensures proper type checking when accessing write and close methods. This makes the code more robust when handling file operations.


569-571: Replaced direct state modification with method call for better encapsulation.

Changed from directly setting unhealthy state to using the add_unhealthy_reason method. This is a good practice as it encapsulates state management logic within the appropriate method.

supervisor/coresys.py (3)

809-811: Simplified method signature for more flexible argument passing.

Removed explicit type annotations for *args and **kwargs, which allows for more flexible argument passing. This is in line with Python's dynamic typing approach and makes the method more adaptable.


819-825: Simplified method signature for more flexible argument passing.

Removed explicit type annotations for *args and **kwargs in the sys_call_later method. This change makes the method signature more flexible and is consistent with the changes to other methods.


829-835: Simplified method signature for more flexible argument passing.

Removed explicit type annotations for *args and **kwargs in the sys_call_at method. This change makes the method signature more flexible and is consistent with the changes to other methods.

supervisor/api/utils.py (6)

32-32: Fixed function name typo for better code clarity.

Corrected the function name from excract_supervisor_token to extract_supervisor_token, fixing a typo. This improves code readability and ensures consistent naming.


61-63: Added type annotations for improved type checking.

Added explicit type annotations for the api parameter and return type, specifying api as CoreSysAttributes and return type as web.Response | web.StreamResponse. This enhances type safety and code clarity.


90-90: Added type annotation for parameter in wrapped API function.

Added explicit type annotation for the api parameter as CoreSysAttributes, improving type safety and making the expected parameter type clear to callers.


107-109: Added type annotations for improved type checking.

Added explicit type annotations for the api parameter and return type, consistent with other similar functions in the file. This enhances type safety and documentation.


172-172: Enhanced type flexibility for the data parameter.

Modified the type annotation to allow both dictionary and list types for the data parameter. This provides more flexibility in the types of data that can be returned while maintaining type safety.


181-181: Expanded schema type annotation for more flexible validation.

Added support for vol.All in the schema parameter type annotation, allowing for more flexible schema validation. This change accommodates different validation approaches.

supervisor/api/store.py (7)

96-96: Added default value for improved robustness.

Added a default empty string when retrieving addon_slug from request match info. This prevents potential None values and ensures consistent type handling.


105-105: Added type casting for safer type handling.

Added explicit type casting to Addon to ensure proper type checking when accessing addon_store attribute. This improves type safety when working with addon objects.


114-114: Added default value for improved robustness.

Added a default empty string when retrieving repository_slug from request match info. This prevents potential None values and improves code resilience.


129-132: Added type casting for clearer type handling in conditional assignment.

Added explicit type casting to Addon when retrieving an addon by slug. This ensures proper type checking while maintaining the conditional logic.


149-149: Simplified conditional logic for better readability.

Improved the expression for determining ATTR_UPDATE_AVAILABLE by using a concise conditional expression. This makes the code more readable while preserving the same behavior.


152-152: Simplified conditional logic for better readability.

Improved the expression for determining ATTR_VERSION by using a concise conditional expression. This makes the code more readable while preserving the same behavior.


249-249: Added type casting for improved type safety.

Added explicit type casting to AddonStore after extracting the addon. This ensures proper type checking and clarity about the expected object type.

supervisor/docker/interface.py (1)

56-56: Great enhancement to type safety.

Adding explicit type annotation to MAP_ARCH will help mypy verify correct usage of this dictionary and improve code readability.

supervisor/api/audio.py (3)

127-127: Improved parameter handling with default value.

Adding a default empty string prevents potential None values being passed to StreamType(), which could cause runtime errors. The type annotation also enhances type safety.


140-140: Consistent parameter handling with default value.

Similar improvement as in the set_volume method, ensuring source is always a string before being passed to StreamType().


153-153: Consistent parameter handling with default value.

Same improvement as in the previous methods, ensuring type safety and preventing potential None values.

supervisor/api/services.py (1)

28-28:

❓ Verification inconclusive

Excellent rename to avoid shadowing Python built-in.

Renaming the method from list to list_services avoids shadowing the built-in list type and makes the method's purpose more explicit.


🏁 Script executed:

#!/bin/bash
# Check if all references to the renamed method have been updated
rg -A 2 "api_services\.list\(" --glob "*.py"

Length of output: 46


Action Required: Verify Manual References to the Updated Method Name

The renaming of the method to list_services in supervisor/api/services.py (line 28) is excellent as it avoids shadowing Python's built-in list and clarifies the method's purpose. However, the automated search (rg -A 2 "api_services\.list\(") produced no output, which might indicate that no lingering calls to the old name exist—but the absence of output also raises concerns about the search’s coverage. Please manually verify that all references have been correctly updated across the repository.

  • Location: supervisor/api/services.py (line 28: async def list_services(self, request):)
  • Action: Manually check the codebase for any instances of list used on api_services to ensure the old method is not referenced.
supervisor/store/data.py (1)

182-184: Good refactoring to use method call instead of direct assignment.

Using add_unhealthy_reason() method instead of directly assigning to the property is a better approach as it encapsulates the logic and provides a consistent interface for setting unhealthy reasons throughout the codebase.

supervisor/resolution/evaluations/source_mods.py (1)

54-56: Improved error handling with proper method call

This change properly replaces direct attribute assignment with a method call to add_unhealthy_reason(), which follows better encapsulation principles. This is a good improvement for type safety and is aligned with the PR goal of enabling mypy.

supervisor/hardware/monitor.py (1)

43-43: Properly encapsulating unhealthy state management

Good refactoring to replace direct property assignment with a method call. This change enhances type safety and encapsulation, which aligns with enabling mypy in the codebase.

tests/resolution/fixup/test_fixup.py (1)

31-33: Improved test structure with proper method call

The modification correctly updates the test to use add_suggestion() rather than directly assigning to the suggestions property. This improves encapsulation and makes the test more robust against internal implementation changes.

supervisor/os/manager.py (1)

240-242: Enhanced error handling through proper method usage

This change correctly replaces direct property assignment with a method call to add_unhealthy_reason(). This follows the same pattern seen in other files, providing better encapsulation and type safety for mypy.

tests/jobs/test_job_decorator.py (1)

53-53: Method call replaces direct property assignment for improved type safety

The code now uses add_unhealthy_reason() instead of directly assigning to the unhealthy property. This method likely provides better encapsulation and allows for more structured handling of unhealthy states, supporting multiple reasons simultaneously.

supervisor/resolution/evaluations/container.py (1)

104-104: Method call replaces direct property assignment for improved type safety

The code now uses add_unhealthy_reason() instead of directly assigning to the unhealthy property. This method likely provides better type handling, validation, and potentially allows tracking multiple unhealthy reasons simultaneously.

supervisor/resolution/evaluations/base.py (1)

26-26: Method call replaces direct property assignment for improved type safety

The code now uses add_unsupported_reason() instead of directly assigning to the unsupported property. This provides better encapsulation and aligns with the pattern seen in other resolution-related classes where direct property assignments are replaced with method calls.

supervisor/resolution/evaluate.py (1)

70-70: Method call replaces direct property assignment for improved type safety

Changed from directly setting the unhealthy property to using the add_unhealthy_reason() method. This is consistent with similar changes in other files and improves type safety while potentially allowing for more sophisticated handling of multiple unhealthy reasons.

supervisor/addons/build.py (4)

7-7: Type import enhancement

The addition of Any from typing improves the code's type annotation capabilities for the dict in get_docker_args.


26-26: Import path refinement

Changing the import source of AnyAddon from relative . to more specific .manager improves code clarity and organization.


129-129: Dict type annotation added

Adding the explicit type annotation dict[str, Any] to the args variable improves code clarity and enables better static type checking.


66-66:

❓ Verification inconclusive

Architecture matching parameter update

Changed self.sys_arch.match to accept a list of architectures rather than a single value. This aligns with mypy type checking requirements and ensures that the match function receives the expected parameter type.


🏁 Script executed:

#!/bin/bash
# Verify the sys_arch.match method signature and usage pattern

# Check definition of the match method
rg -A 5 "def match" | grep -A 10 "sys_arch"

Length of output: 43


Please manually verify the updated architecture matching parameter

The change in supervisor/addons/build.py—updating the call to

return self.sys_arch.match([self.addon.arch])

—is intended to ensure that the match method receives a list of architectures (as required by mypy type checking). However, our initial automated search for the definition of sys_arch.match did not yield any output. Please manually confirm that the match method’s signature indeed expects a list rather than a single value.

Action items:

  • Verify the definition of sys_arch.match (possibly in its module, e.g., supervisor/sys_arch.py) to ensure it accepts a list.
  • Confirm that all consumers of sys_arch.match are updated accordingly to match the new parameter requirement.
supervisor/plugins/audio.py (2)

97-99: Improved unhealthy state management

Changed from direct assignment to a method call for adding unhealthy reasons. This encapsulates the state change logic and provides a single point of control for managing system health.


116-118: Consistent unhealthy state management

Similar to the previous change, this updates the error handling to use the add_unhealthy_reason method instead of direct assignment, maintaining consistency with the system health management pattern.

supervisor/api/supervisor.py (2)

214-214: Return type generalization

Changed return type from Awaitable[None] to the more general Awaitable, which is more accurate as the method now returns an awaitable that resolves to the result of asyncio.gather().


216-220: Simplified asynchronous operation

Replaced previous implementation with a cleaner approach using asyncio.gather() to run multiple coroutines concurrently, with each protected from cancellation using asyncio.shield(). This reduces code complexity while maintaining the same functionality.

supervisor/api/host.py (5)

6-6: Added typing import

The addition of Any from typing module enables proper type annotations in the file.


199-199: Type annotation added to params dictionary

Adding explicit type annotation dict[str, Any] for the params variable improves code clarity and enables better static type checking.


203-203: Defensive dictionary access

Changed from direct dictionary access request.match_info[IDENTIFIER] to .get() method with a default empty string. This prevents KeyError exceptions when the identifier is not present in the match info.


211-211: Consistent defensive dictionary access

Similar to the previous change, this uses the .get() method with a default empty string when accessing the BOOTID key, preventing potential KeyError exceptions.


245-245: Defensive headers access

Using the .get() method with a default empty string when accessing the RANGE header ensures that the code won't raise exceptions if the header is missing.

supervisor/supervisor.py (1)

177-179: Improved error handling with method-based approach

The change from directly setting the unhealthy reason to using the add_unhealthy_reason() method is a better approach that likely allows for maintaining multiple unhealthy reasons simultaneously rather than overwriting a previous state.

tests/resolution/fixup/test_system_clear_full_backup.py (1)

20-22: Enhanced encapsulation with method-based suggestion management

Replacing direct assignment with the add_suggestion() method improves type safety and encapsulation by properly managing the addition of suggestions through a dedicated API rather than directly manipulating the underlying collection.

tests/resolution/fixup/test_system_create_full_backup.py (1)

20-22: Enhanced encapsulation with method-based suggestion management

Using the add_suggestion() method instead of direct assignment improves type safety and encapsulation, consistent with the mypy enablement objective of this PR.

tests/resolution/fixup/test_system_execute_integrity.py (2)

25-28: Improved state management with method-based approach

Using add_suggestion() and add_issue() methods instead of direct assignments enhances type safety and provides better encapsulation of the resolution system's state management.


51-54: Consistent method-based state management

This change maintains consistency with the pattern established earlier in the file, using method calls instead of direct property assignments for better type safety and encapsulation.

tests/resolution/fixup/test_system_execute_reboot.py (1)

23-26: Improved encapsulation with method calls instead of direct assignment

The refactoring from direct assignment to method calls improves encapsulation and will provide better type checking support for mypy, which aligns with the PR's goal of enabling mypy. This change follows a consistent pattern applied across the codebase.

supervisor/backups/manager.py (4)

199-201: Improved encapsulation for unhealthy reason management

Refactoring from direct assignment to using the add_unhealthy_reason method improves type safety and encapsulation. This is consistent with the PR's mypy enablement goals.


355-357: Consistent pattern for managing unhealthy states

This refactoring follows the same pattern as other changes in this file, using the add_unhealthy_reason method instead of direct assignment.


411-413: Consistent unhealthy reason management

This change maintains consistency with the other similar changes in this file and across the codebase.


454-456: Consistent use of add_unhealthy_reason method

The consistent application of this pattern across all error handlers in this file shows a systematic approach to improving type safety.

tests/resolution/fixup/test_addon_execute_remove.py (1)

18-31: Improved encapsulation with method calls for suggestion and issue management

Refactoring from direct assignment to method calls (add_suggestion and add_issue) enhances type safety and encapsulation. The indentation and formatting also improves readability.

tests/resolution/fixup/test_store_execute_remove.py (1)

19-28: Consistent pattern for managing suggestions and issues

This change follows the same pattern as seen in other test files, using method calls instead of direct assignment for better type safety and encapsulation.

supervisor/core.py (2)

117-117: Good refactoring to use add_unhealthy_reason method

This change improves code encapsulation by using the dedicated method rather than directly assigning to the unhealthy state. This approach allows for better tracking of multiple unhealthy reasons simultaneously.


180-180: Good refactoring to use add_unhealthy_reason method

Similar to the previous instance, this change properly uses the dedicated method instead of direct assignment to manage unhealthy states during setup errors.

tests/resolution/fixup/test_store_execute_reset.py (2)

21-23: Good refactoring to use add_suggestion method

This change properly updates the test to use the new method-based approach for adding suggestions rather than direct assignment. This maintains better encapsulation and is more type-safe.


24-26: Good refactoring to use add_issue method

Similar to the suggestion change, this refactoring properly updates the test to use the dedicated method for adding issues. This is consistent with the overall refactoring approach across the codebase.

tests/resolution/fixup/test_store_execute_reload.py (2)

18-20: Good refactoring to use add_suggestion method

This change properly updates the test to use the new method-based approach for adding suggestions, consistent with the changes in other test files.


21-23: Good refactoring to use add_issue method

This refactoring properly updates the test to use the dedicated method for adding issues, maintaining consistency across the codebase.

tests/misc/test_filter_data.py (2)

99-99: Good refactoring to use add_unsupported_reason method

This change improves the test by using the dedicated method rather than direct assignment to the unsupported state.


218-218: Good refactoring to use add_unhealthy_reason method

This change properly updates the test to use the dedicated method for adding unhealthy reasons, consistent with the overall refactoring pattern.

tests/resolution/fixup/test_system_adopt_data_disk.py (8)

88-92: Good refactoring to use method calls rather than direct assignment.

Converting direct assignments to method calls improves encapsulation and type safety, which aligns with the mypy enablement objective.


93-95: Appropriate use of add_issue method.

The switch from direct property assignment to the method call pattern is consistent with good OOP practices and improves code maintainability.


129-133: Consistent application of encapsulation pattern.

Good consistency in applying the same method-based approach across multiple test functions.


134-136: Well-executed refactoring for issue handling.

The refactoring maintains the same functionality while improving code structure.


166-170: Consistent pattern application throughout the file.

The systematic replacement of direct property assignments with method calls enhances type safety.


171-173: Proper encapsulation of issue addition.

This change follows the same pattern established throughout the file, maintaining consistency.


218-222: Appropriate use of method encapsulation pattern in final test case.

The consistent application of the new pattern makes the code more maintainable and type-safe.


223-225: Consistent implementation of the add_issue pattern.

This final instance completes the consistent refactoring throughout the test file.

supervisor/plugins/dns.py (4)

159-162: Good refactoring of error handling for improved type safety.

Replacing direct assignment to unhealthy with the add_unhealthy_reason method call improves encapsulation and makes the code more mypy-friendly.


170-173: Consistent application of the unhealthy reason pattern.

This change follows the same pattern established earlier in the file, maintaining consistency in error handling.


350-353: Proper error handling pattern in write_hosts method.

The consistent use of add_unhealthy_reason rather than direct assignment improves encapsulation and type safety.


441-444: Consistent implementation of error handling pattern.

The final instance maintains the same error handling pattern throughout the file, enhancing code maintainability.

tests/resolution/fixup/test_system_rename_data_disk.py (6)

46-50: Well-implemented method-based approach for suggestion handling.

Replacing direct assignment with the add_suggestion method call improves encapsulation and type safety.


51-53: Good refactoring for issue handling.

The switch to add_issue follows proper OOP practices and will help with mypy type checking.


78-82: Consistent application of suggestion handling pattern.

The refactoring maintains a consistent approach across different test functions.


83-85: Proper issue handling consistent with the established pattern.

This change follows the same pattern established earlier in the file.


105-109: Maintains consistency in the final test function.

The same pattern is correctly applied to the final test function, ensuring consistent code structure.


110-112: Clean implementation of the issue handling pattern.

The consistent application of add_issue completes the refactoring of the test file.

tests/api/test_resolution.py (7)

30-33: Good refactoring to use dedicated methods for resolution management.

Converting direct assignments to method calls (add_unsupported_reason, add_suggestion) improves encapsulation and type safety.


50-52: Well-structured variable assignment in method call.

The assignment of the returned suggestion to a variable (clear_backup :=) is done cleanly within the method call.


64-71: Good implementation of multiple suggestion additions.

The consistent use of add_suggestion with variable assignments maintains clean code structure and improves type safety.


94-96: Proper implementation of issue handling with assignment.

The variable assignment within the method call pattern is consistent with earlier examples.


106-107: Effective use of unhealthy reason handling method.

The switch to add_unhealthy_reason maintains the same encapsulation pattern seen throughout the PR.


147-149: Consistent implementation of issue handling pattern.

The method-based approach with variable assignment is maintained consistently.


156-165: Well-structured implementation of multiple suggestion additions.

The consistent pattern of adding suggestions via method calls with variable assignments maintains clean code structure throughout the test file.

supervisor/api/addons.py (6)

145-150: Good addition of TypedDict for improved type safety.

Adding the OptionsValidateResponse TypedDict provides explicit typing for the API response structure, which will improve code readability and help catch potential type errors during development.


158-158: Good defensive programming to prevent None values.

Using an empty string as default value for addon_slug instead of potentially returning None helps prevent potential NoneType errors in downstream code.


176-176: Improved method naming for clarity.

Renaming list to list_addons makes the method name more descriptive and avoids potential confusion with Python's built-in list function. This change aligns with the naming conventions seen in other modules.


346-346: Enhanced return type annotations.

The method now correctly specifies its return type as OptionsValidateResponse instead of None, which improves type-safety and makes the function's contract clearer.


349-350: Improved response initialization using TypedDict.

Using the TypedDict constructor to initialize the response with default values ensures the response has the correct structure and all required fields are present.


358-381: Direct dictionary access is clear and consistent.

Using direct string keys in dictionary operations rather than constants makes the code more readable. The conditions for setting validity based on pwned status are now easier to follow.

supervisor/addons/addon.py (6)

319-319: Enhanced type safety with AwesomeVersion.

Changed return types from str | None to AwesomeVersion for version-related properties to ensure consistent version handling throughout the codebase.

Also applies to: 467-468


677-678: Improved URL validation in watchdog_application.

Enhanced validation of watchdog URLs by properly checking both conditions before proceeding. This prevents potential errors when working with invalid URLs.


780-782: Added guard clause to prevent installation errors.

Adding an early check for addon_store availability before attempting installation prevents potential errors when trying to install an addon that doesn't exist in the store.


886-888: Consistent error handling for update operation.

Similar to the install method, this guard clause prevents update errors for addons missing from the store. This ensures consistent error handling across related operations.


945-947: Conditional update based on addon_store availability.

The rebuild method now checks if the addon_store is available before attempting to update from it. This prevents potential errors when working with addons that don't have a store reference.


1607-1609: Consistent path cache refresh logic.

Updated the path cache refresh logic to be consistent with other methods by checking both detached status and addon_store availability.

supervisor/resolution/module.py (3)

95-113: Improved method design with add_suggestion.

Replacing the setter with an explicit add_suggestion method is a better design that prevents accidental replacement of the entire collection. It also centralizes the duplicate checking and event notification logic.


119-127: Improved design for unsupported reason management.

The add_unsupported_reason method provides a more explicit and controlled way to manage unsupported reasons, with clear logic for avoiding duplicates and triggering appropriate notifications.


187-197: Improved issue handling.

Simplified the issue handling logic by moving the duplicate check, logging, and event notification directly into the add_issue method. This makes the code more maintainable and ensures consistent behavior when adding issues.

supervisor/api/__init__.py (4)

85-86: Improved initialization of api_host.

Directly initializing _api_host as an APIHost instance and setting its coresys attribute is cleaner than the previous approach of setting it to None and initializing it later.


527-527: Improved method naming in route registration.

Changed from api_addons.list to the more descriptive api_addons.list_addons, which aligns with the implementation in the addons.py file and avoids confusion with Python's built-in list function.


595-597: Enhanced flexibility for ingress handler.

Changed from web.view to web.route(hdrs.METH_ANY, ...) to explicitly specify that any HTTP method is allowed. This improves code clarity and makes the API's behavior more explicit.


635-635: Consistent method naming improvements.

Renamed endpoint handlers from general list to more specific list_services and list_discovery, improving clarity and consistency with the rest of the codebase.

Also applies to: 649-649

tests/resolution/test_resolution_manager.py (15)

25-25: Method-based approach for adding unsupported reasons

The code has been updated to use add_unsupported_reason() instead of direct property assignment. This change improves encapsulation and is part of a larger refactoring to use methods for state management.


33-33: Method-based approach for adding unhealthy reasons

Similar to the unsupported reasons change, this uses add_unhealthy_reason() instead of direct property assignment, improving encapsulation.


40-42: Updated suggestion creation to use method-based approach

The code now uses add_suggestion() with the walrus operator to both create and add the suggestion in a single expression, replacing direct property assignment.


55-62: Structured suggestion creation for multiple suggestions

Using the add_suggestion() method with the walrus operator for multiple suggestions improves code consistency and maintainability.


85-87: Method-based approach for adding issues

Using add_issue() instead of direct property assignment is consistent with the other state management improvements in this file.


118-118: Consistent usage of add_unsupported_reason

The change to use add_unsupported_reason() is applied consistently throughout the test file.


129-133: Method-based issue creation with improved readability

The walrus operator combined with add_issue() creates cleaner code while maintaining the ability to reference the created issue.


136-141: Consistent method usage for unrelated suggestions

These changes continue the pattern of using add_suggestion() instead of direct assignment, maintaining consistency throughout the codebase.


146-155: Method-based creation for related suggestions

Continues the consistent pattern of using add_suggestion() for creating and storing suggestions.


172-175: Improved issue management with method-based approach

Using add_issue() for both single-line and multi-line issue creation improves code consistency.


180-187: Consistent method-based approach for related issues

The use of add_issue() with the walrus operator continues the pattern throughout the test file.


241-245: Method-based suggestion creation in event tests

Consistent application of the method-based approach for suggestion management in the event-related tests.


287-301: Method-based approach in multiple suggestion tests

The refactoring to use add_suggestion() is applied consistently across the test file, even in complex test scenarios with multiple suggestions.


317-317: Consistent unsupported reason management in event tests

All instances of unsupported reason management have been updated to use the method-based approach, maintaining consistency throughout the test file.

Also applies to: 329-329, 335-335


381-381: Method-based unhealthy reason management in event tests

The refactoring to use add_unhealthy_reason() has been applied consistently throughout the unhealthy state tests.

Also applies to: 393-393, 399-399

supervisor/api/discovery.py (11)

4-4: Added cast for type safety

Added cast import from typing module, which will be used later for proper type handling.


6-6: Improved import statement

Updated the import style for web from aiohttp to be more explicit, which is good for readability and maintainability.


21-21: Direct Message type import

Now directly importing the Message type from the discovery module, making the code more explicit about its dependencies.


38-38: Added type annotations to _extract_message

Improved method signature with proper type annotations, specifying that it takes a web.Request and returns a Message object.


40-40: Minor code consistency improvement

Updated the variable name matching pattern to be more explicit, though the functionality remains the same.


47-47: Renamed method and added type annotations

Changed list to list_discovery to avoid conflict with Python's built-in list type and added proper return type annotation.


58-64: Enhanced type safety with cast

Improved the condition in the list comprehension to use cast for ensuring proper type safety when checking the addon state.


67-67: Added type annotation for services variable

Explicitly defined the type of services as dict[str, list[str]], improving code readability and type safety.


75-75: Added return type annotation to set_discovery

Added proper return type annotation to the set_discovery method, specifying it returns a dict[str, str].


99-99: Added return type annotation to get_discovery

Added proper return type annotation to the get_discovery method, specifying it returns a dict[str, Any].


111-111: Changed return type and removed return statement

Updated the del_discovery method to specify it returns None and removed an unnecessary return statement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla-signed refactor A code change that neither fixes a bug nor adds a feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant