test_device.py 23 KB

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