test_config_flow.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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=3,
  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": 3,
  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. version=3,
  294. unique_id="uniqueid",
  295. data={
  296. CONF_DEVICE_ID: "deviceid",
  297. CONF_HOST: "hostname",
  298. CONF_LOCAL_KEY: "localkey",
  299. CONF_NAME: "test",
  300. CONF_SWITCH: True,
  301. CONF_TYPE: "kogan_switch",
  302. },
  303. )
  304. config_entry.add_to_hass(hass)
  305. assert await hass.config_entries.async_setup(config_entry.entry_id)
  306. await hass.async_block_till_done()
  307. # show initial form
  308. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  309. assert "form" == result["type"]
  310. assert "user" == result["step_id"]
  311. assert {} == result["errors"]
  312. assert result["data_schema"](
  313. {
  314. CONF_HOST: "hostname",
  315. CONF_LOCAL_KEY: "localkey",
  316. CONF_SWITCH: True,
  317. }
  318. )
  319. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  320. async def test_options_flow_modifies_config(mock_test, hass):
  321. mock_device = MagicMock()
  322. mock_test.return_value = mock_device
  323. config_entry = MockConfigEntry(
  324. domain=DOMAIN,
  325. version=3,
  326. unique_id="uniqueid",
  327. data={
  328. CONF_CLIMATE: True,
  329. CONF_DEVICE_ID: "deviceid",
  330. CONF_HOST: "hostname",
  331. CONF_LOCAL_KEY: "localkey",
  332. CONF_LOCK: True,
  333. CONF_NAME: "test",
  334. CONF_TYPE: "kogan_heater",
  335. },
  336. )
  337. config_entry.add_to_hass(hass)
  338. assert await hass.config_entries.async_setup(config_entry.entry_id)
  339. await hass.async_block_till_done()
  340. # show initial form
  341. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  342. # submit updated config
  343. result = await hass.config_entries.options.async_configure(
  344. form["flow_id"],
  345. user_input={
  346. CONF_CLIMATE: True,
  347. CONF_HOST: "new_hostname",
  348. CONF_LOCAL_KEY: "new_key",
  349. CONF_LOCK: False,
  350. },
  351. )
  352. expected = {
  353. CONF_CLIMATE: True,
  354. CONF_HOST: "new_hostname",
  355. CONF_LOCAL_KEY: "new_key",
  356. CONF_LOCK: False,
  357. }
  358. assert "create_entry" == result["type"]
  359. assert "" == result["title"]
  360. assert result["result"] is True
  361. assert expected == result["data"]
  362. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  363. async def test_options_flow_fails_when_connection_fails(mock_test, hass):
  364. mock_test.return_value = None
  365. config_entry = MockConfigEntry(
  366. domain=DOMAIN,
  367. version=3,
  368. unique_id="uniqueid",
  369. data={
  370. CONF_DEVICE_ID: "deviceid",
  371. CONF_HOST: "hostname",
  372. CONF_LOCAL_KEY: "localkey",
  373. CONF_NAME: "test",
  374. CONF_SWITCH: True,
  375. CONF_TYPE: "kogan_switch",
  376. },
  377. )
  378. config_entry.add_to_hass(hass)
  379. assert await hass.config_entries.async_setup(config_entry.entry_id)
  380. await hass.async_block_till_done()
  381. # show initial form
  382. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  383. # submit updated config
  384. result = await hass.config_entries.options.async_configure(
  385. form["flow_id"],
  386. user_input={
  387. CONF_HOST: "new_hostname",
  388. CONF_LOCAL_KEY: "new_key",
  389. CONF_SWITCH: False,
  390. },
  391. )
  392. assert "form" == result["type"]
  393. assert "user" == result["step_id"]
  394. assert {"base": "connection"} == result["errors"]
  395. @patch("custom_components.tuya_local.config_flow.async_test_connection")
  396. async def test_options_flow_fails_when_config_is_missing(mock_test, hass):
  397. mock_device = MagicMock()
  398. mock_test.return_value = mock_device
  399. config_entry = MockConfigEntry(
  400. domain=DOMAIN,
  401. version=3,
  402. unique_id="uniqueid",
  403. data={
  404. CONF_DEVICE_ID: "deviceid",
  405. CONF_HOST: "hostname",
  406. CONF_LOCAL_KEY: "localkey",
  407. CONF_NAME: "test",
  408. CONF_SWITCH: True,
  409. CONF_TYPE: "non_existing",
  410. },
  411. )
  412. config_entry.add_to_hass(hass)
  413. assert await hass.config_entries.async_setup(config_entry.entry_id)
  414. await hass.async_block_till_done()
  415. # show initial form
  416. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  417. assert result["type"] == "abort"
  418. assert result["reason"] == "not_supported"
  419. # More tests to exercise code branches that earlier tests missed.
  420. @patch("custom_components.tuya_local.setup_device")
  421. async def test_async_setup_entry_for_dehumidifier(mock_setup, hass):
  422. """Test setting up based on a config entry. Repeats test_init_entry."""
  423. config_entry = MockConfigEntry(
  424. domain=DOMAIN,
  425. version=3,
  426. unique_id="uniqueid",
  427. data={
  428. CONF_CLIMATE: False,
  429. CONF_DEVICE_ID: "deviceid",
  430. CONF_FAN: True,
  431. CONF_HOST: "hostname",
  432. CONF_HUMIDIFIER: True,
  433. CONF_LIGHT: True,
  434. CONF_LOCK: False,
  435. CONF_LOCAL_KEY: "localkey",
  436. CONF_NAME: "test",
  437. CONF_TYPE: "dehumidifier",
  438. },
  439. )
  440. assert await async_setup_entry(hass, config_entry)
  441. @patch("custom_components.tuya_local.setup_device")
  442. async def test_async_setup_entry_for_switch(mock_device, hass):
  443. """Test setting up based on a config entry. Repeats test_init_entry."""
  444. config_entry = MockConfigEntry(
  445. domain=DOMAIN,
  446. version=3,
  447. unique_id="uniqueid",
  448. data={
  449. CONF_DEVICE_ID: "deviceid",
  450. CONF_HOST: "hostname",
  451. CONF_LOCAL_KEY: "localkey",
  452. CONF_NAME: "test",
  453. CONF_SWITCH: True,
  454. CONF_TYPE: "kogan_switch",
  455. },
  456. )
  457. assert await async_setup_entry(hass, config_entry)