Skip to content

tests: add type annotations to top-level test files#1688

Open
ZeliardM wants to merge 6 commits intopython-kasa:masterfrom
ZeliardM:tests/toplevel-type-annotations
Open

tests: add type annotations to top-level test files#1688
ZeliardM wants to merge 6 commits intopython-kasa:masterfrom
ZeliardM:tests/toplevel-type-annotations

Conversation

@ZeliardM
Copy link
Copy Markdown
Contributor

@ZeliardM ZeliardM commented Apr 7, 2026

Summary

Add type annotations (parameter types and -> None return types) to all top-level test functions across 22 test files. This enables mypy to check test function bodies, catching type errors that were previously hidden.

Type annotations added

  • -> None return types on void test functions (only on functions that don't return values or yield)
  • Parameter type annotations from common patterns: dev: Device, mocker: MockerFixture, runner: CliRunner, etc.
  • Missing imports for newly-used types: MockerFixture, Module, URL, SmartProtocol, etc.

Pre-existing type issues fixed (exposed by new annotations)

  • Use isinstance narrowing for Device | Module union types in test_feature.py
  • Add None-safety assertions for optional values (alias, encrypt_type, etc.)
  • Build CLI args conditionally when encrypt_type is None (SMARTCAM fixtures)
  • Fix int-to-str in CLI argument lists (--discovery-timeout 0"0")
  • Add explicit type annotations for variable assignments to avoid inference conflicts
  • Use cast for intentional type mismatches in serialization tests
  • Add module.__package__ is not None guard in test_device.py

Pre-existing bugs fixed

  • Fix _mock_response.read() return type from None to bytes in test_httpclient.py
  • Fix chained comparison bug in fakeprotocol_smart._edit_preset_rules: "states" not in info[...] is None always evaluated false due to Python's chained comparison semantics; replaced with .get("states") is None

Annotations intentionally omitted

  • dev parameter in test_command_with_child (uses dynamic dev.__class__ as base class)
  • dev parameter in test_all_binary_states (skipped test using strip-specific is_on.items() API)

Out of scope

Files changed (22)

tests/conftest.py, tests/device_fixtures.py, tests/discovery_fixtures.py, tests/fakeprotocol_iot.py, tests/fakeprotocol_smart.py, tests/fakeprotocol_smartcam.py, tests/fixtureinfo.py, tests/test_bulb.py, tests/test_childdevice.py, tests/test_cli.py, tests/test_common_modules.py, tests/test_device.py, tests/test_device_factory.py, tests/test_device_type.py, tests/test_deviceconfig.py, tests/test_devtools.py, tests/test_discovery.py, tests/test_feature.py, tests/test_httpclient.py, tests/test_plug.py, tests/test_readme_examples.py, tests/test_strip.py

Merge order

This is PR 9 of 9 in the test modernization series. Must merge last — has file overlaps with #1677 and #1683.

Order PR Scope
1 #1677 Tests: cleanup and fixes
2 #1681 CI: pin GitHub Actions to SHA
3 #1682 Docs: modernize docstrings
4 #1683 Tests: centralize session cleanup
5 #1684 Tests: transport type annotations
6 #1685 Tests: IoT type annotations
7 #1686 Tests: Smart type annotations
8 #1687 Tests: CLI/protocols/smartcam type annotations
9 #1688 Tests: top-level type annotations

Merge note: Two trivial context conflicts when merging after #1677 + #1683:

  1. tests/conftest.py: Keep tests: centralize transport and session cleanup in conftest #1683's _close_transport_and_http_sessions fixture and this PR's type annotation on load_fixture(foldername: str, filename: str)
  2. tests/test_device.py: Keep tests: fix typos, child device subtype, CLI patch path, and deprecation test logic #1677's will_warn = is_expected or attribute_name in deprecated_warns_before_attribute_error and this PR's type annotations + if is_expected and will_raise: condition

Verification

  • mypy: 0 errors across all 22 files
  • pre-commit: all hooks pass (ruff, ruff-format, mypy)
  • pytest: all test_cli.py tests pass (6,697 passed, 194 skipped)
  • Full test suite passes after sequential merge of all 9 PRs (10,656 passed, 194 skipped)

ZeliardM added 3 commits April 6, 2026 19:58
Add a single autouse fixture in tests/conftest.py that tracks all
BaseTransport and HttpClient instances via __init__ monkeypatching,
then closes them after each test.

Uses functools.wraps to preserve original __init__ signatures so
existing inspect-based tests continue to pass.
… test logic

- Fix CHANGELOG typo: valid_temperate_range -> valid_temperature_range
- Add plug.powerstrip.sub-bulb child device type mapping
- Narrow discover raw test to patch CLI-level redact path
- Fix deprecated attribute test logic for attrs that warn before raising
- Update supported_modules -> modules in discovery test
Add type annotations (parameter types and -> None return types) to all
top-level test functions across 22 test files. This enables mypy to check
test function bodies, catching type errors that were previously hidden.

Key changes:
- Add -> None return types to void test functions
- Add parameter type annotations (Device, MockerFixture, CliRunner, etc.)
- Add missing imports (MockerFixture, Module, URL, SmartProtocol, etc.)
- Fix pre-existing type issues exposed by the new annotations:
  - Use isinstance narrowing for Device | Module union types
  - Add None-safety assertions for optional values
  - Fix int-to-str in CLI argument lists
  - Add explicit type annotations for variable assignments
  - Use cast for intentional type mismatches in tests
- Remove dev: Device annotations from functions using dynamic class
  inheritance or strip-specific APIs incompatible with Device type
Copilot AI review requested due to automatic review settings April 7, 2026 03:20
Copy link
Copy Markdown

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 adds explicit type annotations to top-level test functions (and related helpers) across the test suite so mypy can type-check test bodies and surface previously-hidden type issues.

Changes:

  • Add parameter/return type annotations (-> None, MockerFixture, CliRunner, Device, etc.) across many tests and fixtures.
  • Apply small test-side fixes exposed by typing (e.g., None assertions, cast(...), and stringifying CLI args).
  • Refine some test helpers/fake protocols with additional typing and minor logic adjustments.

Reviewed changes

Copilot reviewed 22 out of 22 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/conftest.py Annotates common test helpers and pytest hooks to improve type checking.
tests/device_fixtures.py Adds typing to fixture utilities and the main dev fixture.
tests/discovery_fixtures.py Adds typing to discovery fixtures and patch helpers.
tests/fakeprotocol_iot.py Adds typing to fake IOT protocol/transport helpers.
tests/fakeprotocol_smart.py Adds typing to fake SMART protocol helpers and setters.
tests/fakeprotocol_smartcam.py Adds typing to fake SMARTCAM protocol/transport helpers.
tests/fixtureinfo.py Adds typing to fixture info utilities and fixture.
tests/test_bulb.py Adds -> None / parameter annotations to bulb tests.
tests/test_childdevice.py Adds -> None / parameter annotations to child-device tests.
tests/test_cli.py Adds typing to CLI tests and fixes a few typed CLI arg cases.
tests/test_common_modules.py Adds -> None / parameter annotations to common module tests.
tests/test_device.py Adds typing to device tests and helper utilities.
tests/test_device_factory.py Adds typing to factory/connect tests and adjusts http client access typing.
tests/test_device_type.py Adds -> None return annotation to the device type test.
tests/test_deviceconfig.py Adds typing to serialization/deserialization tests and uses cast where intentional.
tests/test_devtools.py Adds -> None / parameter annotations to devtools tests.
tests/test_discovery.py Adds -> None / parameter annotations to discovery tests and helper stubs.
tests/test_feature.py Adds typing and narrowing for feature tests (including union/container handling).
tests/test_httpclient.py Adds typing to http client tests and switches to yarl.URL for HttpClient.post.
tests/test_plug.py Adds -> None return annotations to plug tests.
tests/test_readme_examples.py Adds typing for doctest-driving tests and mocker usage.
tests/test_strip.py Adds typing and None-safety assertions for strip/children tests.
Comments suppressed due to low confidence (1)

tests/fakeprotocol_smartcam.py:140

  • FakeSmartCamTransport._get_param_set_value types value as dict, but the call site passes section_value from parsed request params, which can be non-dict values (e.g., bool/int/str). This annotation is too narrow; widen it (e.g., Any/object) or use a generic type variable that matches the actual setter values.
    @staticmethod
    def _get_param_set_value(info: dict, set_keys: list[str], value: dict) -> None:
        cifp = info.get(CHILD_INFO_FROM_PARENT)

        for key in set_keys[:-1]:
            info = info[key]
        info[set_keys[-1]] = value

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

- Fix test_credentials: build CLI args conditionally when encrypt_type
  is None (SMARTCAM fixtures have no encrypt_type)
- Add missing -> None to test_httpclient_errors, test_feature_value_container,
  test_discover_try_connect_all
- Fix _mock_response.read() return type from None to bytes
- Fix chained comparison bug in fakeprotocol_smart._edit_preset_rules:
  'not in ... is None' always evaluates false; use .get() instead
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 7, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.23%. Comparing base (76d9f68) to head (49065a2).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1688      +/-   ##
==========================================
+ Coverage   93.22%   93.23%   +0.01%     
==========================================
  Files         157      157              
  Lines        9815     9815              
  Branches     1003     1003              
==========================================
+ Hits         9150     9151       +1     
+ Misses        472      471       -1     
  Partials      193      193              

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ZeliardM ZeliardM force-pushed the tests/toplevel-type-annotations branch from 8c71f8a to 49065a2 Compare April 7, 2026 13:18
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.

2 participants