test_device.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. from datetime import datetime
  2. from time import time
  3. from unittest import IsolatedAsyncioTestCase
  4. from unittest.mock import AsyncMock, Mock, call, patch
  5. from homeassistant.const import (
  6. EVENT_HOMEASSISTANT_STARTED,
  7. EVENT_HOMEASSISTANT_STOP,
  8. )
  9. from custom_components.tuya_local.device import TuyaLocalDevice
  10. from .const import (
  11. EUROM_600_HEATER_PAYLOAD,
  12. )
  13. class TestDevice(IsolatedAsyncioTestCase):
  14. def setUp(self):
  15. device_patcher = patch("tinytuya.Device")
  16. self.addCleanup(device_patcher.stop)
  17. self.mock_api = device_patcher.start()
  18. hass_patcher = patch("homeassistant.core.HomeAssistant")
  19. self.addCleanup(hass_patcher.stop)
  20. self.hass = hass_patcher.start()
  21. lock_patcher = patch("custom_components.tuya_local.device.Lock")
  22. self.addCleanup(lock_patcher.stop)
  23. self.mock_lock = lock_patcher.start()
  24. self.subject = TuyaLocalDevice(
  25. "Some name",
  26. "some_dev_id",
  27. "some.ip.address",
  28. "some_local_key",
  29. "auto",
  30. self.hass(),
  31. )
  32. def test_configures_tinytuya_correctly(self):
  33. self.mock_api.assert_called_once_with(
  34. "some_dev_id", "some.ip.address", "some_local_key"
  35. )
  36. self.assertIs(self.subject._api, self.mock_api())
  37. def test_name(self):
  38. """Returns the name given at instantiation."""
  39. self.assertEqual(self.subject.name, "Some name")
  40. def test_unique_id(self):
  41. """Returns the unique ID presented by the API class."""
  42. self.assertIs(self.subject.unique_id, self.mock_api().id)
  43. def test_device_info(self):
  44. """Returns generic info plus the unique ID for categorisation."""
  45. self.assertEqual(
  46. self.subject.device_info,
  47. {
  48. "identifiers": {("tuya_local", self.mock_api().id)},
  49. "name": "Some name",
  50. "manufacturer": "Tuya",
  51. },
  52. )
  53. def test_has_returned_state(self):
  54. """Returns True if the device has returned its state."""
  55. self.subject._cached_state = EUROM_600_HEATER_PAYLOAD
  56. self.assertTrue(self.subject.has_returned_state)
  57. self.subject._cached_state = {"updated_at": 0}
  58. self.assertFalse(self.subject.has_returned_state)
  59. async def test_refreshes_state_if_no_cached_state_exists(self):
  60. self.subject._cached_state = {}
  61. self.subject.async_refresh = AsyncMock()
  62. await self.subject.async_inferred_type()
  63. self.subject.async_refresh.assert_awaited()
  64. async def test_detection_returns_none_when_device_type_not_detected(self):
  65. self.subject._cached_state = {"2": False, "updated_at": datetime.now()}
  66. self.assertEqual(await self.subject.async_inferred_type(), None)
  67. async def test_refreshes_when_there_is_no_pending_reset(self):
  68. async_job = AsyncMock()
  69. self.subject._cached_state = {"updated_at": time() - 19}
  70. self.hass().async_add_executor_job.return_value = async_job()
  71. await self.subject.async_refresh()
  72. async_job.assert_awaited()
  73. async def test_refreshes_when_there_is_expired_pending_reset(self):
  74. async_job = AsyncMock()
  75. self.subject._cached_state = {"updated_at": time() - 20}
  76. self.hass().async_add_executor_job.return_value = async_job()
  77. await self.subject.async_refresh()
  78. async_job.assert_awaited()
  79. async def test_refresh_reloads_status_from_device(self):
  80. self.hass().async_add_executor_job = AsyncMock()
  81. self.hass().async_add_executor_job.return_value = {"dps": {"1": False}}
  82. await self.subject.async_refresh()
  83. self.hass().async_add_executor_job.assert_called_once()
  84. async def test_refresh_retries_up_to_nine_times(self):
  85. self.hass().async_add_executor_job = AsyncMock()
  86. self.hass().async_add_executor_job.side_effect = [
  87. Exception("Error"),
  88. Exception("Error"),
  89. Exception("Error"),
  90. Exception("Error"),
  91. Exception("Error"),
  92. Exception("Error"),
  93. Exception("Error"),
  94. Exception("Error"),
  95. {"dps": {"1": False}},
  96. ]
  97. await self.subject.async_refresh()
  98. self.assertEqual(self.hass().async_add_executor_job.call_count, 9)
  99. # self.assertEqual(self.subject._cached_state["1"], False)
  100. async def test_refresh_clears_cached_and_pending_after_nine_fails(
  101. self,
  102. ):
  103. self.subject._cached_state = {"1": True}
  104. self.subject._pending_updates = {
  105. "1": {"value": False, "updated_at": datetime.now(), "sent": True}
  106. }
  107. self.hass().async_add_executor_job = AsyncMock()
  108. self.hass().async_add_executor_job.side_effect = [
  109. Exception("Error"),
  110. Exception("Error"),
  111. Exception("Error"),
  112. Exception("Error"),
  113. Exception("Error"),
  114. Exception("Error"),
  115. Exception("Error"),
  116. Exception("Error"),
  117. Exception("Error"),
  118. ]
  119. await self.subject.async_refresh()
  120. self.assertEqual(self.hass().async_add_executor_job.call_count, 9)
  121. self.assertEqual(self.subject._cached_state, {"updated_at": 0})
  122. self.assertEqual(self.subject._pending_updates, {})
  123. async def test_api_protocol_version_is_rotated_with_each_failure(self):
  124. self.mock_api().set_version.reset_mock()
  125. self.hass().async_add_executor_job = AsyncMock()
  126. self.hass().async_add_executor_job.side_effect = [
  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.3), call(3.1)]
  137. )
  138. async def test_api_protocol_version_is_stable_once_successful(self):
  139. self.mock_api().set_version.reset_mock()
  140. self.hass().async_add_executor_job = AsyncMock()
  141. self.hass().async_add_executor_job.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. self.subject._protocol_configured = 3.4
  167. self.subject._api_protocol_version_index = None
  168. self.mock_api().set_version.reset_mock()
  169. self.subject._rotate_api_protocol_version()
  170. self.mock_api().set_version.assert_called_once_with(3.4)
  171. self.mock_api().set_version.reset_mock()
  172. self.hass().async_add_executor_job = AsyncMock()
  173. self.hass().async_add_executor_job.side_effect = [
  174. Exception("Error"),
  175. Exception("Error"),
  176. Exception("Error"),
  177. {"dps": {"1": False}},
  178. {"dps": {"1": False}},
  179. Exception("Error"),
  180. Exception("Error"),
  181. Exception("Error"),
  182. Exception("Error"),
  183. Exception("Error"),
  184. Exception("Error"),
  185. Exception("Error"),
  186. {"dps": {"1": False}},
  187. ]
  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_schedules_job(self):
  226. async_job = AsyncMock()
  227. self.hass().async_add_executor_job.return_value = async_job()
  228. await self.subject.async_set_property("1", False)
  229. self.hass().async_add_executor_job.assert_called_once()
  230. async_job.assert_awaited()
  231. async def test_set_property_immediately_stores_pending_updates(self):
  232. self.subject._cached_state = {"1": True}
  233. await self.subject.async_set_property("1", False)
  234. self.assertFalse(self.subject.get_property("1"))
  235. async def test_set_properties_takes_no_action_when_nothing_provided(self):
  236. with patch("asyncio.sleep") as mock:
  237. await self.subject.async_set_properties({})
  238. mock.assert_not_called()
  239. def test_anticipate_property_value_updates_cached_state(self):
  240. self.subject._cached_state = {"1": True}
  241. self.subject.anticipate_property_value("1", False)
  242. self.assertEqual(self.subject._cached_state["1"], False)
  243. def test_get_key_for_value_returns_key_from_object_matching_value(self):
  244. obj = {"key1": "value1", "key2": "value2"}
  245. self.assertEqual(
  246. TuyaLocalDevice.get_key_for_value(obj, "value1"),
  247. "key1",
  248. )
  249. self.assertEqual(
  250. TuyaLocalDevice.get_key_for_value(obj, "value2"),
  251. "key2",
  252. )
  253. def test_get_key_for_value_returns_fallback_when_value_not_found(self):
  254. obj = {"key1": "value1", "key2": "value2"}
  255. self.assertEqual(
  256. TuyaLocalDevice.get_key_for_value(obj, "value3", fallback="fb"),
  257. "fb",
  258. )
  259. def test_refresh_cached_state(self):
  260. # set up preconditions
  261. self.mock_api().status.return_value = {"dps": {"1": "CHANGED"}}
  262. self.subject._cached_state = {"1": "UNCHANGED", "updated_at": 123}
  263. # call the function under test
  264. self.subject._refresh_cached_state()
  265. # Did it call the API as expected?
  266. self.mock_api().status.assert_called_once()
  267. # Did it update the cached state?
  268. self.assertDictEqual(
  269. self.subject._cached_state,
  270. {"1": "CHANGED"} | self.subject._cached_state,
  271. )
  272. # Did it update the timestamp on the cached state?
  273. self.assertAlmostEqual(
  274. self.subject._cached_state["updated_at"],
  275. time(),
  276. delta=2,
  277. )
  278. def test_send_payload(self):
  279. # set up preconditions
  280. self.subject._pending_updates = {
  281. "1": {"value": "sample", "updated_at": time() - 2, "sent": False},
  282. }
  283. # call the function under test
  284. self.subject._send_payload("PAYLOAD")
  285. # did it send what it was asked?
  286. self.mock_api().send.assert_called_once_with("PAYLOAD")
  287. # did it mark the pending updates as sent?
  288. self.assertTrue(self.subject._pending_updates["1"]["sent"])
  289. # did it update the time on the pending updates?
  290. self.assertAlmostEqual(
  291. self.subject._pending_updates["1"]["updated_at"],
  292. time(),
  293. delta=2,
  294. )
  295. # did it lock and unlock when sending
  296. self.subject._lock.acquire.assert_called_once()
  297. self.subject._lock.release.assert_called_once()
  298. def test_actually_start(self):
  299. # Set up the preconditions
  300. self.subject.receive_loop = Mock()
  301. self.subject.receive_loop.return_value = "LOOP"
  302. self.hass().bus.async_listen_once.return_value = "LISTENER"
  303. self.subject._running = False
  304. # run the function under test
  305. self.subject.actually_start()
  306. # did it register a listener for EVENT_HOMEASSISTANT_STOP?
  307. self.hass().bus.async_listen_once.assert_called_once_with(
  308. EVENT_HOMEASSISTANT_STOP, self.subject.async_stop
  309. )
  310. self.assertEqual(self.subject._shutdown_listener, "LISTENER")
  311. # did it set the running flag?
  312. self.assertTrue(self.subject._running)
  313. # did it schedule the loop?
  314. self.hass().async_create_task.assert_called_once_with("LOOP")
  315. def test_start_starts_when_ha_running(self):
  316. # Set up preconditions
  317. self.hass().is_running = True
  318. self.hass().is_stopping = False
  319. listener = Mock()
  320. self.subject._startup_listener = listener
  321. self.subject.actually_start = Mock()
  322. # Call the function under test
  323. self.subject.start()
  324. # Did it actually start?
  325. self.subject.actually_start.assert_called_once()
  326. # Did it cancel the startup listener?
  327. self.assertIsNone(self.subject._startup_listener)
  328. listener.assert_called_once()
  329. def test_start_schedules_for_later_when_ha_starting(self):
  330. # Set up preconditions
  331. self.hass().is_running = False
  332. self.hass().is_stopping = False
  333. self.hass().bus.async_listen_once.return_value = "LISTENER"
  334. self.subject.actually_start = Mock()
  335. # Call the function under test
  336. self.subject.start()
  337. # Did it avoid actually starting?
  338. self.subject.actually_start.assert_not_called()
  339. # Did it register a listener?
  340. self.assertEqual(self.subject._startup_listener, "LISTENER")
  341. self.hass().bus.async_listen_once.assert_called_once_with(
  342. EVENT_HOMEASSISTANT_STARTED, self.subject.actually_start
  343. )
  344. def test_start_does_nothing_when_ha_stopping(self):
  345. # Set up preconditions
  346. self.hass().is_running = True
  347. self.hass().is_stopping = True
  348. self.subject.actually_start = Mock()
  349. # Call the function under test
  350. self.subject.start()
  351. # Did it avoid actually starting?
  352. self.subject.actually_start.assert_not_called()
  353. # Did it avoid registering a listener?
  354. self.hass().bus.async_listen_once.assert_not_called()
  355. self.assertIsNone(self.subject._startup_listener)
  356. async def test_async_stop(self):
  357. # Set up preconditions
  358. listener = Mock()
  359. self.subject._refresh_task = None
  360. self.subject._shutdown_listener = listener
  361. self.subject._children = [1, 2, 3]
  362. # Call the function under test
  363. await self.subject.async_stop()
  364. # Was the shutdown listener cancelled?
  365. listener.assert_called_once()
  366. self.assertIsNone(self.subject._shutdown_listener)
  367. # Were the child entities cleared?
  368. self.assertEqual(self.subject._children, [])
  369. # Did it wait for the refresh task to finish then clear it?
  370. # This doesn't work because AsyncMock only mocks awaitable method calls
  371. # but we want an awaitable object
  372. # refresh.assert_awaited_once()
  373. self.assertIsNone(self.subject._refresh_task)
  374. async def test_async_stop_when_not_running(self):
  375. # Set up preconditions
  376. self._refresh_task = None
  377. self.subject._shutdown_listener = None
  378. self.subject._children = []
  379. # Call the function under test
  380. await self.subject.async_stop()
  381. # Was the shutdown listener left empty?
  382. self.assertIsNone(self.subject._shutdown_listener)
  383. # Were the child entities cleared?
  384. self.assertEqual(self.subject._children, [])
  385. # Was the refresh task left empty?
  386. self.assertIsNone(self.subject._refresh_task)
  387. def test_register_first_entity_ha_running(self):
  388. # Set up preconditions
  389. self.subject._children = []
  390. self.subject._running = False
  391. self.subject._startup_listener = None
  392. self.subject.start = Mock()
  393. # Call the function under test
  394. self.subject.register_entity("Entity")
  395. # Was the entity added to the list?
  396. self.assertEqual(self.subject._children, ["Entity"])
  397. # Did we start the loop?
  398. self.subject.start.assert_called_once()
  399. def test_register_subsequent_entity_ha_running(self):
  400. # Set up preconditions
  401. self.subject._children = ["First"]
  402. self.subject._running = True
  403. self.subject._startup_listener = None
  404. self.subject.start = Mock()
  405. # Call the function under test
  406. self.subject.register_entity("Entity")
  407. # Was the entity added to the list?
  408. self.assertCountEqual(self.subject._children, ["First", "Entity"])
  409. # Did we avoid restarting the loop?
  410. self.subject.start.assert_not_called()
  411. def test_register_subsequent_entity_ha_starting(self):
  412. # Set up preconditions
  413. self.subject._children = ["First"]
  414. self.subject._running = False
  415. self.subject._startup_listener = Mock()
  416. self.subject.start = Mock()
  417. # Call the function under test
  418. self.subject.register_entity("Entity")
  419. # Was the entity added to the list?
  420. self.assertCountEqual(self.subject._children, ["First", "Entity"])
  421. # Did we avoid restarting the loop?
  422. self.subject.start.assert_not_called()
  423. async def test_unregister_one_of_many_entities(self):
  424. # Set up preconditions
  425. self.subject._children = ["First", "Second"]
  426. self.subject.async_stop = AsyncMock()
  427. # Call the function under test
  428. await self.subject.async_unregister_entity("First")
  429. # Was the entity removed from the list?
  430. self.assertCountEqual(self.subject._children, ["Second"])
  431. # Is the loop still running?
  432. self.subject.async_stop.assert_not_called()
  433. async def test_unregister_last_entity(self):
  434. # Set up preconditions
  435. self.subject._children = ["Last"]
  436. self.subject.async_stop = AsyncMock()
  437. # Call the function under test
  438. await self.subject.async_unregister_entity("Last")
  439. # Was the entity removed from the list?
  440. self.assertEqual(self.subject._children, [])
  441. # Was the loop stopped?
  442. self.subject.async_stop.assert_called_once()
  443. async def test_async_receive(self):
  444. # Set up preconditions
  445. def job(func, *args):
  446. return func(*args)
  447. status = Mock(
  448. name="status",
  449. return_value={"dps": {"1": "INIT", "2": 2}},
  450. )
  451. self.mock_api().status = status
  452. heartbeat = Mock(name="heartbeat")
  453. self.mock_api().heartbeat = heartbeat
  454. receive = Mock(name="receive", return_value={"1": "UPDATED"})
  455. self.mock_api().receive = receive
  456. async_add_executor_job = AsyncMock(
  457. name="async_add_executor_job",
  458. side_effect=job,
  459. )
  460. self.hass().async_add_executor_job = async_add_executor_job
  461. self.subject._running = True
  462. self.subject._cached_state = {"updated_at": 0}
  463. self.subject._api_protocol_version_index = 0
  464. self.subject._api_protocol_working = True
  465. # Call the function under test
  466. loop = self.subject.async_receive()
  467. result = await loop.__anext__()
  468. # Check that the loop was started
  469. self.mock_api().set_socketPersistent.assert_called_once_with(True)
  470. # Check that a full poll was done
  471. async_add_executor_job.assert_called_once()
  472. status.assert_called_once()
  473. self.assertDictEqual(result, {"1": "INIT", "2": 2})
  474. # Prepare for next round
  475. self.mock_api().set_socketPersistent.reset_mock()
  476. status.reset_mock()
  477. self.subject._cached_state["updated_at"] = time()
  478. # Call the function under test
  479. result = await loop.__anext__()
  480. # Check that the loop was not restarted
  481. self.mock_api().set_socketPersistent.assert_not_called()
  482. # Check that a heartbeat poll was done
  483. status.assert_not_called()
  484. heartbeat.assert_called_once()
  485. receive.assert_called_once()
  486. self.assertDictEqual(result, {"1": "UPDATED"})
  487. # Prepare for next iteration
  488. async_add_executor_job.reset_mock()
  489. self.subject._running = False
  490. # Call the function under test
  491. try:
  492. result = await loop.__anext__()
  493. self.assertTrue(False)
  494. # Check that the loop terminated
  495. except StopAsyncIteration:
  496. pass
  497. self.mock_api().set_socketPersistent.assert_called_once_with(False)