test_device.py 23 KB

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