test_device.py 22 KB

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