test_sensors.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. """Unit tests for sensor property logic.
  2. Bypasses HA entity setup by using object.__new__ and injecting a mock
  3. coordinator — valid because every tested property only reads self.coordinator.data.
  4. """
  5. from datetime import date, datetime, time, timezone
  6. from unittest.mock import MagicMock
  7. import pytest
  8. from custom_components.room_cal_ha.coordinator import CoordinatorData
  9. from custom_components.room_cal_ha.models import ApiStatusData, ReservationData
  10. from custom_components.room_cal_ha.sensor import (
  11. ApiHealthSensor,
  12. GuestNameSensor,
  13. LastRefreshSensor,
  14. ReservationDateTimeSensor,
  15. ReservationStrSensor,
  16. ReservationTimeSensor,
  17. WiFiKeySensor,
  18. )
  19. from custom_components.room_cal_ha.const import STORE_CURRENT, STORE_NEXT
  20. # ---------------------------------------------------------------------------
  21. # Helpers
  22. # ---------------------------------------------------------------------------
  23. def _coordinator(
  24. current=None,
  25. nxt=None,
  26. current_ts=None,
  27. next_ts=None,
  28. api_status=None,
  29. ):
  30. coord = MagicMock()
  31. coord.data = CoordinatorData(
  32. current=current or ReservationData(),
  33. next=nxt or ReservationData(),
  34. current_last_refresh=current_ts,
  35. next_last_refresh=next_ts,
  36. api_status=api_status,
  37. )
  38. return coord
  39. def _sensor(cls, coordinator, slot=STORE_CURRENT, field="guest_name", **extra):
  40. """Create a sensor instance without running __init__."""
  41. s = object.__new__(cls)
  42. s.coordinator = coordinator
  43. s._slot = slot
  44. s._field = field
  45. for k, v in extra.items():
  46. setattr(s, k, v)
  47. return s
  48. SAMPLE = ReservationData(
  49. guest_name="Alice",
  50. check_in_date=date(2026, 7, 1),
  51. check_in_time=time(14, 0),
  52. check_out_date=date(2026, 7, 5),
  53. check_out_time=time(12, 0),
  54. wifi_ssid="MyNet",
  55. wifi_key="hunter2",
  56. door_code="0472",
  57. )
  58. # ---------------------------------------------------------------------------
  59. # ReservationStrSensor
  60. # ---------------------------------------------------------------------------
  61. def test_str_sensor_returns_field_value():
  62. coord = _coordinator(current=SAMPLE)
  63. s = _sensor(ReservationStrSensor, coord, field="guest_name")
  64. assert s.native_value == "Alice"
  65. def test_str_sensor_reads_next_slot():
  66. nxt = ReservationData(guest_name="Bob")
  67. coord = _coordinator(nxt=nxt)
  68. s = _sensor(ReservationStrSensor, coord, slot=STORE_NEXT, field="guest_name")
  69. assert s.native_value == "Bob"
  70. def test_str_sensor_none_when_field_is_none():
  71. res = ReservationData(guest_name=None)
  72. coord = _coordinator(current=res)
  73. s = _sensor(ReservationStrSensor, coord, field="guest_name")
  74. assert s.native_value is None
  75. # ---------------------------------------------------------------------------
  76. # GuestNameSensor
  77. # ---------------------------------------------------------------------------
  78. def test_guest_name_single_word():
  79. coord = _coordinator(current=ReservationData(guest_name="Alice"))
  80. s = _sensor(GuestNameSensor, coord, field="guest_name")
  81. attrs = s.extra_state_attributes
  82. assert attrs["first_name"] == "Alice"
  83. assert attrs["first_abbr"] == "A"
  84. assert attrs["last_name"] is None
  85. assert attrs["last_abbr"] is None
  86. assert attrs["public"] == "Alice"
  87. def test_guest_name_two_words():
  88. coord = _coordinator(current=ReservationData(guest_name="ZiB Guest"))
  89. s = _sensor(GuestNameSensor, coord, field="guest_name")
  90. attrs = s.extra_state_attributes
  91. assert attrs["first_name"] == "ZiB"
  92. assert attrs["first_abbr"] == "Z"
  93. assert attrs["last_name"] == "Guest"
  94. assert attrs["last_abbr"] == "G"
  95. assert attrs["public"] == "ZiB G."
  96. def test_guest_name_three_words_last_is_final():
  97. coord = _coordinator(current=ReservationData(guest_name="ZiB Middle Guest"))
  98. s = _sensor(GuestNameSensor, coord, field="guest_name")
  99. attrs = s.extra_state_attributes
  100. assert attrs["first_name"] == "ZiB Middle"
  101. assert attrs["last_name"] == "Guest"
  102. assert attrs["last_abbr"] == "G"
  103. assert attrs["public"] == "ZiB Middle G."
  104. def test_guest_name_none_returns_no_attrs():
  105. coord = _coordinator(current=ReservationData(guest_name=None))
  106. s = _sensor(GuestNameSensor, coord, field="guest_name")
  107. assert s.extra_state_attributes is None
  108. # ---------------------------------------------------------------------------
  109. # ReservationTimeSensor
  110. # ---------------------------------------------------------------------------
  111. def test_time_sensor_returns_iso_string():
  112. coord = _coordinator(current=SAMPLE)
  113. s = _sensor(ReservationTimeSensor, coord, field="check_in_time")
  114. assert s.native_value == "14:00:00"
  115. def test_time_sensor_none_when_time_is_none():
  116. res = ReservationData(check_in_time=None)
  117. coord = _coordinator(current=res)
  118. s = _sensor(ReservationTimeSensor, coord, field="check_in_time")
  119. assert s.native_value is None
  120. # ---------------------------------------------------------------------------
  121. # ReservationDateTimeSensor
  122. # ---------------------------------------------------------------------------
  123. def test_datetime_sensor_native_value_is_date():
  124. coord = _coordinator(current=SAMPLE)
  125. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  126. s._time_field = "check_in_time"
  127. assert s.native_value == date(2026, 7, 1)
  128. def test_datetime_sensor_attrs_contain_expected_keys():
  129. coord = _coordinator(current=SAMPLE)
  130. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  131. s._time_field = "check_in_time"
  132. attrs = s.extra_state_attributes
  133. assert attrs is not None
  134. for key in ("datetime", "date", "weekday", "month", "time_abbr", "hour"):
  135. assert key in attrs, f"missing key: {key}"
  136. def test_datetime_sensor_attrs_none_when_date_missing():
  137. res = ReservationData(check_in_date=None, check_in_time=time(14, 0))
  138. coord = _coordinator(current=res)
  139. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  140. s._time_field = "check_in_time"
  141. assert s.extra_state_attributes is None
  142. def test_datetime_sensor_attrs_none_when_time_missing():
  143. res = ReservationData(check_in_date=date(2026, 7, 1), check_in_time=None)
  144. coord = _coordinator(current=res)
  145. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  146. s._time_field = "check_in_time"
  147. assert s.extra_state_attributes is None
  148. # ---------------------------------------------------------------------------
  149. # WiFiKeySensor
  150. # ---------------------------------------------------------------------------
  151. def test_wifi_key_sensor_native_value():
  152. coord = _coordinator(current=SAMPLE)
  153. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  154. assert s.native_value == "hunter2"
  155. def test_wifi_key_sensor_qr_attribute():
  156. coord = _coordinator(current=SAMPLE)
  157. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  158. attrs = s.extra_state_attributes
  159. assert attrs is not None
  160. assert attrs["qr"] == "WIFI:S:MyNet;T:WPA;P:hunter2;;"
  161. def test_wifi_key_sensor_no_attrs_when_ssid_missing():
  162. res = ReservationData(wifi_ssid=None, wifi_key="hunter2")
  163. coord = _coordinator(current=res)
  164. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  165. assert s.extra_state_attributes is None
  166. def test_wifi_key_sensor_no_attrs_when_key_missing():
  167. res = ReservationData(wifi_ssid="MyNet", wifi_key=None)
  168. coord = _coordinator(current=res)
  169. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  170. assert s.extra_state_attributes is None
  171. # ---------------------------------------------------------------------------
  172. # LastRefreshSensor
  173. # ---------------------------------------------------------------------------
  174. def test_last_refresh_sensor_current():
  175. ts = datetime(2026, 6, 22, 10, 0, tzinfo=timezone.utc)
  176. coord = _coordinator(current_ts=ts)
  177. s = _sensor(LastRefreshSensor, coord)
  178. s._slot = STORE_CURRENT
  179. assert s.native_value == ts
  180. def test_last_refresh_sensor_next():
  181. ts = datetime(2026, 6, 22, 12, 0, tzinfo=timezone.utc)
  182. coord = _coordinator(next_ts=ts)
  183. s = _sensor(LastRefreshSensor, coord)
  184. s._slot = STORE_NEXT
  185. assert s.native_value == ts
  186. def test_last_refresh_sensor_none_before_any_fetch():
  187. coord = _coordinator()
  188. s = _sensor(LastRefreshSensor, coord)
  189. s._slot = STORE_CURRENT
  190. assert s.native_value is None
  191. # ---------------------------------------------------------------------------
  192. # ApiHealthSensor
  193. # ---------------------------------------------------------------------------
  194. def _api_sensor(coordinator):
  195. s = object.__new__(ApiHealthSensor)
  196. s.coordinator = coordinator
  197. return s
  198. _REAL_CHECKS = {
  199. "caldav_connection": {"ok": True},
  200. "calendar": {"ok": True},
  201. "credentials": {
  202. "airbnb": {"ok": True},
  203. "booking": {"ok": False},
  204. },
  205. }
  206. def test_api_health_ok():
  207. status = ApiStatusData(status="ok", checks=_REAL_CHECKS)
  208. assert _api_sensor(_coordinator(api_status=status)).native_value == "OK"
  209. def test_api_health_degraded_on_non_ok_status():
  210. status = ApiStatusData(status="error", checks=_REAL_CHECKS)
  211. assert _api_sensor(_coordinator(api_status=status)).native_value == "Degraded"
  212. def test_api_health_none_when_no_status():
  213. assert _api_sensor(_coordinator(api_status=None)).native_value is None
  214. def test_api_health_attrs_flatten_checks():
  215. from datetime import datetime
  216. ts = datetime(2026, 6, 23, 8, 0, 0)
  217. status = ApiStatusData(status="ok", checks=_REAL_CHECKS, stale=False, checked_at=ts)
  218. attrs = _api_sensor(_coordinator(api_status=status)).extra_state_attributes
  219. assert attrs["caldav_connection"] is True
  220. assert attrs["calendar"] is True
  221. assert attrs["airbnb"] is True
  222. assert attrs["booking"] is False
  223. assert attrs["stale"] is False
  224. assert attrs["checked_at"] == ts.isoformat()
  225. def test_api_health_attrs_present_with_empty_checks():
  226. status = ApiStatusData(status="ok", checks={}, stale=True)
  227. attrs = _api_sensor(_coordinator(api_status=status)).extra_state_attributes
  228. assert attrs == {"stale": True, "checked_at": None}
  229. def test_api_health_no_attrs_when_no_status():
  230. assert _api_sensor(_coordinator(api_status=None)).extra_state_attributes is None