test_light.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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-2. Original bug: low brightness maps below min
  195. ({"min": 1, "max": 6}, 20, 1, "brightness"),
  196. ({"min": 1, "max": 6}, 20, 1, "white"),
  197. # 3-4. Generic min: not just tied to min=1
  198. ({"min": 10, "max": 15}, 20, 10, "brightness"),
  199. ({"min": 10, "max": 15}, 20, 10, "white"),
  200. # 5-6. Wide range snap: ensures bright=1 snaps to physical min, not proportional (3.92 -> 4)
  201. ({"min": 1, "max": 1000}, 1, 1, "brightness"),
  202. ({"min": 1, "max": 1000}, 1, 1, "white"),
  203. # 7-8. Wide offset range snap: proves snap uses actual DP min
  204. ({"min": 10, "max": 1000}, 1, 10, "brightness"),
  205. ({"min": 10, "max": 1000}, 1, 10, "white"),
  206. # 9-10. Normal mid-range value: proves we don't over-clamp
  207. ({"min": 1, "max": 6}, 128, 3, "brightness"),
  208. ({"min": 1, "max": 6}, 128, 3, "white"),
  209. # 11-12. Maximum value: proves upper bound is reachable
  210. ({"min": 1, "max": 6}, 255, 6, "brightness"),
  211. ({"min": 1, "max": 6}, 255, 6, "white"),
  212. ],
  213. )
  214. @pytest.mark.asyncio
  215. async def test_async_turn_on_clamps_low_brightness_to_range_min(
  216. brightness_range, ha_value, expected_dps, path
  217. ):
  218. """Low non-zero HA brightness should clamp to the first DP range value.
  219. Tests both the regular brightness path (ATTR_BRIGHTNESS) and the white
  220. brightness path (ATTR_WHITE) in async_turn_on, ensuring brightness_to_value
  221. results below the DP minimum are clamped correctly.
  222. """
  223. mock_device = AsyncMock()
  224. mock_device.get_property = Mock()
  225. if path == "white":
  226. dps_config = [
  227. {"id": "1", "name": "switch", "type": "boolean"},
  228. {
  229. "id": "2",
  230. "name": "color_mode",
  231. "type": "string",
  232. "mapping": [
  233. {"dps_val": "white", "value": "white"},
  234. {"dps_val": "colour", "value": "hs"},
  235. ],
  236. },
  237. {
  238. "id": "3",
  239. "name": "brightness",
  240. "type": "integer",
  241. "range": brightness_range,
  242. },
  243. ]
  244. device_dps = {"1": True, "2": "white", "3": brightness_range["min"]}
  245. call_kwargs = {"white": ha_value}
  246. assert_dp = "3"
  247. else:
  248. dps_config = [
  249. {"id": "1", "name": "switch", "type": "boolean"},
  250. {
  251. "id": "2",
  252. "name": "brightness",
  253. "type": "integer",
  254. "range": brightness_range,
  255. },
  256. ]
  257. device_dps = {"1": True, "2": brightness_range["min"]}
  258. call_kwargs = {"brightness": ha_value}
  259. assert_dp = "2"
  260. mock_device.get_property.side_effect = lambda arg: device_dps[arg]
  261. mock_config = Mock()
  262. config = TuyaEntityConfig(mock_config, {"entity": "light", "dps": dps_config})
  263. light = TuyaLocalLight(mock_device, config)
  264. await light.async_turn_on(**call_kwargs)
  265. mock_device.async_set_properties.assert_called_once_with({assert_dp: expected_dps})
  266. @pytest.mark.asyncio
  267. async def test_is_off_when_off_by_brightness():
  268. """Test that the light appears off when turned off by brightness."""
  269. mock_device = AsyncMock()
  270. mock_device.get_property = Mock()
  271. dps = {"1": 0}
  272. mock_device.get_property.side_effect = lambda arg: dps[arg]
  273. mock_config = Mock()
  274. config = TuyaEntityConfig(
  275. mock_config,
  276. {
  277. "entity": "light",
  278. "dps": [
  279. {
  280. "id": "1",
  281. "name": "brightness",
  282. "type": "integer",
  283. "range": {"min": 0, "max": 100},
  284. },
  285. ],
  286. },
  287. )
  288. light = TuyaLocalLight(mock_device, config)
  289. assert light.is_on is False
  290. assert light.brightness == 0