test_config_flow.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """Tests for the config flow."""
  2. from unittest.mock import ANY, AsyncMock, MagicMock, patch
  3. from homeassistant.const import CONF_HOST, CONF_NAME
  4. import pytest
  5. from pytest_homeassistant_custom_component.common import MockConfigEntry
  6. import voluptuous as vol
  7. from custom_components.tuya_local import (
  8. config_flow,
  9. async_migrate_entry,
  10. async_setup_entry,
  11. )
  12. from custom_components.tuya_local.const import (
  13. CONF_CLIMATE,
  14. CONF_DEVICE_ID,
  15. CONF_FAN,
  16. CONF_HUMIDIFIER,
  17. CONF_LIGHT,
  18. CONF_LOCAL_KEY,
  19. CONF_LOCK,
  20. CONF_SWITCH,
  21. CONF_TYPE,
  22. DOMAIN,
  23. )
  24. @pytest.fixture(autouse=True)
  25. def auto_enable_custom_integrations(enable_custom_integrations):
  26. yield
  27. @pytest.fixture
  28. def bypass_setup():
  29. """Prevent actual setup of the integration after config flow."""
  30. with patch(
  31. "custom_components.tuya_local.async_setup_entry",
  32. return_value=True,
  33. ):
  34. yield
  35. async def test_init_entry(hass):
  36. """Test initialisation of the config flow."""
  37. entry = MockConfigEntry(
  38. domain=DOMAIN,
  39. version=2,
  40. title="test",
  41. data={
  42. CONF_DEVICE_ID: "deviceid",
  43. CONF_HOST: "hostname",
  44. CONF_LOCAL_KEY: "localkey",
  45. CONF_TYPE: "kogan_heater",
  46. CONF_CLIMATE: True,
  47. CONF_LOCK: True,
  48. },
  49. )
  50. entry.add_to_hass(hass)
  51. await hass.config_entries.async_setup(entry.entry_id)
  52. await hass.async_block_till_done()
  53. assert hass.states.get("climate.test")
  54. assert hass.states.get("lock.test")
  55. @patch("custom_components.tuya_local.setup_device")
  56. async def test_migrate_entry(mock_setup, hass):
  57. """Test migration from old entry format."""
  58. mock_device = MagicMock()
  59. mock_device.async_inferred_type = AsyncMock(return_value="heater")
  60. mock_setup.return_value = mock_device
  61. entry = MockConfigEntry(
  62. domain=DOMAIN,
  63. version=1,
  64. title="test",
  65. data={
  66. CONF_DEVICE_ID: "deviceid",
  67. CONF_HOST: "hostname",
  68. CONF_LOCAL_KEY: "localkey",
  69. CONF_TYPE: "auto",
  70. CONF_CLIMATE: True,
  71. "child_lock": True,
  72. "display_light": True,
  73. },
  74. )
  75. assert await async_migrate_entry(hass, entry)
  76. async def test_flow_user_init(hass):
  77. """Test the initialisation of the form in the first step of the config flow."""
  78. result = await hass.config_entries.flow.async_init(
  79. DOMAIN, context={"source": "user"}
  80. )
  81. expected = {
  82. "data_schema": ANY,
  83. "description_placeholders": None,
  84. "errors": {},
  85. "flow_id": ANY,
  86. "handler": DOMAIN,
  87. "step_id": "user",
  88. "type": "form",
  89. "last_step": ANY,
  90. }
  91. assert expected == result
  92. # Check the schema. Simple comparison does not work since they are not
  93. # the same object
  94. try:
  95. result["data_schema"](
  96. {CONF_DEVICE_ID: "test", CONF_LOCAL_KEY: "test", CONF_HOST: "test"}
  97. )
  98. except vol.MultipleInvalid:
  99. assert False
  100. try:
  101. result["data_schema"]({CONF_DEVICE_ID: "missing_some"})
  102. assert False
  103. except vol.MultipleInvalid:
  104. pass
  105. @patch("custom_components.tuya_local.config_flow.TuyaLocalDevice")
  106. async def test_async_test_connection_valid(mock_device, hass):
  107. """Test that device is returned when connection is valid."""
  108. mock_instance = AsyncMock()
  109. mock_instance.has_returned_state = True
  110. mock_device.return_value = mock_instance
  111. device = await config_flow.async_test_connection(
  112. {
  113. CONF_DEVICE_ID: "deviceid",
  114. CONF_LOCAL_KEY: "localkey",
  115. CONF_HOST: "hostname",
  116. },
  117. hass,
  118. )
  119. assert device == mock_instance
  120. @patch("custom_components.tuya_local.config_flow.TuyaLocalDevice")
  121. async def test_async_test_connection_invalid(mock_device, hass):
  122. """Test that None is returned when connection is invalid."""
  123. mock_instance = AsyncMock()
  124. mock_instance.has_returned_state = False
  125. mock_device.return_value = mock_instance
  126. device = await config_flow.async_test_connection(
  127. {
  128. CONF_DEVICE_ID: "deviceid",
  129. CONF_LOCAL_KEY: "localkey",
  130. CONF_HOST: "hostname",
  131. },
  132. hass,
  133. )
  134. assert device is None
  135. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  136. async def test_flow_user_init_invalid_config(mock_test, hass):
  137. """Test errors populated when config is invalid."""
  138. mock_test.return_value = None
  139. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  140. result = await hass.config_entries.flow.async_configure(
  141. flow["flow_id"],
  142. user_input={
  143. CONF_DEVICE_ID: "deviceid",
  144. CONF_HOST: "hostname",
  145. CONF_LOCAL_KEY: "badkey",
  146. },
  147. )
  148. assert {"base": "connection"} == result["errors"]
  149. def setup_device_mock(mock, failure=False, type="test"):
  150. mock_type = MagicMock()
  151. mock_type.legacy_type = type
  152. mock_iter = MagicMock()
  153. mock_iter.__aiter__.return_value = [mock_type] if not failure else []
  154. mock.async_possible_types = MagicMock(return_value=mock_iter)
  155. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  156. async def test_flow_user_init_data_valid(mock_test, hass):
  157. """Test we advance to the next step when connection config is valid."""
  158. mock_device = MagicMock()
  159. setup_device_mock(mock_device)
  160. mock_test.return_value = mock_device
  161. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  162. result = await hass.config_entries.flow.async_configure(
  163. flow["flow_id"],
  164. user_input={
  165. CONF_DEVICE_ID: "deviceid",
  166. CONF_HOST: "hostname",
  167. CONF_LOCAL_KEY: "localkey",
  168. },
  169. )
  170. assert "form" == result["type"]
  171. assert "select_type" == result["step_id"]
  172. @patch.object(config_flow.ConfigFlowHandler, "device")
  173. async def test_flow_select_type_init(mock_device, hass):
  174. """Test the initialisation of the form in the 2nd step of the config flow."""
  175. setup_device_mock(mock_device)
  176. result = await hass.config_entries.flow.async_init(
  177. DOMAIN, context={"source": "select_type"}
  178. )
  179. expected = {
  180. "data_schema": ANY,
  181. "description_placeholders": None,
  182. "errors": None,
  183. "flow_id": ANY,
  184. "handler": DOMAIN,
  185. "step_id": "select_type",
  186. "type": "form",
  187. "last_step": ANY,
  188. }
  189. assert expected == result
  190. # Check the schema. Simple comparison does not work since they are not
  191. # the same object
  192. try:
  193. result["data_schema"]({CONF_TYPE: "test"})
  194. except vol.MultipleInvalid:
  195. assert False
  196. try:
  197. result["data_schema"]({CONF_TYPE: "not_test"})
  198. assert False
  199. except vol.MultipleInvalid:
  200. pass
  201. @patch.object(config_flow.ConfigFlowHandler, "device")
  202. async def test_flow_select_type_aborts_when_no_match(mock_device, hass):
  203. """Test the flow aborts when an unsupported device is used."""
  204. setup_device_mock(mock_device, failure=True)
  205. result = await hass.config_entries.flow.async_init(
  206. DOMAIN, context={"source": "select_type"}
  207. )
  208. assert result["type"] == "abort"
  209. assert result["reason"] == "not_supported"
  210. @patch.object(config_flow.ConfigFlowHandler, "device")
  211. async def test_flow_select_type_data_valid(mock_device, hass):
  212. """Test the flow continues when valid data is supplied."""
  213. setup_device_mock(mock_device, type="kogan_switch")
  214. flow = await hass.config_entries.flow.async_init(
  215. DOMAIN, context={"source": "select_type"}
  216. )
  217. result = await hass.config_entries.flow.async_configure(
  218. flow["flow_id"],
  219. user_input={CONF_TYPE: "kogan_switch"},
  220. )
  221. assert "form" == result["type"]
  222. assert "choose_entities" == result["step_id"]
  223. async def test_flow_choose_entities_init(hass):
  224. """Test the initialisation of the form in the 3rd step of the config flow."""
  225. with patch.dict(config_flow.ConfigFlowHandler.data, {CONF_TYPE: "kogan_switch"}):
  226. result = await hass.config_entries.flow.async_init(
  227. DOMAIN, context={"source": "choose_entities"}
  228. )
  229. expected = {
  230. "data_schema": ANY,
  231. "description_placeholders": None,
  232. "errors": None,
  233. "flow_id": ANY,
  234. "handler": DOMAIN,
  235. "step_id": "choose_entities",
  236. "type": "form",
  237. "last_step": ANY,
  238. }
  239. assert expected == result
  240. # Check the schema. Simple comparison does not work since they are not
  241. # the same object
  242. try:
  243. result["data_schema"]({CONF_NAME: "test", CONF_SWITCH: True})
  244. except vol.MultipleInvalid:
  245. assert False
  246. try:
  247. result["data_schema"]({CONF_CLIMATE: True})
  248. assert False
  249. except vol.MultipleInvalid:
  250. pass
  251. async def test_flow_choose_entities_creates_config_entry(hass, bypass_setup):
  252. """Test the flow ends when data is valid."""
  253. with patch.dict(
  254. config_flow.ConfigFlowHandler.data,
  255. {
  256. CONF_DEVICE_ID: "deviceid",
  257. CONF_LOCAL_KEY: "localkey",
  258. CONF_HOST: "hostname",
  259. CONF_TYPE: "kogan_heater",
  260. },
  261. ):
  262. flow = await hass.config_entries.flow.async_init(
  263. DOMAIN, context={"source": "choose_entities"}
  264. )
  265. result = await hass.config_entries.flow.async_configure(
  266. flow["flow_id"],
  267. user_input={CONF_NAME: "test", CONF_CLIMATE: True, CONF_LOCK: False},
  268. )
  269. expected = {
  270. "version": 2,
  271. "type": "create_entry",
  272. "flow_id": ANY,
  273. "handler": DOMAIN,
  274. "title": "test",
  275. "description": None,
  276. "description_placeholders": None,
  277. "result": ANY,
  278. "options": {},
  279. "data": {
  280. CONF_CLIMATE: True,
  281. CONF_DEVICE_ID: "deviceid",
  282. CONF_HOST: "hostname",
  283. CONF_LOCAL_KEY: "localkey",
  284. CONF_LOCK: False,
  285. CONF_TYPE: "kogan_heater",
  286. },
  287. }
  288. assert expected == result
  289. async def test_options_flow_init(hass):
  290. """Test config flow options."""
  291. config_entry = MockConfigEntry(
  292. domain=DOMAIN,
  293. unique_id="uniqueid",
  294. data={
  295. CONF_DEVICE_ID: "deviceid",
  296. CONF_HOST: "hostname",
  297. CONF_LOCAL_KEY: "localkey",
  298. CONF_NAME: "test",
  299. CONF_SWITCH: True,
  300. CONF_TYPE: "kogan_switch",
  301. },
  302. )
  303. config_entry.add_to_hass(hass)
  304. assert await hass.config_entries.async_setup(config_entry.entry_id)
  305. await hass.async_block_till_done()
  306. # show initial form
  307. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  308. assert "form" == result["type"]
  309. assert "user" == result["step_id"]
  310. assert {} == result["errors"]
  311. assert result["data_schema"](
  312. {
  313. CONF_HOST: "hostname",
  314. CONF_LOCAL_KEY: "localkey",
  315. CONF_SWITCH: True,
  316. }
  317. )
  318. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  319. async def test_options_flow_modifies_config(mock_test, hass):
  320. mock_device = MagicMock()
  321. mock_test.return_value = mock_device
  322. config_entry = MockConfigEntry(
  323. domain=DOMAIN,
  324. unique_id="uniqueid",
  325. data={
  326. CONF_CLIMATE: True,
  327. CONF_DEVICE_ID: "deviceid",
  328. CONF_HOST: "hostname",
  329. CONF_LOCAL_KEY: "localkey",
  330. CONF_LOCK: True,
  331. CONF_NAME: "test",
  332. CONF_TYPE: "kogan_heater",
  333. },
  334. )
  335. config_entry.add_to_hass(hass)
  336. assert await hass.config_entries.async_setup(config_entry.entry_id)
  337. await hass.async_block_till_done()
  338. # show initial form
  339. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  340. # submit updated config
  341. result = await hass.config_entries.options.async_configure(
  342. form["flow_id"],
  343. user_input={
  344. CONF_CLIMATE: True,
  345. CONF_HOST: "new_hostname",
  346. CONF_LOCAL_KEY: "new_key",
  347. CONF_LOCK: False,
  348. },
  349. )
  350. expected = {
  351. CONF_CLIMATE: True,
  352. CONF_HOST: "new_hostname",
  353. CONF_LOCAL_KEY: "new_key",
  354. CONF_LOCK: False,
  355. }
  356. assert "create_entry" == result["type"]
  357. assert "" == result["title"]
  358. assert result["result"] is True
  359. assert expected == result["data"]
  360. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  361. async def test_options_flow_fails_when_connection_fails(mock_test, hass):
  362. mock_test.return_value = None
  363. config_entry = MockConfigEntry(
  364. domain=DOMAIN,
  365. unique_id="uniqueid",
  366. data={
  367. CONF_DEVICE_ID: "deviceid",
  368. CONF_HOST: "hostname",
  369. CONF_LOCAL_KEY: "localkey",
  370. CONF_NAME: "test",
  371. CONF_SWITCH: True,
  372. CONF_TYPE: "kogan_switch",
  373. },
  374. )
  375. config_entry.add_to_hass(hass)
  376. assert await hass.config_entries.async_setup(config_entry.entry_id)
  377. await hass.async_block_till_done()
  378. # show initial form
  379. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  380. # submit updated config
  381. result = await hass.config_entries.options.async_configure(
  382. form["flow_id"],
  383. user_input={
  384. CONF_HOST: "new_hostname",
  385. CONF_LOCAL_KEY: "new_key",
  386. CONF_SWITCH: False,
  387. },
  388. )
  389. assert "form" == result["type"]
  390. assert "user" == result["step_id"]
  391. assert {"base": "connection"} == result["errors"]
  392. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  393. async def test_options_flow_fails_when_config_is_missing(mock_test, hass):
  394. mock_device = MagicMock()
  395. mock_test.return_value = mock_device
  396. config_entry = MockConfigEntry(
  397. domain=DOMAIN,
  398. unique_id="uniqueid",
  399. data={
  400. CONF_DEVICE_ID: "deviceid",
  401. CONF_HOST: "hostname",
  402. CONF_LOCAL_KEY: "localkey",
  403. CONF_NAME: "test",
  404. CONF_SWITCH: True,
  405. CONF_TYPE: "non_existing",
  406. },
  407. )
  408. config_entry.add_to_hass(hass)
  409. assert await hass.config_entries.async_setup(config_entry.entry_id)
  410. await hass.async_block_till_done()
  411. # show initial form
  412. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  413. assert result["type"] == "abort"
  414. assert result["reason"] == "not_supported"
  415. # More tests to exercise code branches that earlier tests missed.
  416. @patch("custom_components.tuya_local.setup_device")
  417. async def test_async_setup_entry_for_dehumidifier(mock_setup, hass):
  418. """Test setting up based on a config entry. Repeats test_init_entry."""
  419. config_entry = MockConfigEntry(
  420. domain=DOMAIN,
  421. unique_id="uniqueid",
  422. data={
  423. CONF_CLIMATE: False,
  424. CONF_DEVICE_ID: "deviceid",
  425. CONF_FAN: True,
  426. CONF_HOST: "hostname",
  427. CONF_HUMIDIFIER: True,
  428. CONF_LIGHT: True,
  429. CONF_LOCK: False,
  430. CONF_LOCAL_KEY: "localkey",
  431. CONF_NAME: "test",
  432. CONF_TYPE: "dehumidifier",
  433. },
  434. )
  435. assert await async_setup_entry(hass, config_entry)
  436. @patch("custom_components.tuya_local.setup_device")
  437. async def test_async_setup_entry_for_switch(mock_device, hass):
  438. """Test setting up based on a config entry. Repeats test_init_entry."""
  439. config_entry = MockConfigEntry(
  440. domain=DOMAIN,
  441. unique_id="uniqueid",
  442. data={
  443. CONF_DEVICE_ID: "deviceid",
  444. CONF_HOST: "hostname",
  445. CONF_LOCAL_KEY: "localkey",
  446. CONF_NAME: "test",
  447. CONF_SWITCH: True,
  448. CONF_TYPE: "kogan_switch",
  449. },
  450. )
  451. assert await async_setup_entry(hass, config_entry)