test_sensors.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. LastUpdatedSensor,
  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. current_updated=None,
  29. next_updated=None,
  30. api_status=None,
  31. ):
  32. coord = MagicMock()
  33. coord.data = CoordinatorData(
  34. active=current or ReservationData(),
  35. current=current or ReservationData(),
  36. next=nxt or ReservationData(),
  37. current_last_refresh=current_ts,
  38. next_last_refresh=next_ts,
  39. current_last_updated=current_updated,
  40. next_last_updated=next_updated,
  41. api_status=api_status,
  42. )
  43. return coord
  44. def _sensor(cls, coordinator, slot=STORE_CURRENT, field="guest_name", **extra):
  45. """Create a sensor instance without running __init__."""
  46. s = object.__new__(cls)
  47. s.coordinator = coordinator
  48. s._slot = slot
  49. s._field = field
  50. for k, v in extra.items():
  51. setattr(s, k, v)
  52. return s
  53. SAMPLE = ReservationData(
  54. guest_name="Alice",
  55. check_in_date=date(2026, 7, 1),
  56. check_in_time=time(14, 0),
  57. check_out_date=date(2026, 7, 5),
  58. check_out_time=time(12, 0),
  59. wifi_ssid="MyNet",
  60. wifi_key="hunter2",
  61. door_code="0472",
  62. )
  63. # ---------------------------------------------------------------------------
  64. # ReservationStrSensor
  65. # ---------------------------------------------------------------------------
  66. def test_str_sensor_returns_field_value():
  67. coord = _coordinator(current=SAMPLE)
  68. s = _sensor(ReservationStrSensor, coord, field="guest_name")
  69. assert s.native_value == "Alice"
  70. def test_str_sensor_reads_next_slot():
  71. nxt = ReservationData(guest_name="Bob")
  72. coord = _coordinator(nxt=nxt)
  73. s = _sensor(ReservationStrSensor, coord, slot=STORE_NEXT, field="guest_name")
  74. assert s.native_value == "Bob"
  75. def test_str_sensor_none_when_field_is_none():
  76. res = ReservationData(guest_name=None)
  77. coord = _coordinator(current=res)
  78. s = _sensor(ReservationStrSensor, coord, field="guest_name")
  79. assert s.native_value is None
  80. # ---------------------------------------------------------------------------
  81. # GuestNameSensor
  82. # ---------------------------------------------------------------------------
  83. def test_guest_name_single_word():
  84. coord = _coordinator(current=ReservationData(guest_name="Alice"))
  85. s = _sensor(GuestNameSensor, coord, field="guest_name")
  86. attrs = s.extra_state_attributes
  87. assert attrs["first_name"] == "Alice"
  88. assert attrs["first_abbr"] == "A"
  89. assert attrs["last_name"] is None
  90. assert attrs["last_abbr"] is None
  91. assert attrs["public"] == "Alice"
  92. def test_guest_name_two_words():
  93. coord = _coordinator(current=ReservationData(guest_name="ZiB Guest"))
  94. s = _sensor(GuestNameSensor, coord, field="guest_name")
  95. attrs = s.extra_state_attributes
  96. assert attrs["first_name"] == "ZiB"
  97. assert attrs["first_abbr"] == "Z"
  98. assert attrs["last_name"] == "Guest"
  99. assert attrs["last_abbr"] == "G"
  100. assert attrs["public"] == "ZiB G."
  101. def test_guest_name_three_words_last_is_final():
  102. coord = _coordinator(current=ReservationData(guest_name="ZiB Middle Guest"))
  103. s = _sensor(GuestNameSensor, coord, field="guest_name")
  104. attrs = s.extra_state_attributes
  105. assert attrs["first_name"] == "ZiB"
  106. assert attrs["last_name"] == "Guest"
  107. assert attrs["last_abbr"] == "G"
  108. assert attrs["public"] == "ZiB G."
  109. def test_guest_name_none_returns_no_attrs():
  110. coord = _coordinator(current=ReservationData(guest_name=None))
  111. s = _sensor(GuestNameSensor, coord, field="guest_name")
  112. assert s.extra_state_attributes is None
  113. # ---------------------------------------------------------------------------
  114. # ReservationTimeSensor
  115. # ---------------------------------------------------------------------------
  116. def test_time_sensor_returns_iso_string():
  117. coord = _coordinator(current=SAMPLE)
  118. s = _sensor(ReservationTimeSensor, coord, field="check_in_time")
  119. assert s.native_value == "14:00:00"
  120. def test_time_sensor_none_when_time_is_none():
  121. res = ReservationData(check_in_time=None)
  122. coord = _coordinator(current=res)
  123. s = _sensor(ReservationTimeSensor, coord, field="check_in_time")
  124. assert s.native_value is None
  125. # ---------------------------------------------------------------------------
  126. # ReservationDateTimeSensor
  127. # ---------------------------------------------------------------------------
  128. def test_datetime_sensor_native_value_is_date():
  129. coord = _coordinator(current=SAMPLE)
  130. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  131. s._time_field = "check_in_time"
  132. assert s.native_value == date(2026, 7, 1)
  133. def test_datetime_sensor_attrs_contain_expected_keys():
  134. coord = _coordinator(current=SAMPLE)
  135. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  136. s._time_field = "check_in_time"
  137. attrs = s.extra_state_attributes
  138. assert attrs is not None
  139. for key in ("datetime", "date", "weekday", "month", "time_abbr", "hour"):
  140. assert key in attrs, f"missing key: {key}"
  141. def test_datetime_sensor_attrs_none_when_date_missing():
  142. res = ReservationData(check_in_date=None, check_in_time=time(14, 0))
  143. coord = _coordinator(current=res)
  144. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  145. s._time_field = "check_in_time"
  146. assert s.extra_state_attributes is None
  147. def test_datetime_sensor_attrs_none_when_time_missing():
  148. res = ReservationData(check_in_date=date(2026, 7, 1), check_in_time=None)
  149. coord = _coordinator(current=res)
  150. s = _sensor(ReservationDateTimeSensor, coord, field="check_in_date")
  151. s._time_field = "check_in_time"
  152. assert s.extra_state_attributes is None
  153. # ---------------------------------------------------------------------------
  154. # WiFiKeySensor
  155. # ---------------------------------------------------------------------------
  156. def test_wifi_key_sensor_native_value():
  157. coord = _coordinator(current=SAMPLE)
  158. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  159. assert s.native_value == "hunter2"
  160. def test_wifi_key_sensor_qr_attribute():
  161. coord = _coordinator(current=SAMPLE)
  162. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  163. attrs = s.extra_state_attributes
  164. assert attrs is not None
  165. assert attrs["qr"] == "WIFI:S:MyNet;T:WPA;P:hunter2;;"
  166. def test_wifi_key_sensor_qr_attribute_open_network():
  167. """An empty-string wifi_key (open network default) should produce a nopass QR string."""
  168. res = ReservationData(wifi_ssid="MyNet", wifi_key="")
  169. coord = _coordinator(current=res)
  170. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  171. attrs = s.extra_state_attributes
  172. assert attrs is not None
  173. assert attrs["qr"] == "WIFI:S:MyNet;T:nopass;;"
  174. def test_wifi_key_sensor_qr_attribute_escapes_special_chars():
  175. res = ReservationData(wifi_ssid="Guest;Net,\"A\"", wifi_key="p:a\\ss;w,ord")
  176. coord = _coordinator(current=res)
  177. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  178. attrs = s.extra_state_attributes
  179. assert attrs is not None
  180. assert attrs["qr"] == 'WIFI:S:Guest\\;Net\\,\\"A\\";T:WPA;P:p\\:a\\\\ss\\;w\\,ord;;'
  181. def test_wifi_key_sensor_no_attrs_when_ssid_missing():
  182. res = ReservationData(wifi_ssid=None, wifi_key="hunter2")
  183. coord = _coordinator(current=res)
  184. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  185. assert s.extra_state_attributes is None
  186. def test_wifi_key_sensor_no_attrs_when_key_missing():
  187. res = ReservationData(wifi_ssid="MyNet", wifi_key=None)
  188. coord = _coordinator(current=res)
  189. s = _sensor(WiFiKeySensor, coord, field="wifi_key")
  190. assert s.extra_state_attributes is None
  191. # ---------------------------------------------------------------------------
  192. # LastUpdatedSensor
  193. # ---------------------------------------------------------------------------
  194. def test_last_updated_sensor_current():
  195. ts = datetime(2026, 6, 22, 10, 0, tzinfo=timezone.utc)
  196. coord = _coordinator(current_updated=ts)
  197. s = _sensor(LastUpdatedSensor, coord)
  198. s._slot = STORE_CURRENT
  199. assert s.native_value == ts
  200. def test_last_updated_sensor_next():
  201. ts = datetime(2026, 6, 22, 12, 0, tzinfo=timezone.utc)
  202. coord = _coordinator(next_updated=ts)
  203. s = _sensor(LastUpdatedSensor, coord)
  204. s._slot = STORE_NEXT
  205. assert s.native_value == ts
  206. def test_last_updated_sensor_none_before_any_change():
  207. coord = _coordinator()
  208. s = _sensor(LastUpdatedSensor, coord)
  209. s._slot = STORE_CURRENT
  210. assert s.native_value is None
  211. def test_last_updated_sensor_exposes_last_refresh_as_attribute():
  212. refresh_ts = datetime(2026, 6, 22, 9, 0, tzinfo=timezone.utc)
  213. updated_ts = datetime(2026, 6, 22, 10, 0, tzinfo=timezone.utc)
  214. coord = _coordinator(current_ts=refresh_ts, current_updated=updated_ts)
  215. s = _sensor(LastUpdatedSensor, coord)
  216. s._slot = STORE_CURRENT
  217. assert s.extra_state_attributes["last_refresh"] == refresh_ts
  218. def test_last_updated_sensor_last_refresh_attribute_none_when_not_yet_fetched():
  219. coord = _coordinator()
  220. s = _sensor(LastUpdatedSensor, coord)
  221. s._slot = STORE_CURRENT
  222. assert s.extra_state_attributes["last_refresh"] is None
  223. # ---------------------------------------------------------------------------
  224. # ApiHealthSensor
  225. # ---------------------------------------------------------------------------
  226. def _api_sensor(coordinator):
  227. s = object.__new__(ApiHealthSensor)
  228. s.coordinator = coordinator
  229. return s
  230. _REAL_CHECKS = {
  231. "caldav_connection": {"ok": True},
  232. "calendar": {"ok": True},
  233. "credentials": {
  234. "airbnb": {"ok": True},
  235. "booking": {"ok": False},
  236. },
  237. }
  238. def test_api_health_ok():
  239. status = ApiStatusData(status="ok", checks=_REAL_CHECKS)
  240. assert _api_sensor(_coordinator(api_status=status)).native_value == "OK"
  241. def test_api_health_degraded_on_non_ok_status():
  242. status = ApiStatusData(status="error", checks=_REAL_CHECKS)
  243. assert _api_sensor(_coordinator(api_status=status)).native_value == "Degraded"
  244. def test_api_health_none_when_no_status():
  245. assert _api_sensor(_coordinator(api_status=None)).native_value is None
  246. def test_api_health_attrs_flatten_checks():
  247. from datetime import datetime
  248. ts = datetime(2026, 6, 23, 8, 0, 0)
  249. status = ApiStatusData(status="ok", checks=_REAL_CHECKS, stale=False, checked_at=ts)
  250. attrs = _api_sensor(_coordinator(api_status=status)).extra_state_attributes
  251. assert attrs["caldav_connection"] is True
  252. assert attrs["calendar"] is True
  253. assert attrs["airbnb"] is True
  254. assert attrs["booking"] is False
  255. assert attrs["stale"] is False
  256. assert attrs["checked_at"] == ts.isoformat()
  257. def test_api_health_attrs_present_with_empty_checks():
  258. status = ApiStatusData(status="ok", checks={}, stale=True)
  259. attrs = _api_sensor(_coordinator(api_status=status)).extra_state_attributes
  260. assert attrs == {"stale": True, "checked_at": None}
  261. def test_api_health_no_attrs_when_no_status():
  262. assert _api_sensor(_coordinator(api_status=None)).extra_state_attributes is None