test_device.py 23 KB

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