test_device.py 22 KB

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