aiohomematic-test-support 2025.12.13__py3-none-any.whl → 2025.12.23__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -45,4 +45,4 @@ test dependencies to access test support functionality.
45
45
 
46
46
  from __future__ import annotations
47
47
 
48
- __version__ = "2025.12.13"
48
+ __version__ = "2025.12.23"
@@ -81,13 +81,13 @@ class FactoryWithClient:
81
81
  )
82
82
  self.system_event_mock = MagicMock()
83
83
  self.ha_event_mock = MagicMock()
84
- self._event_bus_unsubscribe_handlers: list[Callable[[], None]] = []
84
+ self._event_bus_unsubscribe_callbacks: list[Callable[[], None]] = []
85
85
 
86
86
  def cleanup_event_bus_subscriptions(self) -> None:
87
87
  """Clean up all event bus subscriptions."""
88
- for unsubscribe in self._event_bus_unsubscribe_handlers:
88
+ for unsubscribe in self._event_bus_unsubscribe_callbacks:
89
89
  unsubscribe()
90
- self._event_bus_unsubscribe_handlers.clear()
90
+ self._event_bus_unsubscribe_callbacks.clear()
91
91
 
92
92
  async def get_default_central(self, *, start: bool = True) -> CentralUnit:
93
93
  """Return a central based on give address_device_translation."""
@@ -146,12 +146,12 @@ class FactoryWithClient:
146
146
  """Handle homematic events."""
147
147
  self.ha_event_mock(event)
148
148
 
