test_device.py 23 KB

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