tests: add type annotations to top-level test files#1688
Open
ZeliardM wants to merge 6 commits intopython-kasa:masterfrom
Open
tests: add type annotations to top-level test files#1688ZeliardM wants to merge 6 commits intopython-kasa:masterfrom
ZeliardM wants to merge 6 commits intopython-kasa:masterfrom
Conversation
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
There was a problem hiding this comment.
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.,
Noneassertions,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_valuetypesvalueasdict, but the call site passessection_valuefrom 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
This was referenced Apr 7, 2026
…ions # Conflicts: # tests/test_device.py
…pe-annotations # Conflicts: # tests/conftest.py
8c71f8a to
49065a2
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add type annotations (parameter types and
-> Nonereturn 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
-> Nonereturn types on void test functions (only on functions that don't return values or yield)dev: Device,mocker: MockerFixture,runner: CliRunner, etc.MockerFixture,Module,URL,SmartProtocol, etc.Pre-existing type issues fixed (exposed by new annotations)
isinstancenarrowing forDevice | Moduleunion types in test_feature.pyNone-safety assertions for optional values (alias,encrypt_type, etc.)encrypt_typeisNone(SMARTCAM fixtures)int-to-strin CLI argument lists (--discovery-timeout 0→"0")castfor intentional type mismatches in serialization testsmodule.__package__ is not Noneguard in test_device.pyPre-existing bugs fixed
_mock_response.read()return type fromNonetobytesin test_httpclient.pyfakeprotocol_smart._edit_preset_rules:"states" not in info[...] is Nonealways evaluated false due to Python's chained comparison semantics; replaced with.get("states") is NoneAnnotations intentionally omitted
devparameter intest_command_with_child(uses dynamicdev.__class__as base class)devparameter intest_all_binary_states(skipped test using strip-specificis_on.items()API)Out of scope
aiohttp.ClientSession()intest_discover_try_connect_allis handled by PR tests: centralize transport and session cleanup in conftest #1683 (centralized session cleanup fixture)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.pyMerge order
This is PR 9 of 9 in the test modernization series. Must merge last — has file overlaps with #1677 and #1683.
Verification