test_device.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import tinytuya
  2. from datetime import datetime
  3. from time import time
  4. from unittest import IsolatedAsyncioTestCase
  5. from unittest.mock import AsyncMock, call, patch
  6. from custom_components.tuya_local.device import TuyaLocalDevice
  7. from .const import (
  8. EUROM_600_HEATER_PAYLOAD,
  9. )
  10. class TestDevice(IsolatedAsyncioTestCase):
  11. def setUp(self):
  12. device_patcher = patch("tinytuya.Device")
  13. self.addCleanup(device_patcher.stop)
  14. self.mock_api = device_patcher.start()
  15. hass_patcher = patch("homeassistant.core.HomeAssistant")
  16. self.addCleanup(hass_patcher.stop)
  17. self.hass = hass_patcher.start()
  18. self.subject = TuyaLocalDevice(
  19. "Some name",
  20. "some_dev_id",
  21. "some.ip.address",
  22. "some_local_key",
  23. "auto",
  24. self.hass(),
  25. )
  26. def test_configures_tinytuya_correctly(self):
  27. self.mock_api.assert_called_once_with(
  28. "some_dev_id", "some.ip.address", "some_local_key"
  29. )
  30. self.assertIs(self.subject._api, self.mock_api())
  31. def test_name(self):
  32. """Returns the name given at instantiation."""
  33. self.assertEqual(self.subject.name, "Some name")
  34. def test_unique_id(self):
  35. """Returns the unique ID presented by the API class."""
  36. self.assertIs(self.subject.unique_id, self.mock_api().id)
  37. def test_device_info(self):
  38. """Returns generic info plus the unique ID for categorisation."""
  39. self.assertEqual(
  40. self.subject.device_info,
  41. {
  42. "identifiers": {("tuya_local", self.mock_api().id)},
  43. "name": "Some name",
  44. "manufacturer": "Tuya",
  45. },
  46. )
  47. def test_has_returned_state(self):
  48. """Returns True if the device has returned its state."""
  49. self.subject._cached_state = EUROM_600_HEATER_PAYLOAD
  50. self.assertTrue(self.subject.has_returned_state)
  51. self.subject._cached_state = {"updated_at": 0}
  52. self.assertFalse(self.subject.has_returned_state)
  53. async def test_refreshes_state_if_no_cached_state_exists(self):
  54. self.subject._cached_state = {}
  55. self.subject.async_refresh = AsyncMock()
  56. await self.subject.async_inferred_type()
  57. self.subject.async_refresh.assert_awaited()
  58. async def test_detection_returns_none_when_device_type_could_not_be_detected(self):
  59. self.subject._cached_state = {"2": False, "updated_at": datetime.now()}
  60. self.assertEqual(await self.subject.async_inferred_type(), None)
  61. async def test_refreshes_when_there_is_no_pending_reset(self):
  62. async_job = AsyncMock()
  63. self.subject._cached_state = {"updated_at": time() - 19}
  64. self.subject._hass.async_add_executor_job.return_value = awaitable = async_job()
  65. await self.subject.async_refresh()
  66. async_job.assert_awaited()
  67. async def test_refreshes_when_there_is_expired_pending_reset(self):
  68. async_job = AsyncMock()
  69. self.subject._cached_state = {"updated_at": time() - 20}
  70. self.subject._hass.async_add_executor_job.return_value = awaitable = async_job()
  71. await self.subject.async_refresh()
  72. async_job.assert_awaited()
  73. async def test_refresh_reloads_status_from_device(self):
  74. self.subject._hass.async_add_executor_job = AsyncMock()
  75. self.subject._hass.async_add_executor_job.return_value = awaitable = {
  76. "dps": {"1": False}
  77. }
  78. await self.subject.async_refresh()
  79. self.subject._hass.async_add_executor_job.assert_called_once()
  80. async def test_refresh_retries_up_to_nine_times(self):
  81. self.subject._hass.async_add_executor_job = AsyncMock()
  82. self.subject._hass.async_add_executor_job.side_effect = [
  83. Exception("Error"),
  84. Exception("Error"),
  85. Exception("Error"),
  86. Exception("Error"),
  87. Exception("Error"),
  88. Exception("Error"),
  89. Exception("Error"),
  90. Exception("Error"),
  91. {"dps": {"1": False}},
  92. ]
  93. await self.subject.async_refresh()
  94. self.assertEqual(self.subject._hass.async_add_executor_job.call_count, 9)
  95. # self.assertEqual(self.subject._cached_state["1"], False)
  96. async def test_refresh_clears_cached_state_and_pending_updates_after_failing_nine_times(
  97. self,
  98. ):
  99. self.subject._cached_state = {"1": True}
  100. self.subject._pending_updates = {
  101. "1": {"value": False, "updated_at": datetime.now(), "sent": True}
  102. }
  103. self.subject._hass.async_add_executor_job = AsyncMock()
  104. self.subject._hass.async_add_executor_job.side_effect = [
  105. Exception("Error"),
  106. Exception("Error"),
  107. Exception("Error"),
  108. Exception("Error"),
  109. Exception("Error"),
  110. Exception("Error"),
  111. Exception("Error"),
  112. Exception("Error"),
  113. Exception("Error"),
  114. ]
  115. await self.subject.async_refresh()
  116. self.assertEqual(self.subject._hass.async_add_executor_job.call_count, 9)
  117. self.assertEqual(self.subject._cached_state, {"updated_at": 0})
  118. self.assertEqual(self.subject._pending_updates, {})
  119. async def test_api_protocol_version_is_rotated_with_each_failure(self):
  120. self.subject._api.set_version.reset_mock()
  121. self.subject._hass.async_add_executor_job = AsyncMock()
  122. self.subject._hass.async_add_executor_job.side_effect = [
  123. Exception("Error"),
  124. Exception("Error"),
  125. Exception("Error"),
  126. Exception("Error"),
  127. Exception("Error"),
  128. Exception("Error"),
  129. ]
  130. await self.subject.async_refresh()
  131. self.subject._api.set_version.assert_has_calls(
  132. [call(3.1), call(3.2), call(3.4), call(3.3), call(3.1)]
  133. )
  134. async def test_api_protocol_version_is_stable_once_successful(self):
  135. self.subject._api.set_version.reset_mock()
  136. self.subject._hass.async_add_executor_job = AsyncMock()
  137. self.subject._hass.async_add_executor_job.side_effect = [
  138. Exception("Error"),
  139. Exception("Error"),
  140. Exception("Error"),
  141. {"dps": {"1": False}},
  142. {"dps": {"1": False}},
  143. Exception("Error"),
  144. Exception("Error"),
  145. {"dps": {"1": False}},
  146. ]
  147. await self.subject.async_refresh()
  148. self.assertEqual(self.subject._api_protocol_version_index, 3)
  149. self.assertTrue(self.subject._api_protocol_working)
  150. await self.subject.async_refresh()
  151. self.assertEqual(self.subject._api_protocol_version_index, 3)
  152. await self.subject.async_refresh()
  153. self.assertEqual(self.subject._api_protocol_version_index, 3)
  154. self.subject._api.set_version.assert_has_calls(
  155. [call(3.1), call(3.2), call(3.4)]
  156. )
  157. async def test_api_protocol_version_is_not_rotated_when_not_auto(self):
  158. self.subject._protocol_configured = 3.4
  159. self.subject._api_protocol_version_index = None
  160. self.subject._api.set_version.reset_mock()
  161. self.subject._rotate_api_protocol_version()
  162. self.subject._api.set_version.assert_called_once_with(3.4)
  163. self.subject._api.set_version.reset_mock()
  164. self.subject._hass.async_add_executor_job = AsyncMock()
  165. self.subject._hass.async_add_executor_job.side_effect = [
  166. Exception("Error"),
  167. Exception("Error"),
  168. Exception("Error"),
  169. {"dps": {"1": False}},
  170. {"dps": {"1": False}},
  171. Exception("Error"),
  172. Exception("Error"),
  173. Exception("Error"),
  174. Exception("Error"),
  175. Exception("Error"),
  176. Exception("Error"),
  177. Exception("Error"),
  178. {"dps": {"1": False}},
  179. ]
  180. await self.subject.async_refresh()
  181. self.assertEqual(self.subject._api_protocol_version_index, 3)
  182. await self.subject.async_refresh()
  183. self.assertEqual(self.subject._api_protocol_version_index, 3)
  184. await self.subject.async_refresh()
  185. self.assertEqual(self.subject._api_protocol_version_index, 3)
  186. def test_reset_cached_state_clears_cached_state_and_pending_updates(self):
  187. self.subject._cached_state = {"1": True, "updated_at": time()}
  188. self.subject._pending_updates = {
  189. "1": {"value": False, "updated_at": datetime.now(), "sent": True}
  190. }
  191. self.subject._reset_cached_state()
  192. self.assertEqual(self.subject._cached_state, {"updated_at": 0})
  193. self.assertEqual(self.subject._pending_updates, {})
  194. def test_get_property_returns_value_from_cached_state(self):
  195. self.subject._cached_state = {"1": True}
  196. self.assertEqual(self.subject.get_property("1"), True)
  197. def test_get_property_returns_pending_update_value(self):
  198. self.subject._pending_updates = {
  199. "1": {"value": False, "updated_at": time() - 4, "sent": True}
  200. }
  201. self.assertEqual(self.subject.get_property("1"), False)
  202. def test_pending_update_value_overrides_cached_value(self):
  203. self.subject._cached_state = {"1": True}
  204. self.subject._pending_updates = {
  205. "1": {"value": False, "updated_at": time() - 4, "sent": True}
  206. }
  207. self.assertEqual(self.subject.get_property("1"), False)
  208. def test_expired_pending_update_value_does_not_override_cached_value(self):
  209. self.subject._cached_state = {"1": True}
  210. self.subject._pending_updates = {
  211. "1": {"value": False, "updated_at": time() - 5, "sent": True}
  212. }
  213. self.assertEqual(self.subject.get_property("1"), True)
  214. def test_get_property_returns_none_when_value_does_not_exist(self):
  215. self.subject._cached_state = {"1": True}
  216. self.assertIs(self.subject.get_property("2"), None)
  217. async def test_async_set_property_schedules_job(self):
  218. async_job = AsyncMock()
  219. self.subject._hass.async_add_executor_job.return_value = awaitable = async_job()
  220. await self.subject.async_set_property("1", False)
  221. self.subject._hass.async_add_executor_job.assert_called_once()
  222. async_job.assert_awaited()
  223. async def test_set_property_immediately_stores_new_value_to_pending_updates(self):
  224. self.subject._cached_state = {"1": True}
  225. await self.subject.async_set_property("1", False)
  226. self.assertFalse(self.subject.get_property("1"))
  227. async def test_set_properties_takes_no_action_when_no_properties_are_provided(self):
  228. with patch("asyncio.sleep") as mock:
  229. await self.subject.async_set_properties({})
  230. mock.assert_not_called()
  231. def test_anticipate_property_value_updates_cached_state(self):
  232. self.subject._cached_state = {"1": True}
  233. self.subject.anticipate_property_value("1", False)
  234. self.assertEqual(self.subject._cached_state["1"], False)
  235. def test_get_key_for_value_returns_key_from_object_matching_value(self):
  236. obj = {"key1": "value1", "key2": "value2"}
  237. self.assertEqual(TuyaLocalDevice.get_key_for_value(obj, "value1"), "key1")
  238. self.assertEqual(TuyaLocalDevice.get_key_for_value(obj, "value2"), "key2")
  239. def test_get_key_for_value_returns_fallback_when_value_not_found(self):
  240. obj = {"key1": "value1", "key2": "value2"}
  241. self.assertEqual(
  242. TuyaLocalDevice.get_key_for_value(obj, "value3", fallback="fb"), "fb"
  243. )