test_helpers.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Tests for helper functions."""
  2. import asyncio
  3. import gc
  4. import logging
  5. import pytest
  6. from switchbot.helpers import (
  7. _BACKGROUND_TASKS,
  8. create_background_task,
  9. parse_power_data,
  10. )
  11. async def _drain_background_task(task: asyncio.Task) -> list[dict]:
  12. """Let a background task finish and collect unhandled-exception reports."""
  13. loop = asyncio.get_running_loop()
  14. reports: list[dict] = []
  15. previous_handler = loop.get_exception_handler()
  16. loop.set_exception_handler(lambda _loop, context: reports.append(context))
  17. try:
  18. await asyncio.wait([task])
  19. await asyncio.sleep(0)
  20. del task
  21. gc.collect()
  22. await asyncio.sleep(0)
  23. finally:
  24. loop.set_exception_handler(previous_handler)
  25. return reports
  26. async def _update() -> None:
  27. raise TimeoutError
  28. async def _parse() -> None:
  29. raise IndexError("index out of range")
  30. @pytest.mark.asyncio
  31. @pytest.mark.parametrize(
  32. ("coro_func", "level", "exc_name"),
  33. [
  34. pytest.param(_update, logging.DEBUG, "TimeoutError", id="transient"),
  35. pytest.param(_parse, logging.ERROR, "IndexError", id="unexpected"),
  36. ],
  37. )
  38. async def test_background_task_failure_is_logged(
  39. caplog: pytest.LogCaptureFixture,
  40. coro_func,
  41. level: int,
  42. exc_name: str,
  43. ) -> None:
  44. """Test a failed background task is logged instead of left unretrieved."""
  45. caplog.set_level(logging.DEBUG, logger="switchbot.helpers")
  46. pending = set(_BACKGROUND_TASKS)
  47. reports = await _drain_background_task(create_background_task(coro_func()))
  48. assert reports == []
  49. assert pending == _BACKGROUND_TASKS
  50. [record] = caplog.records
  51. assert record.levelno == level
  52. assert record.getMessage() == f"Background task {coro_func.__name__} failed"
  53. assert record.exc_info[0].__name__ == exc_name
  54. @pytest.mark.asyncio
  55. async def test_background_task_cancelled() -> None:
  56. """Test a cancelled background task is dropped without errors."""
  57. task = create_background_task(asyncio.sleep(10))
  58. await asyncio.sleep(0)
  59. task.cancel()
  60. reports = await _drain_background_task(task)
  61. assert reports == []
  62. assert task not in _BACKGROUND_TASKS
  63. @pytest.mark.asyncio
  64. async def test_background_task_success() -> None:
  65. """Test a successful background task is dropped from the set."""
  66. async def _ok() -> int:
  67. return 1
  68. pending = set(_BACKGROUND_TASKS)
  69. reports = await _drain_background_task(create_background_task(_ok()))
  70. assert reports == []
  71. assert pending == _BACKGROUND_TASKS
  72. def test_parse_power_data_basic():
  73. """Test basic power data parsing."""
  74. # Test data: bytes with value 0x1234 (4660 decimal) at offset 0
  75. data = b"\x12\x34\x56\x78"
  76. # Test without scale (should return raw value)
  77. assert parse_power_data(data, 0) == 4660
  78. # Test with scale of 10
  79. assert parse_power_data(data, 0, 10.0) == 466.0
  80. # Test with scale of 100
  81. assert parse_power_data(data, 0, 100.0) == 46.6
  82. def test_parse_power_data_with_offset():
  83. """Test power data parsing with different offsets."""
  84. data = b"\x00\x00\x12\x34\x56\x78"
  85. # Value at offset 2 should be 0x1234
  86. assert parse_power_data(data, 2, 10.0) == 466.0
  87. # Value at offset 4 should be 0x5678
  88. assert parse_power_data(data, 4, 10.0) == 2213.6
  89. def test_parse_power_data_with_mask():
  90. """Test power data parsing with bitmask."""
  91. # Test data: 0xFFFF
  92. data = b"\xff\xff"
  93. # Without mask
  94. assert parse_power_data(data, 0, 10.0) == 6553.5
  95. # With mask 0x7FFF (clear highest bit)
  96. assert parse_power_data(data, 0, 10.0, 0x7FFF) == 3276.7
  97. def test_parse_power_data_insufficient_data():
  98. """Test error handling for insufficient data."""
  99. data = b"\x12" # Only 1 byte
  100. # Should raise ValueError when trying to read 2 bytes
  101. with pytest.raises(ValueError, match="Insufficient data"):
  102. parse_power_data(data, 0)
  103. # Should also fail at offset 1 with 2-byte data
  104. data = b"\x12\x34"
  105. with pytest.raises(ValueError, match="Insufficient data"):
  106. parse_power_data(data, 1) # Would need to read bytes 1-2
  107. def test_parse_power_data_real_world_examples():
  108. """Test with real-world examples from relay switch."""
  109. # Simulate relay switch data structure
  110. raw_data = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdc\x00\x0f\x00\xe8"
  111. # Voltage at offset 9-10: 0x00DC = 220 / 10.0 = 22.0V
  112. assert parse_power_data(raw_data, 9, 10.0) == 22.0
  113. # Current at offset 11-12: 0x000F = 15 / 1000.0 = 0.015A
  114. assert parse_power_data(raw_data, 11, 1000.0) == 0.015
  115. # Power at offset 13-14: 0x00E8 = 232 / 10.0 = 23.2W
  116. assert parse_power_data(raw_data, 13, 10.0) == 23.2