test_device.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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 = Mock()
  316. self.subject.receive_loop.return_value = "LOOP"
  317. self.hass().bus.async_listen_once.return_value = "LISTENER"
  318. self.hass().async_create_task = Mock()
  319. self.subject._running = False
  320. # run the function under test
  321. self.subject.actually_start()
  322. # did it register a listener for EVENT_HOMEASSISTANT_STOP?
  323. self.hass().bus.async_listen_once.assert_called_once_with(
  324. EVENT_HOMEASSISTANT_STOP, self.subject.async_stop
  325. )
  326. self.assertEqual(self.subject._shutdown_listener, "LISTENER")
  327. # did it set the running flag?
  328. self.assertTrue(self.subject._running)
  329. # did it schedule the loop?
  330. # self.hass().async_create_task.assert_called_once()
  331. def test_start_starts_when_ha_running(self):
  332. # Set up preconditions
  333. self.hass().is_running = True
  334. listener = Mock()
  335. self.subject._startup_listener = listener
  336. self.subject.actually_start = Mock()
  337. # Call the function under test
  338. self.subject.start()
  339. # Did it actually start?
  340. self.subject.actually_start.assert_called_once()
  341. # Did it cancel the startup listener?
  342. self.assertIsNone(self.subject._startup_listener)
  343. listener.assert_called_once()
  344. def test_start_schedules_for_later_when_ha_starting(self):
  345. # Set up preconditions
  346. self.hass().is_running = False
  347. self.hass().bus.async_listen_once.return_value = "LISTENER"
  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 register a listener?
  354. self.assertEqual(self.subject._startup_listener, "LISTENER")
  355. self.hass().bus.async_listen_once.assert_called_once_with(
  356. EVENT_HOMEASSISTANT_STARTED, self.subject.actually_start
  357. )
  358. def test_start_does_nothing_when_ha_stopping(self):
  359. # Set up preconditions
  360. self.hass().is_running = True
  361. self.hass().is_stopping = True
  362. self.subject.actually_start = Mock()
  363. # Call the function under test
  364. self.subject.start()
  365. # Did it avoid actually starting?
  366. self.subject.actually_start.assert_not_called()
  367. # Did it avoid registering a listener?
  368. self.hass().bus.async_listen_once.assert_not_called()
  369. self.assertIsNone(self.subject._startup_listener)
  370. async def test_async_stop(self):
  371. # Set up preconditions
  372. listener = Mock()
  373. self.subject._refresh_task = None
  374. self.subject._shutdown_listener = listener
  375. self.subject._children = [1, 2, 3]
  376. # Call the function under test
  377. await self.subject.async_stop()
  378. # Shutdown listener doesn't get cancelled as HA does that
  379. listener.assert_not_called()
  380. # Were the child entities cleared?
  381. self.assertEqual(self.subject._children, [])
  382. # Did it wait for the refresh task to finish then clear it?
  383. # This doesn't work because AsyncMock only mocks awaitable method calls
  384. # but we want an awaitable object
  385. # refresh.assert_awaited_once()
  386. self.assertIsNone(self.subject._refresh_task)
  387. async def test_async_stop_when_not_running(self):
  388. # Set up preconditions
  389. self._refresh_task = None
  390. self.subject._shutdown_listener = None
  391. self.subject._children = []
  392. # Call the function under test
  393. await self.subject.async_stop()
  394. # Was the shutdown listener left empty?
  395. self.assertIsNone(self.subject._shutdown_listener)
  396. # Were the child entities cleared?
  397. self.assertEqual(self.subject._children, [])
  398. # Was the refresh task left empty?
  399. self.assertIsNone(self.subject._refresh_task)
  400. def test_register_first_entity_ha_running(self):
  401. # Set up preconditions
  402. self.subject._children = []
  403. self.subject._running = False
  404. self.subject._startup_listener = None
  405. self.subject.start = Mock()
  406. entity = AsyncMock()
  407. entity._config = Mock()
  408. entity._config.dps.return_value = []
  409. # despite the name, the below HA function is not async and does not need to be awaited
  410. entity.async_schedule_update_ha_state = Mock()
  411. # Call the function under test
  412. self.subject.register_entity(entity)
  413. # Was the entity added to the list?
  414. self.assertEqual(self.subject._children, [entity])
  415. # Did we start the loop?
  416. self.subject.start.assert_called_once()
  417. def test_register_subsequent_entity_ha_running(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 = True
  425. self.subject._startup_listener = None
  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. def test_register_subsequent_entity_ha_starting(self):
  434. # Set up preconditions
  435. first = AsyncMock()
  436. second = AsyncMock()
  437. second._config = Mock()
  438. second._config.dps.return_value = []
  439. self.subject._children = [first]
  440. self.subject._running = False
  441. self.subject._startup_listener = Mock()
  442. self.subject.start = Mock()
  443. # Call the function under test
  444. self.subject.register_entity(second)
  445. # Was the entity added to the list?
  446. self.assertCountEqual(self.subject._children, [first, second])
  447. # Did we avoid restarting the loop?
  448. self.subject.start.assert_not_called()
  449. async def test_unregister_one_of_many_entities(self):
  450. # Set up preconditions
  451. self.subject._children = ["First", "Second"]
  452. self.subject.async_stop = AsyncMock()
  453. # Call the function under test
  454. await self.subject.async_unregister_entity("First")
  455. # Was the entity removed from the list?
  456. self.assertCountEqual(self.subject._children, ["Second"])
  457. # Is the loop still running?
  458. self.subject.async_stop.assert_not_called()
  459. async def test_unregister_last_entity(self):
  460. # Set up preconditions
  461. self.subject._children = ["Last"]
  462. self.subject.async_stop = AsyncMock()
  463. # Call the function under test
  464. await self.subject.async_unregister_entity("Last")
  465. # Was the entity removed from the list?
  466. self.assertEqual(self.subject._children, [])
  467. # Was the loop stopped?
  468. self.subject.async_stop.assert_called_once()
  469. async def test_async_receive(self):
  470. # Set up preconditions
  471. self.mock_api().status.return_value = {"dps": {"1": "INIT", "2": 2}}
  472. self.mock_api().receive.return_value = {"1": "UPDATED"}
  473. self.subject._running = True
  474. self.subject._cached_state = {"updated_at": 0}
  475. # Call the function under test
  476. print("starting test loop...")
  477. loop = self.subject.async_receive()
  478. print("getting first iteration...")
  479. result = await loop.__anext__()
  480. # Check that the loop was started, but without persistent connection
  481. # since there was no state returned yet and it might need to negotiate
  482. # version.
  483. self.mock_api().set_socketPersistent.assert_called_once_with(False)
  484. # Check that a full poll was done
  485. self.mock_api().status.assert_called_once()
  486. self.assertDictEqual(result, {"1": "INIT", "2": 2, "full_poll": ANY})
  487. # Prepare for next round
  488. self.subject._cached_state = self.subject._cached_state | result
  489. self.mock_api().set_socketPersistent.reset_mock()
  490. self.mock_api().status.reset_mock()
  491. self.subject._cached_state["updated_at"] = time()
  492. # Call the function under test
  493. print("getting second iteration...")
  494. result = await loop.__anext__()
  495. # Check that a heartbeat poll was done
  496. self.mock_api().status.assert_not_called()
  497. self.mock_api().heartbeat.assert_called_once()
  498. self.mock_api().receive.assert_called_once()
  499. self.assertDictEqual(result, {"1": "UPDATED", "full_poll": ANY})
  500. # Check that the connection was made persistent now that data has been
  501. # returned
  502. self.mock_api().set_socketPersistent.assert_called_once_with(True)
  503. # Prepare for next iteration
  504. self.subject._running = False
  505. self.mock_api().set_socketPersistent.reset_mock()
  506. # Call the function under test
  507. print("getting last iteration...")
  508. try:
  509. result = await loop.__anext__()
  510. self.fail("Should have raised an exception to quit the loop")
  511. # Check that the loop terminated
  512. except StopAsyncIteration:
  513. pass
  514. self.mock_api().set_socketPersistent.assert_called_once_with(False)
  515. def test_should_poll(self):
  516. self.subject._cached_state = {"1": "sample", "updated_at": time()}
  517. self.subject._poll_only = False
  518. self.subject._temporary_poll = False
  519. # Test temporary poll via pause/resume
  520. self.assertFalse(self.subject.should_poll)
  521. self.subject.pause()
  522. self.assertTrue(self.subject.should_poll)
  523. self.subject.resume()
  524. self.assertFalse(self.subject.should_poll)
  525. # Test configured polling
  526. self.subject._poll_only = True
  527. self.assertTrue(self.subject.should_poll)
  528. self.subject._poll_only = False
  529. # Test initial polling
  530. self.subject._cached_state = {}
  531. self.assertTrue(self.subject.should_poll)