149
- self._event_bus_unsubscribe_handlers.append(
149
+ self._event_bus_unsubscribe_callbacks.append(
150
150
  central.event_bus.subscribe(
151
151
  event_type=BackendSystemEventData, event_key=None, handler=_system_event_handler
152
152
  )
153
153
  )
154
- self._event_bus_unsubscribe_handlers.append(
154
+ self._event_bus_unsubscribe_callbacks.append(
155
155
  central.event_bus.subscribe(event_type=HomematicEvent, event_key=None, handler=_ha_event_handler)
156
156
  )
157
157
 
@@ -37,6 +37,8 @@ from __future__ import annotations
37
37
 
38
38
  import asyncio
39
39
  from collections import defaultdict
40
+ from collections.abc import Callable
41
+ import contextlib
40
42
  import json
41
43
  import logging
42
44
  import os
@@ -52,7 +54,7 @@ from aiohomematic.client import BaseRpcProxy
52
54
  from aiohomematic.client.json_rpc import _JsonKey, _JsonRpcMethod
53
55
  from aiohomematic.client.rpc_proxy import _RpcMethod
54
56
  from aiohomematic.const import UTF_8, DataOperationResult, Parameter, ParamsetKey, RPCType
55
- from aiohomematic.store.persistent import _freeze_params, _unfreeze_params
57
+ from aiohomematic.store.persistent import _cleanup_params_for_session, _freeze_params, _unfreeze_params
56
58
  from aiohomematic_test_support import const
57
59
 
58
60
  _LOGGER = logging.getLogger(__name__)
@@ -277,6 +279,9 @@ def get_xml_rpc_proxy( # noqa: C901
277
279
  """Return the supported methods."""
278
280
  return self._supported_methods
279
281
 
282
+ def clear_connection_issue(self) -> None:
283
+ """Clear connection issue (no-op for test mock)."""
284
+
280
285
  async def clientServerInitialized(self, interface_id: str) -> None:
281
286
  """Answer clientServerInitialized with pong."""
282
287
  await self.ping(callerId=interface_id)
@@ -376,25 +381,175 @@ def get_xml_rpc_proxy( # noqa: C901
376
381
  return cast(BaseRpcProxy, _AioXmlRpcProxyFromSession())
377
382
 
378
383
 
384
+ def _get_instance_attributes(instance: Any) -> set[str]:
385
+ """
386
+ Get all instance attribute names, supporting both __dict__ and __slots__.
387
+
388
+ For classes with __slots__, iterates through the class hierarchy to collect
389
+ all slot names. For classes with __dict__, returns the keys of __dict__.
390
+ Handles hybrid classes that have both __slots__ and __dict__.
391
+
392
+ Why this is needed:
393
+ Python classes can store instance attributes in two ways:
394
+ 1. __dict__: A dictionary attached to each instance (default behavior)
395
+ 2. __slots__: Pre-declared attribute names stored more efficiently
396
+
397
+ When copying attributes to a mock, we can't just use instance.__dict__
398
+ because __slots__-based classes don't have __dict__ (or have a limited one).
399
+ We must inspect the class hierarchy to find all declared slots.
400
+
401
+ Algorithm:
402
+ 1. Walk the Method Resolution Order (MRO) to find all classes in hierarchy
403
+ 2. For each class with __slots__, collect slot names (skip internal ones)
404
+ 3. Verify each slot actually has a value on this instance (getattr check)
405
+ 4. Also collect any __dict__ attributes if the instance has __dict__
406
+ 5. Return the union of all found attribute names
407
+ """
408
+ attrs: set[str] = set()
409
+
410
+ # Walk the class hierarchy via MRO (Method Resolution Order).
411
+ # __slots__ are inherited but each class defines its own slots separately,
412
+ # so we must check every class in the hierarchy.
413
+ for cls in type(instance).__mro__:
414
+ if hasattr(cls, "__slots__"):
415
+ for slot in cls.__slots__:
416
+ # Skip internal slots like __dict__ and __weakref__ which are
417
+ # automatically added by Python when a class uses __slots__
418
+ if not slot.startswith("__"):
419
+ try:
420
+ # Only include if the attribute actually exists on the instance.
421
+ # Slots can be declared but unset (raises AttributeError).
422
+ getattr(instance, slot)
423
+ attrs.add(slot)
424
+ except AttributeError:
425
+ # Slot is declared but not initialized on this instance
426
+ pass
427
+
428
+ # Also include __dict__ attributes if the instance has __dict__.
429
+ # Some classes have both __slots__ and __dict__ (e.g., if a parent class
430
+ # doesn't use __slots__, or if __dict__ is explicitly in __slots__).
431
+ if hasattr(instance, "__dict__"):
432
+ attrs.update(instance.__dict__.keys())
433
+
434
+ return attrs
435
+
436
+
379
437
  def get_mock(
380
438
  *, instance: Any, exclude_methods: set[str] | None = None, include_properties: set[str] | None = None, **kwargs: Any
381
439
  ) -> Any:
382
- """Create a mock and copy instance attributes over mock."""
440
+ """
441
+ Create a mock that wraps an instance with proper property delegation.
442
+
443
+ Supports both __dict__-based and __slots__-based classes. Properties are
444
+ delegated dynamically to the wrapped instance to ensure current values
445
+ are always returned.
446
+
447
+ Problem solved:
448
+ MagicMock(wraps=instance) only delegates method calls, not property access.
449
+ When you access mock.some_property, MagicMock returns the value that was
450
+ captured at mock creation time, not the current value on the wrapped instance.
451
+ This causes test failures when the wrapped instance's state changes after
452
+ the mock is created (e.g., client.available changes from False to True
453
+ after initialize_proxy() is called).
454
+
455
+ Solution:
456
+ Create a dynamic MagicMock subclass with property descriptors that delegate
457
+ to the wrapped instance on every access. This ensures properties always
458
+ return current values.
459
+
460
+ Algorithm:
461
+ 1. If already a Mock, just sync attributes from wrapped instance
462
+ 2. Identify all properties on the instance's class
463
+ 3. Create a MagicMock subclass with delegating property descriptors
464
+ 4. Create mock instance with spec and wraps
465
+ 5. Copy instance attributes (supports both __slots__ and __dict__)
466
+ 6. Copy non-mockable methods directly to mock
467
+ """
383
468
  if exclude_methods is None:
384
469
  exclude_methods = set()
385
470
  if include_properties is None:
386
471
  include_properties = set()
387
472
 
473
+ # Early return: if already a Mock, just refresh attributes from wrapped instance
388
474
  if isinstance(instance, Mock):
389
- instance.__dict__.update(instance._mock_wraps.__dict__)
475
+ if hasattr(instance, "_mock_wraps") and instance._mock_wraps is not None:
476
+ for attr in _get_instance_attributes(instance._mock_wraps):
477
+ with contextlib.suppress(AttributeError, TypeError):
478
+ setattr(instance, attr, getattr(instance._mock_wraps, attr))
390
479
  return instance
391
- mock = MagicMock(spec=instance, wraps=instance, **kwargs)
392
- mock.__dict__.update(instance.__dict__)
480
+
481
+ # Step 1: Identify all @property decorated attributes on the class
482
+ # These need special handling because MagicMock doesn't delegate property access
483
+ property_names = _get_properties(data_object=instance, decorator=property)
484
+
485
+ # Step 2: Create a dynamic MagicMock subclass
486
+ # We add property descriptors to this subclass that delegate to _mock_wraps.
487
+ # This is the key technique: property descriptors on the class take precedence
488
+ # over MagicMock's attribute access, allowing us to intercept property reads.
489
+ class _DynamicMock(MagicMock):
490
+ pass
491
+
492
+ # Helper factory functions to create closures with correct name binding.
493
+ # Using a factory function ensures each property gets its own 'name' variable,
494
+ # avoiding the classic lambda closure bug where all properties would share
495
+ # the last loop value.
496
+ def _make_getter(name: str) -> Callable[[Any], Any]:
497
+ """Create a getter that delegates to the wrapped instance."""
498
+
499
+ def getter(self: Any) -> Any:
500
+ # Access _mock_wraps which holds the original instance
501
+ return getattr(self._mock_wraps, name)
502
+
503
+ return getter
504
+
505
+ def _make_setter(name: str) -> Callable[[Any, Any], None]:
506
+ """Create a setter that delegates to the wrapped instance."""
507
+
508
+ def setter(self: Any, value: Any) -> None:
509
+ setattr(self._mock_wraps, name, value)
510
+
511
+ return setter
512
+
513
+ # Step 3: Add property descriptors to the dynamic subclass
514
+ for prop_name in property_names:
515
+ # Skip properties that should be mocked or overridden via kwargs
516
+ if prop_name not in include_properties and prop_name not in kwargs:
517
+ # Check if the original property has a setter (is writable)
518
+ prop_descriptor = getattr(type(instance), prop_name, None)
519
+ if prop_descriptor is not None and getattr(prop_descriptor, "fset", None) is not None:
520
+ # Writable property: create descriptor with both getter and setter
521
+ setattr(
522
+ _DynamicMock,
523
+ prop_name,
524
+ property(_make_getter(prop_name), _make_setter(prop_name)),
525
+ )
526
+ else:
527
+ # Read-only property: create descriptor with getter only
528
+ setattr(
529
+ _DynamicMock,
530
+ prop_name,
531
+ property(_make_getter(prop_name)),
532
+ )
533
+
534
+ # Step 4: Create the mock instance
535
+ # spec=instance: ensures mock only allows access to attributes that exist on instance
536
+ # wraps=instance: delegates method calls to the real instance
537
+ mock = _DynamicMock(spec=instance, wraps=instance, **kwargs)
538
+
539
+ # Step 5: Copy instance attributes to mock
540
+ # This handles both __slots__ and __dict__ based classes via _get_instance_attributes()
541
+ for attr in _get_instance_attributes(instance):
542
+ with contextlib.suppress(AttributeError, TypeError):
543
+ setattr(mock, attr, getattr(instance, attr))
544
+
545
+ # Step 6: Copy non-mockable methods directly
546
+ # Some methods (like bound methods or special attributes) need to be copied
547
+ # directly rather than being mocked
393
548
  try:
394
549
  for method_name in [
395
550
  prop
396
551
  for prop in _get_not_mockable_method_names(instance=instance, exclude_methods=exclude_methods)
397
- if prop not in include_properties and prop not in kwargs
552
+ if prop not in include_properties and prop not in kwargs and prop not in property_names
398
553
  ]:
399
554
  setattr(mock, method_name, getattr(instance, method_name))
400
555
  except Exception:
@@ -513,7 +668,7 @@ class SessionPlayer:
513
668
  return None
514
669
  if not (bucket_by_parameter := bucket_by_method.get(method)):
515
670
  return None
516
- frozen_params = _freeze_params(params=params)
671
+ frozen_params = _freeze_params(params=_cleanup_params_for_session(params=params))
517
672
 
518
673
  # For each parameter, choose the response at the latest timestamp.
519
674
  if (bucket_by_ts := bucket_by_parameter.get(frozen_params)) is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiohomematic-test-support
3
- Version: 2025.12.13
3
+ Version: 2025.12.23
4
4
  Summary: Support-only package for AioHomematic (tests/dev). Not part of production builds.
5
5
  Author-email: SukramJ <sukramj@icloud.com>
6
6
  Project-URL: Homepage, https://github.com/SukramJ/aiohomematic
@@ -0,0 +1,12 @@
1
+ aiohomematic_test_support/__init__.py,sha256=hwFQdytuqaQAqUbDFz_hSF39zeCY1PW_vafTdwa-Qoo,1623
2
+ aiohomematic_test_support/const.py,sha256=YXN3FvZCqjxOaqCs0E7KTz2PUa1zONzS9-W_6YqJrPI,19755
3
+ aiohomematic_test_support/factory.py,sha256=E3tHyeIAO1Id1c0ODP7WnUs_XOgnt14bMzPyow5SEJc,10772
4
+ aiohomematic_test_support/helper.py,sha256=Ue2tfy10_fiuMjYsc1jYPvo5sEtMF2WVKjvLnTZ0TzU,1360
5
+ aiohomematic_test_support/mock.py,sha256=h7kL6R7IeZfRArZ7TXfVgX_O2GRC-7CQk9llysQczTI,30228
6
+ aiohomematic_test_support/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ aiohomematic_test_support/data/full_session_randomized_ccu.zip,sha256=kKHMtJouCskAHkXaP1hHRSoWZO2cZDJ9P_EwuJuywJQ,733017
8
+ aiohomematic_test_support/data/full_session_randomized_pydevccu.zip,sha256=_QFWSP03dkiMFdD_w-R98DS6ur4PYDQXw-DCkbJEGg4,1293240
9
+ aiohomematic_test_support-2025.12.23.dist-info/METADATA,sha256=4MzyPgvkaZ98FmvnyIaBgIjGw1Vc1gFDcu06LzacPMc,536
10
+ aiohomematic_test_support-2025.12.23.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ aiohomematic_test_support-2025.12.23.dist-info/top_level.txt,sha256=KmK-OiDDbrmawIsIgPWNAkpkDfWQnOoumYd9MXAiTHc,26
12
+ aiohomematic_test_support-2025.12.23.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- aiohomematic_test_support/__init__.py,sha256=QZ6fA_Lk1iukixJUU6h8a4XcgF3OhzQaiVhUYc9VtTA,1623
2
- aiohomematic_test_support/const.py,sha256=YXN3FvZCqjxOaqCs0E7KTz2PUa1zONzS9-W_6YqJrPI,19755
3
- aiohomematic_test_support/factory.py,sha256=BT0bsplFO5nPqAJo2zwyI5QmNVDu32JcrgTCQbpB2dU,10767
4
- aiohomematic_test_support/helper.py,sha256=Ue2tfy10_fiuMjYsc1jYPvo5sEtMF2WVKjvLnTZ0TzU,1360
5
- aiohomematic_test_support/mock.py,sha256=z91_mjLMF09B5FprCnVeXwXpWHM1ZWe4h2nn97pGXR8,22713
6
- aiohomematic_test_support/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- aiohomematic_test_support/data/full_session_randomized_ccu.zip,sha256=oN7g0CB_0kQX3qk-RSu-Rt28yW7BcplVqPYZCDqr0EU,734626
8
- aiohomematic_test_support/data/full_session_randomized_pydevccu.zip,sha256=_QFWSP03dkiMFdD_w-R98DS6ur4PYDQXw-DCkbJEGg4,1293240
9
- aiohomematic_test_support-2025.12.13.dist-info/METADATA,sha256=BbOorwMcviBXtN2mBdNtdJVpuQQ9SCJLLyyMMgvIzl0,536
10
- aiohomematic_test_support-2025.12.13.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
- aiohomematic_test_support-2025.12.13.dist-info/top_level.txt,sha256=KmK-OiDDbrmawIsIgPWNAkpkDfWQnOoumYd9MXAiTHc,26
12
- aiohomematic_test_support-2025.12.13.dist-info/RECORD,,