test_device.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. from datetime import datetime
  2. from time import time
  3. from unittest import IsolatedAsyncioTestCase
  4. from unittest.mock import ANY, AsyncMock, Mock, call, patch
  5. from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP
  6. from custom_components.tuya_local.device import TuyaLocalDevice
  7. from custom_components.tuya_local.helpers.device_config import TuyaEntityConfig
  8. from custom_components.tuya_local.switch import TuyaLocalSwitch
  9. from .const import EUROM_600_HEATER_PAYLOAD
  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.hass().is_running = True
  19. self.hass().is_stopping = False
  20. def job(func, *args):
  21. return func(*args)
  22. self.hass().async_add_executor_job = AsyncMock()
  23. self.hass().async_add_executor_job.side_effect = job
  24. sleep_patcher = patch("asyncio.sleep")
  25. self.addCleanup(sleep_patcher.stop)
  26. self.mock_sleep = sleep_patcher.start()
  27. lock_patcher = patch("custom_components.tuya_local.device.Lock")
  28. self.addCleanup(lock_patcher.stop)
  29. self.mock_lock = lock_patcher.start()
  30. self.subject = TuyaLocalDevice(
  31. "Some name",
  32. "some_dev_id",
  33. "some.ip.address",
  34. "some_local_key",
  35. "auto",
  36. None,
  37. self.hass(),
  38. )
  39. # For most tests we want the protocol working
  40. self.subject._api_protocol_version_index = 0
  41. self.subject._api_protocol_working = True
  42. self.subject._protocol_configured = "auto"
  43. def test_configures_tinytuya_correctly(self):
  44. self.mock_api.assert_called_once_with(
  45. "some_dev_id", "some.ip.address", "some_local_key"
  46. )
  47. self.assertIs(self.subject._api, self.mock_api())
  48. def test_name(self):
  49. """Returns the name given at instantiation."""
  50. self.assertEqual(self.subject.name, "Some name")
  51. def test_unique_id(self):
  52. """Returns the unique ID presented by the API class."""
  53. self.assertIs(self.subject.unique_id, self.mock_api().id)
  54. def test_device_info(self):
  55. """Returns generic info plus the unique ID for categorisation."""
  56. self.assertEqual(
  57. self.subject.device_info,
  58. {
  59. "identifiers": {("tuya_local", self.mock_api().id)},
  60. "name": "Some name",
  61. "manufacturer": "Tuya",
  62. },
  63. )
  64. def test_has_returned_state(self):
  65. """Returns True if the device has returned its state."""
  66. self.subject._cached_state = EUROM_600_HEATER_PAYLOAD
  67. self.assertTrue(self.subject.has_returned_state)
  68. self.subject._cached_state = {"updated_at": 0}
  69. self.assertFalse(self.subject.has_returned_state)
  70. async def test_refreshes_state_if_no_cached_state_exists(self):
  71. self.subject._cached_state = {}
  72. self.subject.async_refresh = AsyncMock()
  73. await self.subject.async_inferred_type()
  74. self.subject.async_refresh.assert_awaited()
  75. async def test_detection_returns_none_when_device_type_not_detected(self):
  76. self.subject._cached_state = {"2": False, "updated_at": datetime.now()}
  77. self.assertEqual(await self.subject.async_inferred_type(), None)
  78. async def test_refreshes_when_there_is_no_pending_reset(self):
  79. self.subject._cached_state = {"updated_at": time() - 19}
  80. self.mock_api().status.return_value = {"dps": {"1": "called"}}
  81. await self.subject.async_refresh()
  82. self.mock_api().status.assert_called_once()
  83. self.assertEqual(self.subject._cached_state["1"], "called")
  84. async def test_refreshes_when_there_is_expired_pending_reset(self):
  85. self.subject._cached_state = {"updated_at": time() - 20}
  86. self.mock_api().status.return_value = {"dps": {"1": "called"}}
  87. await self.subject.async_refresh()
  88. self.mock_api().status.assert_called_once()
  89. self.assertEqual(self.subject._cached_state["1"], "called")
  90. async def test_refresh_retries_up_to_eleven_times(self):
  91. self.subject._api_protocol_working = False
  92. self.mock_api().status.side_effect = [
  93. Exception("Error"),
  94. Exception("Error"),
  95. Exception("Error"),
  96. Exception("Error"),
  97. Exception("Error"),
  98. Exception("Error"),
  99. Exception("Error"),
  100. Exception("Error"),
  101. Exception("Error"),
  102. Exception("Error"),
  103. {"dps": {"1": False}},
  104. ]
  105. await self.subject.async_refresh()
  106. self.assertEqual(self.mock_api().status.call_count, 11)
  107. self.assertEqual(self.subject._cached_state["1"], False)
  108. async def test_refresh_clears_cache_after_allowed_failures(self):
  109. self.subject._cached_state = {"1": True}
  110. self.subject._pending_updates = {
  111. "1": {"value": False, "updated_at": datetime.now(), "sent": True}
  112. }
  113. self.mock_api().status.side_effect = [
  114. Exception("Error"),
  115. Exception("Error"),
  116. Exception("Error"),
  117. ]
  118. await self.subject.async_refresh()
  119. self.assertEqual(self.mock_api().status.call_count, 3)
  120. self.assertEqual(self.subject._cached_state, {"updated_at": 0})
  121. self.assertEqual(self.subject._pending_updates, {})
  122. async def test_api_protocol_version_is_rotated_with_each_failure(self):
  123. self.subject._api_protocol_version_index = None
  124. self.subject._api_protocol_working = False
  125. self.mock_api().status.side_effect = [
  126. Exception("Error"),
  127. Exception("Error"),
  128. Exception("Error"),
  129. Exception("Error"),
  130. Exception("Error"),
  131. Exception("Error"),
  132. Exception("Error"),
  133. ]
  134. await self.subject.async_refresh()
  135. self.mock_api().set_version.assert_has_calls(
  136. [call(3.1), call(3.2), call(3.4), call(3.5), call(3.3), call(3.1)]
  137. )
  138. async def test_api_protocol_version_is_stable_once_successful(self):
  139. self.subject._api_protocol_version_index = None
  140. self.subject._api_protocol_working = False
  141. self.mock_api().status.side_effect = [
  142. Exception("Error"),
  143. Exception("Error"),
  144. Exception("Error"),
  145. {"dps": {"1": False}},
  146. {"dps": {"1": False}},
  147. Exception("Error"),
  148. Exception("Error"),
  149. {"dps": {"1": False}},
  150. ]
  151. await self.subject.async_refresh()
  152. self.assertEqual(self.subject._api_protocol_version_index, 3)
  153. self.assertTrue(self.subject._api_protocol_working)
  154. await self.subject.async_refresh()
  155. self.assertEqual(self.subject._api_protocol_version_index, 3)
  156. await self.subject.async_refresh()
  157. self.assertEqual(self.subject._api_protocol_version_index, 3)
  158. self.mock_api().set_version.assert_has_calls(
  159. [
  160. call(3.1),
  161. call(3.2),
  162. call(3.4),
  163. ]
  164. )
  165. async def test_api_protocol_version_is_not_rotated_when_not_auto(self):
  166. # Set up preconditions for the test
  167. self.subject._protocol_configured = 3.4
  168. self.subject._api_protocol_version_index = None
  169. self.subject._api_protocol_working = False
  170. self.mock_api().status.side_effect = [
  171. Exception("Error"),
  172. Exception("Error"),
  173. Exception("Error"),
  174. {"dps": {"1": False}},
  175. {"dps": {"1": False}},
  176. Exception("Error"),
  177. Exception("Error"),
  178. Exception("Error"),
  179. Exception("Error"),
  180. Exception("Error"),
  181. Exception("Error"),
  182. Exception("Error"),
  183. {"dps": {"1": False}},
  184. ]
  185. await self.subject._rotate_api_protocol_version()
  186. self.mock_api().set_version.assert_called_once_with(3.4)
  187. self.mock_api().set_version.reset_mock()
  188. await self.subject.async_refresh()
  189. self.assertEqual(self.subject._api_protocol_version_index, 3)
  190. await self.subject.async_refresh()
  191. self.assertEqual(self.subject._api_protocol_version_index, 3)
  192. await self.subject.async_refresh()
  193. self.assertEqual(self.subject._api_protocol_version_index, 3)
  194. def test_reset_cached_state_clears_cached_state_and_pending_updates(self):
  195. self.subject._cached_state = {"1": True, "updated_at": time()}
  196. self.subject._pending_updates = {
  197. "1": {"value": False, "updated_at": datetime.now(), "sent": True}
  198. }
  199. self.subject._reset_cached_state()
  200. self.assertEqual(self.subject._cached_state, {"updated_at": 0})
  201. self.assertEqual(self.subject._pending_updates, {})
  202. def test_get_property_returns_value_from_cached_state(self):
  203. self.subject._cached_state = {"1": True}
  204. self.assertEqual(self.subject.get_property("1"), True)
  205. def test_get_property_returns_pending_update_value(self):
  206. self.subject._pending_updates = {
  207. "1": {"value": False, "updated_at": time() - 4, "sent": True}
  208. }
  209. self.assertEqual(self.subject.get_property("1"), False)
  210. def test_pending_update_value_overrides_cached_value(self):
  211. self.subject._cached_state = {"1": True}
  212. self.subject._pending_updates = {
  213. "1": {"value": False, "updated_at": time() - 4, "sent": True}
  214. }
  215. self.assertEqual(self.subject.get_property("1"), False)
  216. def test_expired_pending_update_value_does_not_override_cached_value(self):
  217. self.subject._cached_state = {"1": True}
  218. self.subject._pending_updates = {
  219. "1": {"value": False, "updated_at": time() - 5, "sent": True}
  220. }
  221. self.assertEqual(self.subject.get_property("1"), True)
  222. def test_get_property_returns_none_when_value_does_not_exist(self):
  223. self.subject._cached_state = {"1": True}
  224. self.assertIs(self.subject.get_property("2"), None)
  225. async def test_async_set_property_sends_to_api(self):
  226. await self.subject.async_set_property("1", False)
  227. self.mock_api().set_multiple_values.assert_called_once()
  228. async def test_set_property_immediately_stores_pending_updates(self):
  229. self.subject._cached_state = {"1": True}
  230. await self.subject.async_set_property("1", False)
  231. self.assertFalse(self.subject.get_property("1"))
  232. async def test_set_properties_takes_no_action_when_nothing_provided(self):
  233. with patch("asyncio.sleep") as mock:
  234. await self.subject.async_set_properties({})
  235. mock.assert_not_called()
  236. def test_anticipate_property_value_updates_cached_state(self):
  237. self.subject._cached_state = {"1": True}
  238. self.subject.anticipate_property_value("1", False)
  239. self.assertEqual(self.subject._cached_state["1"], False)
  240. def test_get_key_for_value_returns_key_from_object_matching_value(self):
  241. obj = {"key1": "value1", "key2": "value2"}
  242. self.assertEqual(
  243. TuyaLocalDevice.get_key_for_value(obj, "value1"),
  244. "key1",
  245. )
  246. self.assertEqual(
  247. TuyaLocalDevice.get_key_for_value(obj, "value2"),
  248. "key2",
  249. )
  250. def test_get_key_for_value_returns_fallback_when_value_not_found(self):
  251. obj = {"key1": "value1", "key2": "value2"}
  252. self.assertEqual(
  253. TuyaLocalDevice.get_key_for_value(obj, "value3", fallback="fb"),
  254. "fb",
  255. )
  256. def test_refresh_cached_state(self):
  257. # set up preconditions
  258. self.mock_api().status.return_value = {"dps": {"1": "CHANGED"}}
  259. self.subject._cached_state = {"1": "UNCHANGED", "updated_at": 123}
  260. # call the function under test
  261. self.subject._refresh_cached_state()
  262. # Did it call the API as expected?
  263. self.mock_api().status.assert_called_once()
  264. # Did it update the cached state?
  265. self.assertDictEqual(
  266. self.subject._cached_state,
  267. {"1": "CHANGED"} | self.subject._cached_state,
  268. )
  269. # Did it update the timestamp on the cached state?
  270. self.assertAlmostEqual(
  271. self.subject._cached_state["updated_at"],
  272. time(),
  273. delta=2,
  274. )
  275. def test_set_values(self):
  276. # set up preconditions
  277. self.subject._pending_updates = {
  278. "1": {"value": "sample", "updated_at": time() - 2, "sent": False},
  279. }
  280. # call the function under test
  281. self.subject._set_values({"1": "sample"})
  282. # did it send what it was asked?
  283. self.mock_api().set_multiple_values.assert_called_once_with(
  284. {"1": "sample"}, nowait=True
  285. )
  286. # did it mark the pending updates as sent?
  287. self.assertTrue(self.subject._pending_updates["1"]["sent"])
  288. # did it update the time on the pending updates?
  289. self.assertAlmostEqual(
  290. self.subject._pending_updates["1"]["updated_at"],
  291. time(),
  292. delta=2,
  293. )
  294. # did it lock and unlock when sending
  295. self.subject._lock.acquire.assert_called_once()
  296. self.subject._lock.release.assert_called_once()
  297. def test_actually_start(self):
  298. # Set up the preconditions
  299. self.subject.receive_loop = Mock()
  300. self.subject.receive_loop.return_value = "LOOP"
  301. self.hass().bus.async_listen_once.return_value = "LISTENER"
  302. self.subject._running = False
  303. # run the function under test
  304. self.subject.actually_start()
  305. # did it register a listener for EVENT_HOMEASSISTANT_STOP?
  306. self.hass().bus.async_listen_once.assert_called_once_with(
  307. EVENT_HOMEASSISTANT_STOP, self.subject.async_stop
  308. )
  309. self.assertEqual(self.subject._shutdown_listener, "LISTENER")
  310. # did it set the running flag?
  311. self.assertTrue(self.subject._running)
  312. # did it schedule the loop?
  313. self.hass().async_create_task.assert_called_once_with("LOOP")
  314. def test_start_starts_when_ha_running(self):
  315. # Set up preconditions
  316. self.hass().is_running = True
  317. listener = Mock()
  318. self.subject._startup_listener = listener
  319. self.subject.actually_start = Mock()
  320. # Call the function under test
  321. self.subject.start()
  322. # Did it actually start?
  323. self.subject.actually_start.assert_called_once()
  324. # Did it cancel the startup listener?
  325. self.assertIsNone(self.subject._startup_listener)
  326. listener.assert_called_once()
  327. def test_start_schedules_for_later_when_ha_starting(self):
  328. # Set up preconditions
  329. self.hass().is_running = False
  330. self.hass().bus.async_listen_once.return_value = "LISTENER"
  331. self.subject.actually_start = Mock()
  332. # Call the function under test
  333. self.subject.start()
  334. # Did it avoid actually starting?
  335. self.subject.actually_start.assert_not_called()
  336. # Did it register a listener?
  337. self.assertEqual(self.subject._startup_listener, "LISTENER")
  338. self.hass().bus.async_listen_once.assert_called_once_with(
  339. EVENT_HOMEASSISTANT_STARTED, self.subject.actually_start
  340. )
  341. def test_start_does_nothing_when_ha_stopping(self):
  342. # Set up preconditions
  343. self.hass().is_running = True
  344. self.hass().is_stopping = True
  345. self.subject.actually_start = Mock()
  346. # Call the function under test
  347. self.subject.start()
  348. # Did it avoid actually starting?
  349. self.subject.actually_start.assert_not_called()
  350. # Did it avoid registering a listener?
  351. self.hass().bus.async_listen_once.assert_not_called()
  352. self.assertIsNone(self.subject._startup_listener)
  353. async def test_async_stop(self):
  354. # Set up preconditions
  355. listener = Mock()
  356. self.subject._refresh_task = None
  357. self.subject._shutdown_listener = listener
  358. self.subject._children = [1, 2, 3]
  359. # Call the function under test
  360. await self.subject.async_stop()
  361. # Was the shutdown listener cancelled?
  362. listener.assert_called_once()
  363. self.assertIsNone(self.subject._shutdown_listener)
  364. # Were the child entities cleared?
  365. self.assertEqual(self.subject._children, [])
  366. # Did it wait for the refresh task to finish then clear it?
  367. # This doesn't work because AsyncMock only mocks awaitable method calls
  368. # but we want an awaitable object
  369. # refresh.assert_awaited_once()
  370. self.assertIsNone(self.subject._refresh_task)
  371. async def test_async_stop_when_not_running(self):
  372. # Set up preconditions
  373. self._refresh_task = None
  374. self.subject._shutdown_listener = None
  375. self.subject._children = []
  376. # Call the function under test
  377. await self.subject.async_stop()
  378. # Was the shutdown listener left empty?
  379. self.assertIsNone(self.subject._shutdown_listener)
  380. # Were the child entities cleared?
  381. self.assertEqual(self.subject._children, [])
  382. # Was the refresh task left empty?
  383. self.assertIsNone(self.subject._refresh_task)
  384. def test_register_first_entity_ha_running(self):
  385. # Set up preconditions
  386. self.subject._children = []
  387. self.subject._running = False
  388. self.subject._startup_listener = None
  389. self.subject.start = Mock()
  390. entity = AsyncMock()
  391. entity._config = Mock()
  392. entity._config.dps.return_value = []
  393. # despite the name, the below HA function is not async and does not need to be awaited
  394. entity.async_schedule_update_ha_state = Mock()
  395. # Call the function under test
  396. self.subject.register_entity(entity)
  397. # Was the entity added to the list?
  398. self.assertEqual(self.subject._children, [entity])
  399. # Did we start the loop?
  400. self.subject.start.assert_called_once()
  401. def test_register_subsequent_entity_ha_running(self):
  402. # Set up preconditions
  403. first = AsyncMock()
  404. second = AsyncMock()
  405. second._config = Mock()
  406. second._config.dps.return_value = []
  407. self.subject._children = [first]
  408. self.subject._running = True
  409. self.subject._startup_listener = None
  410. self.subject.start = Mock()
  411. # Call the function under test
  412. self.subject.register_entity(second)
  413. # Was the entity added to the list?
  414. self.assertCountEqual(self.subject._children, [first, second])
  415. # Did we avoid restarting the loop?
  416. self.subject.start.assert_not_called()
  417. def test_register_subsequent_entity_ha_starting(self):
  418. # Set up preconditions
  419. first = AsyncMock()
  420. second = AsyncMock()
  421. second._config = Mock()
  422. second._config.dps.return_value = []
  423. self.subject._children = [first]
  424. self.subject._running = False
  425. self.subject._startup_listener = Mock()
  426. self.subject.start = Mock()
  427. # Call the function under test
  428. self.subject.register_entity(second)
  429. # Was the entity added to the list?
  430. self.assertCountEqual(self.subject._children, [first, second])
  431. # Did we avoid restarting the loop?
  432. self.subject.start.assert_not_called()
  433. async def test_unregister_one_of_many_entities(self):
  434. # Set up preconditions
  435. self.subject._children = ["First", "Second"]
  436. self.subject.async_stop = AsyncMock()
  437. # Call the function under test
  438. await self.subject.async_unregister_entity("First")
  439. # Was the entity removed from the list?
  440. self.assertCountEqual(self.subject._children, ["Second"])
  441. # Is the loop still running?
  442. self.subject.async_stop.assert_not_called()
  443. async def test_unregister_last_entity(self):
  444. # Set up preconditions
  445. self.subject._children = ["Last"]
  446. self.subject.async_stop = AsyncMock()
  447. # Call the function under test
  448. await self.subject.async_unregister_entity("Last")
  449. # Was the entity removed from the list?
  450. self.assertEqual(self.subject._children, [])
  451. # Was the loop stopped?
  452. self.subject.async_stop.assert_called_once()
  453. async def test_async_receive(self):
  454. # Set up preconditions
  455. self.mock_api().status.return_value = {"dps": {"1": "INIT", "2": 2}}
  456. self.mock_api().receive.return_value = {"1": "UPDATED"}
  457. self.subject._running = True
  458. self.subject._cached_state = {"updated_at": 0}
  459. # Call the function under test
  460. print("starting test loop...")
  461. loop = self.subject.async_receive()
  462. print("getting first iteration...")
  463. result = await loop.__anext__()
  464. # Check that the loop was started, but without persistent connection
  465. # since there was no state returned yet and it might need to negotiate
  466. # version.
  467. self.mock_api().set_socketPersistent.assert_called_once_with(False)
  468. # Check that a full poll was done
  469. self.mock_api().status.assert_called_once()
  470. self.assertDictEqual(result, {"1": "INIT", "2": 2, "full_poll": ANY})
  471. # Prepare for next round
  472. self.subject._cached_state = self.subject._cached_state | result
  473. self.mock_api().set_socketPersistent.reset_mock()
  474. self.mock_api().status.reset_mock()
  475. self.subject._cached_state["updated_at"] = time()
  476. # Call the function under test
  477. print("getting second iteration...")
  478. result = await loop.__anext__()
  479. # Check that a heartbeat poll was done
  480. self.mock_api().status.assert_not_called()
  481. self.mock_api().heartbeat.assert_called_once()
  482. self.mock_api().receive.assert_called_once()
  483. self.assertDictEqual(result, {"1": "UPDATED", "full_poll": ANY})
  484. # Check that the connection was made persistent now that data has been
  485. # returned
  486. self.mock_api().set_socketPersistent.assert_called_once_with(True)
  487. # Prepare for next iteration
  488. self.subject._running = False
  489. self.mock_api().set_socketPersistent.reset_mock()
  490. # Call the function under test
  491. print("getting last iteration...")
  492. try:
  493. result = await loop.__anext__()
  494. self.fail("Should have raised an exception to quit the loop")
  495. # Check that the loop terminated
  496. except StopAsyncIteration:
  497. pass
  498. self.mock_api().set_socketPersistent.assert_called_once_with(False)
  499. def test_should_poll(self):
  500. self.subject._cached_state = {"1": "sample", "updated_at": time()}
  501. self.subject._poll_only = False
  502. self.subject._temporary_poll = False
  503. # Test temporary poll via pause/resume
  504. self.assertFalse(self.subject.should_poll)
  505. self.subject.pause()
  506. self.assertTrue(self.subject.should_poll)
  507. self.subject.resume()
  508. self.assertFalse(self.subject.should_poll)
  509. # Test configured polling
  510. self.subject._poll_only = True
  511. self.assertTrue(self.subject.should_poll)
  512. self.subject._poll_only = False
  513. # Test initial polling
  514. self.subject._cached_state = {}
  515. self.assertTrue(self.subject.should_poll)