test_light.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """Tests for the light entity."""
  2. from unittest.mock import AsyncMock, Mock
  3. import pytest
  4. from pytest_homeassistant_custom_component.common import MockConfigEntry
  5. from custom_components.tuya_local.const import (
  6. CONF_DEVICE_ID,
  7. CONF_PROTOCOL_VERSION,
  8. CONF_TYPE,
  9. DOMAIN,
  10. )
  11. from custom_components.tuya_local.helpers.device_config import TuyaEntityConfig
  12. from custom_components.tuya_local.light import TuyaLocalLight, async_setup_entry
  13. @pytest.mark.asyncio
  14. async def test_init_entry(hass):
  15. """Test the initialisation."""
  16. entry = MockConfigEntry(
  17. domain=DOMAIN,
  18. data={
  19. CONF_TYPE: "goldair_gpph_heater",
  20. CONF_DEVICE_ID: "dummy",
  21. CONF_PROTOCOL_VERSION: "auto",
  22. },
  23. )
  24. # although async, the async_add_entities function passed to
  25. # async_setup_entry is called truly asynchronously. If we use
  26. # AsyncMock, it expects us to await the result.
  27. m_add_entities = Mock()
  28. m_device = AsyncMock()
  29. hass.data[DOMAIN] = {}
  30. hass.data[DOMAIN]["dummy"] = {}
  31. hass.data[DOMAIN]["dummy"]["device"] = m_device
  32. await async_setup_entry(hass, entry, m_add_entities)
  33. assert type(hass.data[DOMAIN]["dummy"]["light_display"]) is TuyaLocalLight
  34. m_add_entities.assert_called_once()
  35. @pytest.mark.asyncio
  36. async def test_init_entry_fails_if_device_has_no_light(hass):
  37. """Test initialisation when device has no matching entity"""
  38. entry = MockConfigEntry(
  39. domain=DOMAIN,
  40. data={
  41. CONF_TYPE: "smartplugv1",
  42. CONF_DEVICE_ID: "dummy",
  43. CONF_PROTOCOL_VERSION: "auto",
  44. },
  45. )
  46. # although async, the async_add_entities function passed to
  47. # async_setup_entry is called truly asynchronously. If we use
  48. # AsyncMock, it expects us to await the result.
  49. m_add_entities = Mock()
  50. m_device = AsyncMock()
  51. hass.data[DOMAIN] = {}
  52. hass.data[DOMAIN]["dummy"] = {}
  53. hass.data[DOMAIN]["dummy"]["device"] = m_device
  54. try:
  55. await async_setup_entry(hass, entry, m_add_entities)
  56. assert False
  57. except ValueError:
  58. pass
  59. m_add_entities.assert_not_called()
  60. @pytest.mark.asyncio
  61. async def test_init_entry_fails_if_config_is_missing(hass):
  62. """Test initialisation when device has no matching entity"""
  63. entry = MockConfigEntry(
  64. domain=DOMAIN,
  65. data={
  66. CONF_TYPE: "non_existing",
  67. CONF_DEVICE_ID: "dummy",
  68. CONF_PROTOCOL_VERSION: "auto",
  69. },
  70. )
  71. # although async, the async_add_entities function passed to
  72. # async_setup_entry is called truly asynchronously. If we use
  73. # AsyncMock, it expects us to await the result.
  74. m_add_entities = Mock()
  75. m_device = AsyncMock()
  76. hass.data[DOMAIN] = {}
  77. hass.data[DOMAIN]["dummy"] = {}
  78. hass.data[DOMAIN]["dummy"]["device"] = m_device
  79. try:
  80. await async_setup_entry(hass, entry, m_add_entities)
  81. assert False
  82. except ValueError:
  83. pass
  84. m_add_entities.assert_not_called()
  85. @pytest.mark.asyncio
  86. async def test_async_turn_on_with_white_param():
  87. """Test using WHITE param for async_turn_on."""
  88. mock_device = AsyncMock()
  89. mock_device.get_property = Mock()
  90. dps = {"1": True, "2": "colour", "3": 1000, "4": "ABCDEFFF"}
  91. mock_device.get_property.side_effect = lambda arg: dps[arg]
  92. mock_config = Mock()
  93. config = TuyaEntityConfig(
  94. mock_config,
  95. {
  96. "entity": "light",
  97. "dps": [
  98. {
  99. "id": "1",
  100. "name": "switch",
  101. "type": "boolean",
  102. },
  103. {
  104. "id": "2",
  105. "name": "color_mode",
  106. "type": "string",
  107. "mapping": [
  108. {
  109. "dps_val": "white",
  110. "value": "white",
  111. },
  112. {
  113. "dps_val": "colour",
  114. "value": "hs",
  115. },
  116. ],
  117. },
  118. {
  119. "id": "3",
  120. "name": "brightness",
  121. "type": "integer",
  122. "range": {
  123. "min": 10,
  124. "max": 1000,
  125. },
  126. },
  127. {
  128. "id": "4",
  129. "name": "hs",
  130. "type": "hex",
  131. },
  132. ],
  133. },
  134. )
  135. light = TuyaLocalLight(mock_device, config)
  136. await light.async_turn_on(white=128)
  137. mock_device.async_set_properties.assert_called_once_with({"2": "white", "3": 506})
  138. @pytest.mark.asyncio
  139. async def test_async_turn_on_with_brightness_on_packed_dp():
  140. """Switch-on must merge cleanly when the dp is shared across sub-fields.
  141. On packed dps where switch / brightness / color all share the same dp id
  142. (e.g. dp 51 with different masks), the switch-on branch was previously
  143. skipped once the brightness branch had populated `settings[dp_id]`,
  144. leaving the bulb with brightness staged but not actually on.
  145. For masked switch dps, the merge is always safe — `get_values_to_set`
  146. with `pending_map=settings` ORs onto the existing pending value — so the
  147. final write contains the switch byte AND the brightness bytes.
  148. """
  149. mock_device = AsyncMock()
  150. mock_device.get_property = Mock()
  151. # Bulb currently off: switch byte (mask 0001) is 0, brightness is 0.
  152. dps = {"1": "000000000000"}
  153. mock_device.get_property.side_effect = lambda arg: dps[arg]
  154. mock_config = Mock()
  155. config = TuyaEntityConfig(
  156. mock_config,
  157. {
  158. "entity": "light",
  159. "dps": [
  160. {
  161. "id": "1",
  162. "name": "switch",
  163. "type": "hex",
  164. "mask": "000100000000",
  165. },
  166. {
  167. "id": "1",
  168. "name": "brightness",
  169. "type": "hex",
  170. "mask": "0000FFFF0000",
  171. "range": {"min": 0, "max": 1000},
  172. },
  173. ],
  174. },
  175. )
  176. light = TuyaLocalLight(mock_device, config)
  177. await light.async_turn_on(brightness=255)
  178. mock_device.async_set_properties.assert_called_once()
  179. sent = mock_device.async_set_properties.call_args[0][0]
  180. sent_value = int(sent["1"], 16)
  181. # brightness bytes set
  182. assert sent_value & 0x0000FFFF0000 != 0
  183. # switch byte also set (this is the bug — was zero before the fix)
  184. assert sent_value & 0x000100000000 != 0
  185. @pytest.mark.parametrize(
  186. ("brightness_range", "ha_value", "expected_dps", "path"),
  187. [
  188. # brightness_to_value() uses scale_to_ranged_value((1,255), target, bright).
  189. # For small DP ranges, low HA brightness maps below the configured minimum:
  190. # (1, 6), 20 -> 20 * 6/255 = 0.470 -> below min 1
  191. # (10, 15), 20 -> 20 * 6/255 + 9 = 9.470 -> below min 10
  192. # (1, 6), 1 -> 1 * 6/255 = 0.024 -> below min 1 (HA minimum)
  193. # Each case is tested via both code paths: brightness and white.
  194. # 1-4. Original bug: low brightness maps below min
  195. ({"min": 1, "max": 6}, 1, 1, "brightness"),
  196. ({"min": 1, "max": 6}, 1, 1, "white"),
  197. ({"min": 1, "max": 6}, 20, 1, "brightness"),
  198. ({"min": 1, "max": 6}, 20, 1, "white"),
  199. # 5-6 Theoretical case for a light that uses 0 as a non-off brightness value.
  200. ({"min": 0, "max": 6}, 1, 0, "brightness"),
  201. ({"min": 0, "max": 6}, 1, 0, "white"),
  202. # 7-8. Generic min: not just tied to min=1
  203. ({"min": 10, "max": 15}, 20, 10, "brightness"),
  204. ({"min": 10, "max": 15}, 20, 10, "white"),
  205. # 9-10. Wide range snap: ensures bright=1 snaps to physical min, not proportional (3.92 -> 4)
  206. ({"min": 1, "max": 1000}, 1, 1, "brightness"),
  207. ({"min": 1, "max": 1000}, 1, 1, "white"),
  208. # 11-12. Wide offset range snap: proves snap uses actual DP min
  209. ({"min": 10, "max": 1000}, 1, 10, "brightness"),
  210. ({"min": 10, "max": 1000}, 1, 10, "white"),
  211. # 13-14. Normal mid-range value: proves we don't over-clamp
  212. ({"min": 1, "max": 6}, 128, 3, "brightness"),
  213. ({"min": 1, "max": 6}, 128, 3, "white"),
  214. # 15-16. Maximum value: proves upper bound is reachable
  215. ({"min": 1, "max": 6}, 255, 6, "brightness"),
  216. ({"min": 1, "max": 6}, 255, 6, "white"),
  217. ],
  218. )
  219. @pytest.mark.asyncio
  220. async def test_async_turn_on_clamps_low_brightness_to_range_min(
  221. brightness_range, ha_value, expected_dps, path
  222. ):
  223. """Low non-zero HA brightness should clamp to the first DP range value.
  224. Tests both the regular brightness path (ATTR_BRIGHTNESS) and the white
  225. brightness path (ATTR_WHITE) in async_turn_on, ensuring brightness_to_value
  226. results below the DP minimum are clamped correctly.
  227. """
  228. mock_device = AsyncMock()
  229. mock_device.get_property = Mock()
  230. if path == "white":
  231. dps_config = [
  232. {"id": "1", "name": "switch", "type": "boolean"},
  233. {
  234. "id": "2",
  235. "name": "color_mode",
  236. "type": "string",
  237. "mapping": [
  238. {"dps_val": "white", "value": "white"},
  239. {"dps_val": "colour", "value": "hs"},
  240. ],
  241. },
  242. {
  243. "id": "3",
  244. "name": "brightness",
  245. "type": "integer",
  246. "range": brightness_range,
  247. },
  248. ]
  249. device_dps = {"1": True, "2": "white", "3": brightness_range["min"]}
  250. call_kwargs = {"white": ha_value}
  251. assert_dp = "3"
  252. else:
  253. dps_config = [
  254. {"id": "1", "name": "switch", "type": "boolean"},
  255. {
  256. "id": "2",
  257. "name": "brightness",
  258. "type": "integer",
  259. "range": brightness_range,
  260. },
  261. ]
  262. device_dps = {"1": True, "2": brightness_range["min"]}
  263. call_kwargs = {"brightness": ha_value}
  264. assert_dp = "2"
  265. mock_device.get_property.side_effect = lambda arg: device_dps[arg]
  266. mock_config = Mock()
  267. config = TuyaEntityConfig(mock_config, {"entity": "light", "dps": dps_config})
  268. light = TuyaLocalLight(mock_device, config)
  269. await light.async_turn_on(**call_kwargs)
  270. mock_device.async_set_properties.assert_called_once_with({assert_dp: expected_dps})
  271. @pytest.mark.parametrize(
  272. ("brightness_range", "ha_value", "expected_dps", "step"),
  273. [
  274. ({"min": 0, "max": 6}, 1, 1, 1),
  275. ({"min": 0, "max": 255}, 1, 10, 10),
  276. ],
  277. )
  278. @pytest.mark.asyncio
  279. async def test_async_turn_on_avoids_0_when_0_is_off(
  280. brightness_range, ha_value, expected_dps, step
  281. ):
  282. """Low non-zero HA brightness should clamp to the first non-off DP range value.
  283. Tests the regular brightness path (ATTR_BRIGHTNESS), as ATTR_WHITE is not expected
  284. to be used on a brightness only light, and was tested adequately above.
  285. """
  286. mock_device = AsyncMock()
  287. mock_device.get_property = Mock()
  288. dps_config = [
  289. {
  290. "id": "2",
  291. "name": "brightness",
  292. "type": "integer",
  293. "range": brightness_range,
  294. "mapping": [{"step": step}],
  295. },
  296. ]
  297. device_dps = {"2": brightness_range["max"]}
  298. call_kwargs = {"brightness": ha_value}
  299. mock_device.get_property.side_effect = lambda arg: device_dps[arg]
  300. mock_config = Mock()
  301. config = TuyaEntityConfig(mock_config, {"entity": "light", "dps": dps_config})
  302. light = TuyaLocalLight(mock_device, config)
  303. await light.async_turn_on(**call_kwargs)
  304. mock_device.async_set_properties.assert_called_once_with({"2": expected_dps})
  305. @pytest.mark.asyncio
  306. async def test_is_off_when_off_by_brightness():
  307. """Test that the light appears off when turned off by brightness."""
  308. mock_device = AsyncMock()
  309. mock_device.get_property = Mock()
  310. dps = {"1": 0}
  311. mock_device.get_property.side_effect = lambda arg: dps[arg]
  312. mock_config = Mock()
  313. config = TuyaEntityConfig(
  314. mock_config,
  315. {
  316. "entity": "light",
  317. "dps": [
  318. {
  319. "id": "1",
  320. "name": "brightness",
  321. "type": "integer",
  322. "range": {"min": 0, "max": 100},
  323. },
  324. ],
  325. },
  326. )
  327. light = TuyaLocalLight(mock_device, config)
  328. assert light.is_on is False
  329. assert light.brightness == 0