4
0

test_config_flow.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. """Tests for the config flow."""
  2. from unittest.mock import AsyncMock
  3. import probatio as vol
  4. import pytest
  5. from homeassistant.const import CONF_HOST, CONF_NAME
  6. from homeassistant.data_entry_flow import FlowResultType
  7. from homeassistant.exceptions import ConfigEntryNotReady
  8. from homeassistant.helpers import entity_registry as er
  9. from pytest_homeassistant.common import MockConfigEntry
  10. from custom_components.tuya_local import (
  11. async_migrate_entry,
  12. async_setup_entry,
  13. async_unload_entry,
  14. async_update_entry,
  15. config_flow,
  16. get_device_unique_id,
  17. )
  18. from custom_components.tuya_local.const import (
  19. CONF_DEVICE_CID,
  20. CONF_DEVICE_ID,
  21. CONF_LOCAL_KEY,
  22. CONF_POLL_ONLY,
  23. CONF_PROTOCOL_VERSION,
  24. CONF_TYPE,
  25. DOMAIN,
  26. )
  27. # Designed to contain "special" characters that users constantly suspect.
  28. TESTKEY = ")<jO<@)'P1|kR$Kd"
  29. @pytest.fixture(autouse=True)
  30. def auto_enable_custom_integrations(enable_custom_integrations):
  31. yield
  32. @pytest.fixture(autouse=True)
  33. def prevent_task_creation(mocker):
  34. mocker.patch("custom_components.tuya_local.device.TuyaLocalDevice.register_entity")
  35. yield
  36. @pytest.fixture(autouse=True)
  37. def bypass_discovery(mocker):
  38. """Don't open real LAN discovery sockets during setup in these tests.
  39. The discovery listener is exercised directly in tests/test_discovery.py.
  40. """
  41. mocker.patch(
  42. "custom_components.tuya_local.async_start_discovery",
  43. new=AsyncMock(),
  44. )
  45. yield
  46. @pytest.fixture
  47. def bypass_setup(mocker):
  48. """Prevent actual setup of the integration after config flow."""
  49. mocker.patch("custom_components.tuya_local.async_setup_entry", return_value=True)
  50. yield
  51. @pytest.fixture
  52. def bypass_data_fetch(mocker):
  53. """Prevent actual data fetching from the device."""
  54. mocker.patch("tinytuya.Device.status", return_value={"1": True})
  55. yield
  56. @pytest.mark.asyncio
  57. async def test_init_entry(hass, bypass_data_fetch):
  58. """Test initialisation of the config flow."""
  59. entry = MockConfigEntry(
  60. domain=DOMAIN,
  61. version=11,
  62. title="test",
  63. data={
  64. CONF_DEVICE_ID: "deviceid",
  65. CONF_HOST: "hostname",
  66. CONF_LOCAL_KEY: TESTKEY,
  67. CONF_POLL_ONLY: False,
  68. CONF_PROTOCOL_VERSION: "auto",
  69. CONF_TYPE: "kogan_kahtp_heater",
  70. CONF_DEVICE_CID: None,
  71. },
  72. options={},
  73. )
  74. entry.add_to_hass(hass)
  75. await hass.config_entries.async_setup(entry.entry_id)
  76. await hass.async_block_till_done()
  77. assert hass.states.get("climate.test")
  78. assert hass.states.get("lock.test_child_lock")
  79. @pytest.mark.asyncio
  80. @pytest.mark.parametrize("refresh_error", [RuntimeError("boom"), None])
  81. async def test_async_setup_entry_cleans_up_failed_device(hass, mocker, refresh_error):
  82. """Failed runtime setup should not leave stale device state cached."""
  83. mock_device = mocker.MagicMock()
  84. if refresh_error is None:
  85. mock_device.async_refresh = mocker.AsyncMock()
  86. mock_device.has_returned_state = False
  87. else:
  88. mock_device.async_refresh = mocker.AsyncMock(side_effect=refresh_error)
  89. def fake_setup_device(hass, config):
  90. hass.data.setdefault(DOMAIN, {})
  91. hass.data[DOMAIN]["deviceid"] = {
  92. "device": mock_device,
  93. "tuyadevice": mock_device._api,
  94. "tuyadevicelock": mocker.MagicMock(),
  95. }
  96. return mock_device
  97. mocker.patch(
  98. "custom_components.tuya_local.setup_device", side_effect=fake_setup_device
  99. )
  100. entry = MockConfigEntry(
  101. domain=DOMAIN,
  102. version=13,
  103. minor_version=18,
  104. title="test",
  105. data={
  106. CONF_DEVICE_ID: "deviceid",
  107. CONF_HOST: "hostname",
  108. CONF_LOCAL_KEY: TESTKEY,
  109. CONF_POLL_ONLY: False,
  110. CONF_PROTOCOL_VERSION: 3.4,
  111. CONF_TYPE: "kogan_kahtp_heater",
  112. },
  113. options={},
  114. )
  115. with pytest.raises(ConfigEntryNotReady):
  116. await async_setup_entry(hass, entry)
  117. assert "deviceid" not in hass.data.get(DOMAIN, {})
  118. mock_device._api.set_socketPersistent.assert_called_with(False)
  119. @pytest.mark.asyncio
  120. async def test_async_unload_entry_ignores_missing_device_data(hass):
  121. """Unload should tolerate entries that failed before device data was cached."""
  122. hass.data[DOMAIN] = {}
  123. entry = MockConfigEntry(
  124. domain=DOMAIN,
  125. version=13,
  126. minor_version=18,
  127. title="test",
  128. data={
  129. CONF_DEVICE_ID: "deviceid",
  130. CONF_HOST: "hostname",
  131. CONF_LOCAL_KEY: TESTKEY,
  132. CONF_POLL_ONLY: False,
  133. CONF_PROTOCOL_VERSION: 3.4,
  134. CONF_TYPE: "kogan_kahtp_heater",
  135. },
  136. options={},
  137. )
  138. assert await async_unload_entry(hass, entry)
  139. @pytest.mark.asyncio
  140. async def test_async_update_entry_reloads_config_entry(hass, mocker):
  141. """Entry updates should delegate lifecycle management to Home Assistant."""
  142. entry = MockConfigEntry(
  143. domain=DOMAIN,
  144. data={CONF_DEVICE_ID: "deviceid"},
  145. )
  146. schedule_reload = mocker.patch.object(
  147. hass.config_entries,
  148. "async_schedule_reload",
  149. )
  150. unload_entry = mocker.patch(
  151. "custom_components.tuya_local.async_unload_entry",
  152. new=AsyncMock(),
  153. )
  154. setup_entry = mocker.patch(
  155. "custom_components.tuya_local.async_setup_entry",
  156. new=AsyncMock(),
  157. )
  158. await async_update_entry(hass, entry)
  159. schedule_reload.assert_called_once_with(entry.entry_id)
  160. unload_entry.assert_not_awaited()
  161. setup_entry.assert_not_awaited()
  162. @pytest.mark.asyncio
  163. async def test_migrate_entry(hass, mocker):
  164. """Test migration from old entry format."""
  165. mock_device = mocker.MagicMock()
  166. mock_device.async_inferred_type = mocker.AsyncMock(
  167. return_value="goldair_gpph_heater"
  168. )
  169. mocker.patch("custom_components.tuya_local.setup_device", return_value=mock_device)
  170. entry = MockConfigEntry(
  171. domain=DOMAIN,
  172. version=1,
  173. title="test",
  174. data={
  175. CONF_DEVICE_ID: "deviceid",
  176. CONF_HOST: "hostname",
  177. CONF_LOCAL_KEY: TESTKEY,
  178. CONF_TYPE: "auto",
  179. "climate": True,
  180. "child_lock": True,
  181. "display_light": True,
  182. },
  183. )
  184. entry.add_to_hass(hass)
  185. assert await async_migrate_entry(hass, entry)
  186. mock_device.async_inferred_type = mocker.AsyncMock(return_value=None)
  187. mock_device.reset_mock()
  188. entry = MockConfigEntry(
  189. domain=DOMAIN,
  190. version=1,
  191. title="test2",
  192. data={
  193. CONF_DEVICE_ID: "deviceid",
  194. CONF_HOST: "hostname",
  195. CONF_LOCAL_KEY: TESTKEY,
  196. CONF_TYPE: "unknown",
  197. "climate": False,
  198. },
  199. )
  200. entry.add_to_hass(hass)
  201. with pytest.raises(KeyError):
  202. await async_migrate_entry(hass, entry)
  203. mock_device.reset_mock()
  204. entry = MockConfigEntry(
  205. domain=DOMAIN,
  206. version=2,
  207. title="test3",
  208. data={
  209. CONF_DEVICE_ID: "deviceid",
  210. CONF_HOST: "hostname",
  211. CONF_LOCAL_KEY: TESTKEY,
  212. CONF_TYPE: "auto",
  213. },
  214. options={
  215. "climate": False,
  216. },
  217. )
  218. entry.add_to_hass(hass)
  219. with pytest.raises(KeyError):
  220. await async_migrate_entry(hass, entry)
  221. mock_device.async_inferred_type = mocker.AsyncMock(return_value="smartplugv1")
  222. mock_device.reset_mock()
  223. entry = MockConfigEntry(
  224. domain=DOMAIN,
  225. version=3,
  226. title="test4",
  227. data={
  228. CONF_DEVICE_ID: "deviceid",
  229. CONF_HOST: "hostname",
  230. CONF_LOCAL_KEY: TESTKEY,
  231. CONF_TYPE: "smartplugv1",
  232. },
  233. options={
  234. "switch": True,
  235. },
  236. )
  237. entry.add_to_hass(hass)
  238. assert await async_migrate_entry(hass, entry)
  239. mock_device.async_inferred_type = mocker.AsyncMock(return_value="smartplugv2")
  240. mock_device.reset_mock()
  241. entry = MockConfigEntry(
  242. domain=DOMAIN,
  243. version=3,
  244. title="test5",
  245. data={
  246. CONF_DEVICE_ID: "deviceid",
  247. CONF_HOST: "hostname",
  248. CONF_LOCAL_KEY: TESTKEY,
  249. CONF_TYPE: "smartplugv1",
  250. },
  251. options={
  252. "switch": True,
  253. },
  254. )
  255. entry.add_to_hass(hass)
  256. assert await async_migrate_entry(hass, entry)
  257. mock_device.async_inferred_type = mocker.AsyncMock(
  258. return_value="goldair_dehumidifier"
  259. )
  260. mock_device.reset_mock()
  261. entry = MockConfigEntry(
  262. domain=DOMAIN,
  263. version=4,
  264. title="test6",
  265. data={
  266. CONF_DEVICE_ID: "deviceid",
  267. CONF_HOST: "hostname",
  268. CONF_LOCAL_KEY: TESTKEY,
  269. CONF_TYPE: "goldair_dehumidifier",
  270. },
  271. options={
  272. "humidifier": True,
  273. "fan": True,
  274. "light": True,
  275. "lock": False,
  276. "switch": True,
  277. },
  278. )
  279. entry.add_to_hass(hass)
  280. assert await async_migrate_entry(hass, entry)
  281. mock_device.async_inferred_type = mocker.AsyncMock(
  282. return_value="grid_connect_usb_double_power_point"
  283. )
  284. mock_device.reset_mock()
  285. entry = MockConfigEntry(
  286. domain=DOMAIN,
  287. version=6,
  288. title="test7",
  289. data={
  290. CONF_DEVICE_ID: "deviceid",
  291. CONF_HOST: "hostname",
  292. CONF_LOCAL_KEY: TESTKEY,
  293. CONF_TYPE: "grid_connect_usb_double_power_point",
  294. },
  295. options={
  296. "switch_main_switch": True,
  297. "switch_left_outlet": True,
  298. "switch_right_outlet": True,
  299. },
  300. )
  301. entry.add_to_hass(hass)
  302. assert await async_migrate_entry(hass, entry)
  303. @pytest.mark.asyncio
  304. async def test_migrate_child_device_identity_is_scoped_by_gateway(hass):
  305. """Child device identities include their parent gateway after migration."""
  306. entry = MockConfigEntry(
  307. domain=DOMAIN,
  308. version=13,
  309. minor_version=21,
  310. unique_id="001",
  311. title="Kitchen AC",
  312. data={
  313. CONF_DEVICE_ID: "gatewayid",
  314. CONF_DEVICE_CID: "001",
  315. CONF_HOST: "hostname",
  316. CONF_LOCAL_KEY: TESTKEY,
  317. CONF_TYPE: "idea_heatingbelt_airconditioner",
  318. CONF_PROTOCOL_VERSION: 3.3,
  319. CONF_POLL_ONLY: True,
  320. },
  321. )
  322. entry.add_to_hass(hass)
  323. registry = er.async_get(hass)
  324. entity = registry.async_get_or_create(
  325. "climate", DOMAIN, "001-climate", config_entry=entry
  326. )
  327. assert await async_migrate_entry(hass, entry)
  328. assert entry.unique_id == "gatewayid/001"
  329. assert registry.async_get(entity.entity_id).unique_id == "gatewayid/001-climate"
  330. @pytest.mark.asyncio
  331. async def test_flow_user_init(hass, mocker):
  332. """Test the initialisation of the form in the first page of the manual config flow path."""
  333. result = await hass.config_entries.flow.async_init(
  334. DOMAIN, context={"source": "local"}
  335. )
  336. expected = {
  337. "data_schema": mocker.ANY,
  338. "description_placeholders": mocker.ANY,
  339. "errors": {},
  340. "flow_id": mocker.ANY,
  341. "handler": DOMAIN,
  342. "step_id": "local",
  343. "type": "form",
  344. "last_step": mocker.ANY,
  345. "preview": mocker.ANY,
  346. }
  347. assert expected == result
  348. # Check the schema. Simple comparison does not work since they are not
  349. # the same object
  350. try:
  351. result["data_schema"](
  352. {CONF_DEVICE_ID: "test", CONF_LOCAL_KEY: TESTKEY, CONF_HOST: "test"}
  353. )
  354. except vol.MultipleInvalid:
  355. assert False
  356. try:
  357. result["data_schema"]({CONF_DEVICE_ID: "missing_some"})
  358. assert False
  359. except vol.MultipleInvalid:
  360. pass
  361. @pytest.mark.asyncio
  362. async def test_flow_user_init_protocol_options_are_strings(hass, mocker):
  363. """Test that protocol version dropdown uses strings, not floats."""
  364. result = await hass.config_entries.flow.async_init(
  365. DOMAIN, context={"source": "local"}
  366. )
  367. schema = result["data_schema"]
  368. # Validate that string protocol versions are accepted
  369. schema(
  370. {
  371. CONF_DEVICE_ID: "test",
  372. CONF_LOCAL_KEY: TESTKEY,
  373. CONF_HOST: "test",
  374. CONF_PROTOCOL_VERSION: "3.3",
  375. CONF_POLL_ONLY: False,
  376. }
  377. )
  378. # Validate that float protocol versions are rejected
  379. with pytest.raises(vol.MultipleInvalid):
  380. schema(
  381. {
  382. CONF_DEVICE_ID: "test",
  383. CONF_LOCAL_KEY: TESTKEY,
  384. CONF_HOST: "test",
  385. CONF_PROTOCOL_VERSION: 3.3,
  386. CONF_POLL_ONLY: False,
  387. }
  388. )
  389. @pytest.mark.asyncio
  390. async def test_async_test_connection_valid(hass, mocker):
  391. """Test that device is returned when connection is valid."""
  392. mock_device = mocker.patch(
  393. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  394. )
  395. mock_instance = mocker.AsyncMock()
  396. mock_instance.has_returned_state = True
  397. mock_instance.pause = mocker.MagicMock()
  398. mock_instance.resume = mocker.MagicMock()
  399. mock_device.return_value = mock_instance
  400. hass.data[DOMAIN] = {"deviceid": {"device": mock_instance}}
  401. device = await config_flow.async_test_connection(
  402. {
  403. CONF_DEVICE_ID: "deviceid",
  404. CONF_LOCAL_KEY: TESTKEY,
  405. CONF_HOST: "hostname",
  406. CONF_PROTOCOL_VERSION: "auto",
  407. },
  408. hass,
  409. )
  410. assert device == mock_instance
  411. mock_instance.pause.assert_called_once()
  412. mock_instance.resume.assert_called_once()
  413. @pytest.mark.asyncio
  414. async def test_async_test_connection_for_subdevice_valid(hass, mocker):
  415. """Test that subdevice is returned when connection is valid."""
  416. mock_device = mocker.patch(
  417. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  418. )
  419. mock_instance = mocker.AsyncMock()
  420. mock_instance.has_returned_state = True
  421. mock_instance.pause = mocker.MagicMock()
  422. mock_instance.resume = mocker.MagicMock()
  423. mock_device.return_value = mock_instance
  424. hass.data[DOMAIN] = {"deviceid/subdeviceid": {"device": mock_instance}}
  425. device = await config_flow.async_test_connection(
  426. {
  427. CONF_DEVICE_ID: "deviceid",
  428. CONF_LOCAL_KEY: TESTKEY,
  429. CONF_HOST: "hostname",
  430. CONF_PROTOCOL_VERSION: "auto",
  431. CONF_DEVICE_CID: "subdeviceid",
  432. },
  433. hass,
  434. )
  435. assert device == mock_instance
  436. mock_instance.pause.assert_called_once()
  437. mock_instance.resume.assert_called_once()
  438. @pytest.mark.asyncio
  439. async def test_async_test_connection_invalid(hass, mocker):
  440. """Test that None is returned when connection is invalid."""
  441. mock_device = mocker.patch(
  442. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  443. )
  444. mock_instance = mocker.AsyncMock()
  445. mock_instance.has_returned_state = False
  446. mock_instance._api = mocker.MagicMock()
  447. mock_device.return_value = mock_instance
  448. device = await config_flow.async_test_connection(
  449. {
  450. CONF_DEVICE_ID: "deviceid",
  451. CONF_LOCAL_KEY: TESTKEY,
  452. CONF_HOST: "hostname",
  453. CONF_PROTOCOL_VERSION: "auto",
  454. },
  455. hass,
  456. )
  457. assert device is None
  458. @pytest.mark.asyncio
  459. async def test_flow_user_init_invalid_config(hass, mocker):
  460. """Test errors populated when config is invalid."""
  461. mocker.patch(
  462. "custom_components.tuya_local.config_flow.async_test_connection",
  463. return_value=None,
  464. )
  465. flow = await hass.config_entries.flow.async_init(
  466. DOMAIN, context={"source": "local"}
  467. )
  468. result = await hass.config_entries.flow.async_configure(
  469. flow["flow_id"],
  470. user_input={
  471. CONF_DEVICE_ID: "deviceid",
  472. CONF_HOST: "hostname",
  473. CONF_LOCAL_KEY: "badkey",
  474. CONF_PROTOCOL_VERSION: "auto",
  475. CONF_POLL_ONLY: False,
  476. },
  477. )
  478. assert {"base": "connection"} == result["errors"]
  479. def setup_device_mock(mock, mocker, failure=False, devtype="test"):
  480. mock_type = mocker.MagicMock()
  481. mock_type.legacy_type = devtype
  482. mock_type.config_type = devtype
  483. mock_type.match_quality.return_value = 100
  484. mock_type.product_display_entries.return_value = [(None, None)]
  485. mock.async_possible_types = mocker.AsyncMock(
  486. return_value=[mock_type] if not failure else []
  487. )
  488. @pytest.mark.asyncio
  489. async def test_flow_user_init_data_valid(hass, mocker):
  490. """Test we advance to the next step when connection config is valid."""
  491. mock_device = mocker.MagicMock()
  492. mock_device._protocol_configured = "auto"
  493. setup_device_mock(mock_device, mocker)
  494. mocker.patch(
  495. "custom_components.tuya_local.config_flow.async_test_connection",
  496. return_value=mock_device,
  497. )
  498. flow = await hass.config_entries.flow.async_init(
  499. DOMAIN, context={"source": "local"}
  500. )
  501. result = await hass.config_entries.flow.async_configure(
  502. flow["flow_id"],
  503. user_input={
  504. CONF_DEVICE_ID: "deviceid",
  505. CONF_HOST: "hostname",
  506. CONF_LOCAL_KEY: TESTKEY,
  507. },
  508. )
  509. assert "form" == result["type"]
  510. assert "select_type" == result["step_id"]
  511. @pytest.mark.asyncio
  512. async def test_flow_select_type_init(hass, mocker):
  513. """Test the initialisation of the form in the 2nd step of the config flow."""
  514. mock_device = mocker.patch.object(config_flow.ConfigFlowHandler, "device")
  515. setup_device_mock(mock_device, mocker)
  516. result = await hass.config_entries.flow.async_init(
  517. DOMAIN, context={"source": "select_type"}
  518. )
  519. expected = {
  520. "data_schema": mocker.ANY,
  521. "description_placeholders": {"device_name": ""},
  522. "errors": None,
  523. "flow_id": mocker.ANY,
  524. "handler": DOMAIN,
  525. "step_id": "select_type",
  526. "type": "form",
  527. "last_step": mocker.ANY,
  528. "preview": mocker.ANY,
  529. }
  530. assert expected == result
  531. # Check the schema. Simple comparison does not work since they are not
  532. # the same object
  533. try:
  534. result["data_schema"]({CONF_TYPE: "test||||"})
  535. except vol.MultipleInvalid:
  536. assert False
  537. try:
  538. result["data_schema"]({CONF_TYPE: "not_test||||"})
  539. assert False
  540. except vol.MultipleInvalid:
  541. pass
  542. @pytest.mark.asyncio
  543. async def test_flow_select_type_aborts_when_no_match(hass, mocker):
  544. """Test the flow aborts when an unsupported device is used."""
  545. mock_device = mocker.patch.object(config_flow.ConfigFlowHandler, "device")
  546. setup_device_mock(mock_device, mocker, failure=True)
  547. result = await hass.config_entries.flow.async_init(
  548. DOMAIN, context={"source": "select_type"}
  549. )
  550. assert result["type"] == "abort"
  551. assert result["reason"] == "not_supported"
  552. @pytest.mark.asyncio
  553. async def test_flow_select_type_data_valid(hass, mocker):
  554. """Test the flow continues when valid data is supplied."""
  555. mock_device = mocker.patch.object(config_flow.ConfigFlowHandler, "device")
  556. setup_device_mock(mock_device, mocker, devtype="smartplugv1")
  557. flow = await hass.config_entries.flow.async_init(
  558. DOMAIN, context={"source": "select_type"}
  559. )
  560. result = await hass.config_entries.flow.async_configure(
  561. flow["flow_id"],
  562. user_input={CONF_TYPE: "smartplugv1||||"},
  563. )
  564. assert "form" == result["type"]
  565. assert "choose_entities" == result["step_id"]
  566. @pytest.mark.asyncio
  567. async def test_flow_choose_entities_init(hass, mocker):
  568. """Test the initialisation of the form in the 3rd step of the config flow."""
  569. mocker.patch.dict(config_flow.ConfigFlowHandler.data, {CONF_TYPE: "smartplugv1"})
  570. result = await hass.config_entries.flow.async_init(
  571. DOMAIN, context={"source": "choose_entities"}
  572. )
  573. expected = {
  574. "data_schema": mocker.ANY,
  575. "description_placeholders": {"device_name": ""},
  576. "errors": None,
  577. "flow_id": mocker.ANY,
  578. "handler": DOMAIN,
  579. "step_id": "choose_entities",
  580. "type": "form",
  581. "last_step": mocker.ANY,
  582. "preview": mocker.ANY,
  583. }
  584. assert expected == result
  585. # Check the schema. Simple comparison does not work since they are not
  586. # the same object
  587. try:
  588. result["data_schema"]({CONF_NAME: "test"})
  589. except vol.MultipleInvalid:
  590. assert False
  591. try:
  592. result["data_schema"]({"climate": True})
  593. assert False
  594. except vol.MultipleInvalid:
  595. pass
  596. @pytest.mark.asyncio
  597. async def test_flow_choose_entities_creates_config_entry(hass, bypass_setup, mocker):
  598. """Test the flow ends when data is valid."""
  599. mocker.patch.dict(
  600. config_flow.ConfigFlowHandler.data,
  601. {
  602. CONF_DEVICE_ID: "deviceid",
  603. CONF_LOCAL_KEY: TESTKEY,
  604. CONF_HOST: "hostname",
  605. CONF_POLL_ONLY: False,
  606. CONF_PROTOCOL_VERSION: "auto",
  607. CONF_TYPE: "kogan_kahtp_heater",
  608. CONF_DEVICE_CID: None,
  609. },
  610. )
  611. flow = await hass.config_entries.flow.async_init(
  612. DOMAIN, context={"source": "choose_entities"}
  613. )
  614. result = await hass.config_entries.flow.async_configure(
  615. flow["flow_id"],
  616. user_input={
  617. CONF_NAME: "test",
  618. },
  619. )
  620. expected = {
  621. "version": 13,
  622. "minor_version": mocker.ANY,
  623. "context": {"source": "choose_entities"},
  624. "type": FlowResultType.CREATE_ENTRY,
  625. "flow_id": mocker.ANY,
  626. "handler": DOMAIN,
  627. "title": "test",
  628. "description": None,
  629. "description_placeholders": None,
  630. "result": mocker.ANY,
  631. "subentries": (),
  632. "options": {},
  633. "data": {
  634. CONF_DEVICE_ID: "deviceid",
  635. CONF_HOST: "hostname",
  636. CONF_LOCAL_KEY: TESTKEY,
  637. CONF_POLL_ONLY: False,
  638. CONF_PROTOCOL_VERSION: "auto",
  639. CONF_TYPE: "kogan_kahtp_heater",
  640. CONF_DEVICE_CID: None,
  641. },
  642. }
  643. assert expected == result
  644. @pytest.mark.asyncio
  645. async def test_options_flow_init(hass, bypass_data_fetch):
  646. """Test config flow options."""
  647. config_entry = MockConfigEntry(
  648. domain=DOMAIN,
  649. version=13,
  650. unique_id="uniqueid",
  651. data={
  652. CONF_DEVICE_ID: "deviceid",
  653. CONF_HOST: "hostname",
  654. CONF_LOCAL_KEY: TESTKEY,
  655. CONF_NAME: "test",
  656. CONF_POLL_ONLY: False,
  657. CONF_PROTOCOL_VERSION: "auto",
  658. CONF_TYPE: "smartplugv1",
  659. CONF_DEVICE_CID: "",
  660. },
  661. )
  662. config_entry.add_to_hass(hass)
  663. assert await hass.config_entries.async_setup(config_entry.entry_id)
  664. await hass.async_block_till_done()
  665. # show initial form
  666. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  667. assert "form" == result["type"]
  668. assert "user" == result["step_id"]
  669. assert {} == result["errors"]
  670. assert result["data_schema"](
  671. {
  672. CONF_HOST: "hostname",
  673. CONF_LOCAL_KEY: TESTKEY,
  674. }
  675. )
  676. @pytest.mark.asyncio
  677. async def test_options_flow_modifies_config(hass, bypass_setup, mocker):
  678. mock_device = mocker.MagicMock()
  679. mocker.patch(
  680. "custom_components.tuya_local.config_flow.async_test_connection",
  681. return_value=mock_device,
  682. )
  683. config_entry = MockConfigEntry(
  684. domain=DOMAIN,
  685. version=13,
  686. unique_id="uniqueid",
  687. data={
  688. CONF_DEVICE_ID: "deviceid",
  689. CONF_HOST: "hostname",
  690. CONF_LOCAL_KEY: TESTKEY,
  691. CONF_NAME: "test",
  692. CONF_POLL_ONLY: False,
  693. CONF_PROTOCOL_VERSION: "auto",
  694. CONF_TYPE: "ble_pt216_temp_humidity",
  695. CONF_DEVICE_CID: "subdeviceid",
  696. },
  697. )
  698. config_entry.add_to_hass(hass)
  699. assert await hass.config_entries.async_setup(config_entry.entry_id)
  700. await hass.async_block_till_done()
  701. # show initial form
  702. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  703. # submit updated config
  704. result = await hass.config_entries.options.async_configure(
  705. form["flow_id"],
  706. user_input={
  707. CONF_HOST: "new_hostname",
  708. CONF_LOCAL_KEY: "new_key",
  709. CONF_POLL_ONLY: False,
  710. CONF_PROTOCOL_VERSION: "3.3",
  711. },
  712. )
  713. expected = {
  714. CONF_HOST: "new_hostname",
  715. CONF_LOCAL_KEY: "new_key",
  716. CONF_POLL_ONLY: False,
  717. CONF_PROTOCOL_VERSION: 3.3,
  718. }
  719. assert "create_entry" == result["type"]
  720. assert "" == result["title"]
  721. assert expected == result["data"]
  722. @pytest.mark.asyncio
  723. async def test_options_flow_fails_when_connection_fails(
  724. hass, bypass_data_fetch, mocker
  725. ):
  726. mocker.patch(
  727. "custom_components.tuya_local.config_flow.async_test_connection",
  728. return_value=None,
  729. )
  730. config_entry = MockConfigEntry(
  731. domain=DOMAIN,
  732. version=13,
  733. unique_id="uniqueid",
  734. data={
  735. CONF_DEVICE_ID: "deviceid",
  736. CONF_HOST: "hostname",
  737. CONF_LOCAL_KEY: TESTKEY,
  738. CONF_NAME: "test",
  739. CONF_POLL_ONLY: False,
  740. CONF_PROTOCOL_VERSION: "auto",
  741. CONF_TYPE: "smartplugv1",
  742. CONF_DEVICE_CID: "",
  743. },
  744. )
  745. config_entry.add_to_hass(hass)
  746. assert await hass.config_entries.async_setup(config_entry.entry_id)
  747. await hass.async_block_till_done()
  748. # show initial form
  749. form = await hass.config_entries.options.async_init(config_entry.entry_id)
  750. # submit updated config
  751. result = await hass.config_entries.options.async_configure(
  752. form["flow_id"],
  753. user_input={
  754. CONF_HOST: "new_hostname",
  755. CONF_LOCAL_KEY: "new_key",
  756. },
  757. )
  758. assert "form" == result["type"]
  759. assert "user" == result["step_id"]
  760. assert {"base": "connection"} == result["errors"]
  761. @pytest.mark.asyncio
  762. async def test_options_flow_fails_when_config_is_missing(hass, mocker):
  763. mock_device = mocker.MagicMock()
  764. mocker.patch(
  765. "custom_components.tuya_local.config_flow.async_test_connection",
  766. return_value=mock_device,
  767. )
  768. config_entry = MockConfigEntry(
  769. domain=DOMAIN,
  770. version=13,
  771. unique_id="uniqueid",
  772. data={
  773. CONF_DEVICE_ID: "deviceid",
  774. CONF_HOST: "hostname",
  775. CONF_LOCAL_KEY: TESTKEY,
  776. CONF_NAME: "test",
  777. CONF_POLL_ONLY: False,
  778. CONF_PROTOCOL_VERSION: "auto",
  779. CONF_TYPE: "non_existing",
  780. },
  781. )
  782. config_entry.add_to_hass(hass)
  783. await hass.config_entries.async_setup(config_entry.entry_id)
  784. await hass.async_block_till_done()
  785. # show initial form
  786. result = await hass.config_entries.options.async_init(config_entry.entry_id)
  787. assert result["type"] == "abort"
  788. assert result["reason"] == "not_supported"
  789. def test_migration_gets_correct_device_id():
  790. """Test that migration gets the correct device id."""
  791. # Normal device
  792. entry = MockConfigEntry(
  793. domain=DOMAIN,
  794. version=1,
  795. title="test",
  796. data={
  797. CONF_DEVICE_ID: "deviceid",
  798. CONF_HOST: "hostname",
  799. CONF_LOCAL_KEY: TESTKEY,
  800. CONF_TYPE: "auto",
  801. },
  802. )
  803. assert get_device_unique_id(entry) == "deviceid"
  804. # ---------------------------------------------------------------------------
  805. # async_step_user
  806. # ---------------------------------------------------------------------------
  807. @pytest.mark.asyncio
  808. async def test_flow_user_shows_form(hass):
  809. """Test the user step shows the setup mode form when no input."""
  810. result = await hass.config_entries.flow.async_init(
  811. DOMAIN, context={"source": "user"}
  812. )
  813. assert result["type"] == "form"
  814. assert result["step_id"] == "user"
  815. @pytest.mark.asyncio
  816. async def test_flow_user_manual_goes_to_local(hass):
  817. """Test that choosing 'manual' advances to the local step."""
  818. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  819. result = await hass.config_entries.flow.async_configure(
  820. flow["flow_id"], user_input={"setup_mode": "manual"}
  821. )
  822. assert result["type"] == "form"
  823. assert result["step_id"] == "local"
  824. @pytest.mark.asyncio
  825. async def test_flow_user_cloud_authenticated_goes_to_choose_device(hass, mocker):
  826. """Test cloud mode when already authenticated goes to choose_device."""
  827. mock_cloud = mocker.MagicMock()
  828. mock_cloud.is_authenticated = True
  829. mock_cloud.async_get_devices = AsyncMock(
  830. return_value={
  831. "dev1": {
  832. "name": "Light",
  833. "product_name": "Smart Light",
  834. "local_key": "key1",
  835. "online": True,
  836. "is_hub": False,
  837. "exists": False,
  838. }
  839. }
  840. )
  841. mocker.patch(
  842. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  843. )
  844. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  845. result = await hass.config_entries.flow.async_configure(
  846. flow["flow_id"], user_input={"setup_mode": "cloud"}
  847. )
  848. assert result["type"] == "form"
  849. assert result["step_id"] == "choose_device"
  850. @pytest.mark.asyncio
  851. async def test_flow_user_cloud_not_authenticated_goes_to_cloud_step(hass, mocker):
  852. """Test cloud mode when not authenticated goes to the cloud (QR) step."""
  853. mock_cloud = mocker.MagicMock()
  854. mock_cloud.is_authenticated = False
  855. mocker.patch(
  856. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  857. )
  858. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  859. result = await hass.config_entries.flow.async_configure(
  860. flow["flow_id"], user_input={"setup_mode": "cloud"}
  861. )
  862. assert result["type"] == "form"
  863. assert result["step_id"] == "cloud"
  864. @pytest.mark.asyncio
  865. async def test_flow_user_cloud_fresh_login_logs_out_and_goes_to_cloud(hass, mocker):
  866. """Test cloud_fresh_login forces logout then goes to cloud step."""
  867. mock_cloud = mocker.MagicMock()
  868. mock_cloud.is_authenticated = False
  869. mock_cloud.logout = mocker.MagicMock()
  870. mocker.patch(
  871. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  872. )
  873. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  874. result = await hass.config_entries.flow.async_configure(
  875. flow["flow_id"], user_input={"setup_mode": "cloud_fresh_login"}
  876. )
  877. mock_cloud.logout.assert_called_once()
  878. assert result["type"] == "form"
  879. assert result["step_id"] == "cloud"
  880. @pytest.mark.asyncio
  881. async def test_flow_user_cloud_exception_goes_to_cloud_step(hass, mocker):
  882. """Test that cloud exceptions cause re-auth (go to cloud step)."""
  883. mock_cloud = mocker.MagicMock()
  884. mock_cloud.is_authenticated = True
  885. mock_cloud.async_get_devices = AsyncMock(side_effect=Exception("network error"))
  886. mocker.patch(
  887. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  888. )
  889. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  890. result = await hass.config_entries.flow.async_configure(
  891. flow["flow_id"], user_input={"setup_mode": "cloud"}
  892. )
  893. assert result["type"] == "form"
  894. assert result["step_id"] == "cloud"
  895. # ---------------------------------------------------------------------------
  896. # async_step_cloud
  897. # ---------------------------------------------------------------------------
  898. @pytest.mark.asyncio
  899. async def test_flow_cloud_shows_form(hass, mocker):
  900. """Test cloud step shows the user_code form."""
  901. mocker.patch("custom_components.tuya_local.config_flow.Cloud")
  902. result = await hass.config_entries.flow.async_init(
  903. DOMAIN, context={"source": "cloud"}
  904. )
  905. assert result["type"] == "form"
  906. assert result["step_id"] == "cloud"
  907. @pytest.mark.asyncio
  908. async def test_flow_cloud_success_goes_to_scan(hass, mocker):
  909. """Test entering a user code that succeeds goes to QR scan step."""
  910. mock_cloud = mocker.MagicMock()
  911. mock_cloud.async_get_qr_code = AsyncMock(return_value="QR_TOKEN_123")
  912. mocker.patch(
  913. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  914. )
  915. flow = await hass.config_entries.flow.async_init(
  916. DOMAIN, context={"source": "cloud"}
  917. )
  918. result = await hass.config_entries.flow.async_configure(
  919. flow["flow_id"], user_input={"user_code": "MY_CODE"}
  920. )
  921. assert result["type"] == "form"
  922. assert result["step_id"] == "scan"
  923. @pytest.mark.asyncio
  924. async def test_flow_cloud_failure_shows_error(hass, mocker):
  925. """Test entering a bad user code stays on cloud step with error."""
  926. mock_cloud = mocker.MagicMock()
  927. mock_cloud.async_get_qr_code = AsyncMock(return_value=False)
  928. mock_cloud.last_error = {"msg": "Invalid code", "code": 1001}
  929. mocker.patch(
  930. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  931. )
  932. flow = await hass.config_entries.flow.async_init(
  933. DOMAIN, context={"source": "cloud"}
  934. )
  935. result = await hass.config_entries.flow.async_configure(
  936. flow["flow_id"], user_input={"user_code": "BAD_CODE"}
  937. )
  938. assert result["type"] == "form"
  939. assert result["step_id"] == "cloud"
  940. assert result["errors"] == {"base": "login_error"}
  941. # ---------------------------------------------------------------------------
  942. # async_step_scan
  943. # ---------------------------------------------------------------------------
  944. @pytest.mark.asyncio
  945. async def test_flow_scan_shows_qr_form(hass, mocker):
  946. """Test the scan step shows the QR code form."""
  947. mock_cloud = mocker.MagicMock()
  948. mock_cloud.async_get_qr_code = AsyncMock(return_value="QR_TOKEN")
  949. mocker.patch(
  950. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  951. )
  952. # Get to scan via cloud step
  953. flow = await hass.config_entries.flow.async_init(
  954. DOMAIN, context={"source": "cloud"}
  955. )
  956. result = await hass.config_entries.flow.async_configure(
  957. flow["flow_id"], user_input={"user_code": "CODE"}
  958. )
  959. assert result["step_id"] == "scan"
  960. @pytest.mark.asyncio
  961. async def test_flow_scan_login_success_goes_to_choose_device(hass, mocker):
  962. """Test scanning QR and successful login goes to choose_device."""
  963. mock_cloud = mocker.MagicMock()
  964. mock_cloud.async_get_qr_code = AsyncMock(return_value="QR_TOKEN")
  965. mock_cloud.async_login = AsyncMock(return_value=True)
  966. mock_cloud.async_get_devices = AsyncMock(
  967. return_value={
  968. "dev1": {
  969. "name": "Plug",
  970. "product_name": "Smart Plug",
  971. "local_key": "key",
  972. "online": True,
  973. "is_hub": False,
  974. "exists": False,
  975. }
  976. }
  977. )
  978. mocker.patch(
  979. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  980. )
  981. flow = await hass.config_entries.flow.async_init(
  982. DOMAIN, context={"source": "cloud"}
  983. )
  984. await hass.config_entries.flow.async_configure(
  985. flow["flow_id"], user_input={"user_code": "CODE"}
  986. )
  987. result = await hass.config_entries.flow.async_configure(
  988. flow["flow_id"], user_input={}
  989. )
  990. assert result["type"] == "form"
  991. assert result["step_id"] == "choose_device"
  992. @pytest.mark.asyncio
  993. async def test_flow_scan_login_failure_stays_on_scan(hass, mocker):
  994. """Test failed login stays on scan step with error."""
  995. mock_cloud = mocker.MagicMock()
  996. mock_cloud.async_get_qr_code = AsyncMock(return_value="QR_TOKEN")
  997. mock_cloud.async_login = AsyncMock(return_value=False)
  998. mock_cloud.last_error = {"msg": "Auth failed", "code": 2000}
  999. mocker.patch(
  1000. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1001. )
  1002. flow = await hass.config_entries.flow.async_init(
  1003. DOMAIN, context={"source": "cloud"}
  1004. )
  1005. await hass.config_entries.flow.async_configure(
  1006. flow["flow_id"], user_input={"user_code": "CODE"}
  1007. )
  1008. result = await hass.config_entries.flow.async_configure(
  1009. flow["flow_id"], user_input={}
  1010. )
  1011. assert result["type"] == "form"
  1012. assert result["step_id"] == "scan"
  1013. assert result["errors"] == {"base": "login_error"}
  1014. # ---------------------------------------------------------------------------
  1015. # async_step_choose_device
  1016. # ---------------------------------------------------------------------------
  1017. def _make_cloud_devices(include_hub=False, include_offline=False):
  1018. devices = {
  1019. "dev1": {
  1020. "name": "Smart Light",
  1021. "product_name": "Light",
  1022. "local_key": "key1",
  1023. "online": True,
  1024. "is_hub": False,
  1025. "exists": False,
  1026. "ip": "192.168.1.10",
  1027. }
  1028. }
  1029. if include_hub:
  1030. devices["hub1"] = {
  1031. "name": "Zigbee Hub",
  1032. "product_name": "Hub",
  1033. "local_key": "hubkey",
  1034. "online": True,
  1035. "is_hub": True,
  1036. "exists": False,
  1037. "ip": "192.168.1.1",
  1038. }
  1039. if include_offline:
  1040. devices["dev2"] = {
  1041. "name": "Offline Device",
  1042. "product_name": "Sensor",
  1043. "local_key": "key2",
  1044. "online": False,
  1045. "is_hub": False,
  1046. "exists": False,
  1047. "ip": "192.168.1.20",
  1048. }
  1049. return devices
  1050. @pytest.mark.asyncio
  1051. async def test_flow_choose_device_shows_form(hass, mocker):
  1052. """Test the choose_device step shows the device list form."""
  1053. mock_cloud = mocker.MagicMock()
  1054. mock_cloud.is_authenticated = True
  1055. mock_cloud.async_get_devices = AsyncMock(return_value=_make_cloud_devices())
  1056. mocker.patch(
  1057. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1058. )
  1059. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1060. result = await hass.config_entries.flow.async_configure(
  1061. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1062. )
  1063. assert result["type"] == "form"
  1064. assert result["step_id"] == "choose_device"
  1065. @pytest.mark.asyncio
  1066. async def test_flow_choose_device_aborts_when_no_devices(hass, mocker):
  1067. """Test choose_device aborts when no new devices are available."""
  1068. mock_cloud = mocker.MagicMock()
  1069. mock_cloud.is_authenticated = True
  1070. mock_cloud.async_get_devices = AsyncMock(return_value={})
  1071. mocker.patch(
  1072. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1073. )
  1074. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1075. result = await hass.config_entries.flow.async_configure(
  1076. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1077. )
  1078. assert result["type"] == "abort"
  1079. assert result["reason"] == "no_devices"
  1080. @pytest.mark.asyncio
  1081. async def test_flow_choose_device_direct_device_no_hub_goes_to_search(hass, mocker):
  1082. """Test selecting a directly addressable device (no hub) goes to search."""
  1083. devices = _make_cloud_devices()
  1084. mock_cloud = mocker.MagicMock()
  1085. mock_cloud.is_authenticated = True
  1086. mock_cloud.async_get_devices = AsyncMock(return_value=devices)
  1087. mocker.patch(
  1088. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1089. )
  1090. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1091. await hass.config_entries.flow.async_configure(
  1092. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1093. )
  1094. result = await hass.config_entries.flow.async_configure(
  1095. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1096. )
  1097. assert result["type"] == "form"
  1098. assert result["step_id"] == "search"
  1099. @pytest.mark.asyncio
  1100. async def test_flow_choose_device_direct_device_with_hub_shows_error(hass, mocker):
  1101. """Test selecting a hub for a direct device shows an error."""
  1102. devices = _make_cloud_devices(include_hub=True)
  1103. mock_cloud = mocker.MagicMock()
  1104. mock_cloud.is_authenticated = True
  1105. mock_cloud.async_get_devices = AsyncMock(return_value=devices)
  1106. mocker.patch(
  1107. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1108. )
  1109. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1110. await hass.config_entries.flow.async_configure(
  1111. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1112. )
  1113. result = await hass.config_entries.flow.async_configure(
  1114. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "hub1"}
  1115. )
  1116. assert result["type"] == "form"
  1117. assert result["step_id"] == "choose_device"
  1118. assert result["errors"] == {"base": "does_not_need_hub"}
  1119. @pytest.mark.asyncio
  1120. async def test_flow_choose_device_indirect_device_with_hub_goes_to_search(hass, mocker):
  1121. """Test selecting an indirect device with a hub goes to search."""
  1122. devices = {
  1123. "subdev1": {
  1124. "name": "Sub Device",
  1125. "product_name": "Sensor",
  1126. "local_key": "subkey", # non-empty so it appears in list
  1127. "online": True,
  1128. "is_hub": False,
  1129. "exists": False,
  1130. "ip": "", # empty ip = indirect/sub-device
  1131. "node_id": "node123",
  1132. "uuid": "uuid123",
  1133. "product_id": "prod_sub",
  1134. },
  1135. "hub1": {
  1136. "name": "Hub",
  1137. "product_name": "Gateway",
  1138. "local_key": "hubkey",
  1139. "online": True,
  1140. "is_hub": True,
  1141. "exists": False,
  1142. "ip": "192.168.1.1",
  1143. },
  1144. }
  1145. mock_cloud = mocker.MagicMock()
  1146. mock_cloud.is_authenticated = True
  1147. mock_cloud.async_get_devices = AsyncMock(return_value=devices)
  1148. mocker.patch(
  1149. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1150. )
  1151. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1152. await hass.config_entries.flow.async_configure(
  1153. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1154. )
  1155. result = await hass.config_entries.flow.async_configure(
  1156. flow["flow_id"], user_input={"device_id": "subdev1", "hub_id": "hub1"}
  1157. )
  1158. assert result["type"] == "form"
  1159. assert result["step_id"] == "search"
  1160. @pytest.mark.asyncio
  1161. async def test_flow_choose_device_indirect_no_hub_shows_error(hass, mocker):
  1162. """Test selecting an indirect device without a hub shows an error."""
  1163. devices = {
  1164. "subdev1": {
  1165. "name": "Sub Device",
  1166. "product_name": "Sensor",
  1167. "local_key": "subkey", # non-empty so it appears in list
  1168. "online": True,
  1169. "is_hub": False,
  1170. "exists": False,
  1171. "ip": "", # empty ip = indirect/sub-device
  1172. }
  1173. }
  1174. mock_cloud = mocker.MagicMock()
  1175. mock_cloud.is_authenticated = True
  1176. mock_cloud.async_get_devices = AsyncMock(return_value=devices)
  1177. mocker.patch(
  1178. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1179. )
  1180. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1181. await hass.config_entries.flow.async_configure(
  1182. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1183. )
  1184. result = await hass.config_entries.flow.async_configure(
  1185. flow["flow_id"], user_input={"device_id": "subdev1", "hub_id": "None"}
  1186. )
  1187. assert result["type"] == "form"
  1188. assert result["step_id"] == "choose_device"
  1189. assert result["errors"] == {"base": "needs_hub"}
  1190. # ---------------------------------------------------------------------------
  1191. # async_step_search
  1192. # ---------------------------------------------------------------------------
  1193. @pytest.mark.asyncio
  1194. async def test_flow_search_shows_form(hass, mocker):
  1195. """Test the search step shows the scanning form."""
  1196. mock_cloud = mocker.MagicMock()
  1197. mock_cloud.is_authenticated = True
  1198. mock_cloud.async_get_devices = AsyncMock(return_value=_make_cloud_devices())
  1199. mocker.patch(
  1200. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1201. )
  1202. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1203. await hass.config_entries.flow.async_configure(
  1204. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1205. )
  1206. result = await hass.config_entries.flow.async_configure(
  1207. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1208. )
  1209. assert result["type"] == "form"
  1210. assert result["step_id"] == "search"
  1211. @pytest.mark.asyncio
  1212. async def test_flow_search_found_device_goes_to_local(hass, mocker):
  1213. """Test that finding a device on the network advances to the local step."""
  1214. mock_cloud = mocker.MagicMock()
  1215. mock_cloud.is_authenticated = True
  1216. mock_cloud.async_get_devices = AsyncMock(return_value=_make_cloud_devices())
  1217. mocker.patch(
  1218. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1219. )
  1220. mocker.patch(
  1221. "custom_components.tuya_local.config_flow.scan_for_device",
  1222. return_value={"ip": "192.168.1.50", "version": "3.3", "productKey": "pk123"},
  1223. )
  1224. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1225. await hass.config_entries.flow.async_configure(
  1226. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1227. )
  1228. await hass.config_entries.flow.async_configure(
  1229. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1230. )
  1231. result = await hass.config_entries.flow.async_configure(
  1232. flow["flow_id"], user_input={}
  1233. )
  1234. assert result["type"] == "form"
  1235. assert result["step_id"] == "local"
  1236. @pytest.mark.asyncio
  1237. async def test_flow_search_not_found_still_goes_to_local(hass, mocker):
  1238. """Test that not finding a device still advances to local step (blank IP)."""
  1239. mock_cloud = mocker.MagicMock()
  1240. mock_cloud.is_authenticated = True
  1241. mock_cloud.async_get_devices = AsyncMock(return_value=_make_cloud_devices())
  1242. mocker.patch(
  1243. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1244. )
  1245. mocker.patch(
  1246. "custom_components.tuya_local.config_flow.scan_for_device",
  1247. return_value={"ip": None},
  1248. )
  1249. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1250. await hass.config_entries.flow.async_configure(
  1251. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1252. )
  1253. await hass.config_entries.flow.async_configure(
  1254. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1255. )
  1256. result = await hass.config_entries.flow.async_configure(
  1257. flow["flow_id"], user_input={}
  1258. )
  1259. assert result["type"] == "form"
  1260. assert result["step_id"] == "local"
  1261. @pytest.mark.asyncio
  1262. async def test_flow_search_oserror_still_goes_to_local(hass, mocker):
  1263. """Test that an OSError during scan still advances to local step."""
  1264. mock_cloud = mocker.MagicMock()
  1265. mock_cloud.is_authenticated = True
  1266. mock_cloud.async_get_devices = AsyncMock(return_value=_make_cloud_devices())
  1267. mocker.patch(
  1268. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1269. )
  1270. mocker.patch(
  1271. "custom_components.tuya_local.config_flow.scan_for_device",
  1272. side_effect=OSError("network unreachable"),
  1273. )
  1274. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1275. await hass.config_entries.flow.async_configure(
  1276. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1277. )
  1278. await hass.config_entries.flow.async_configure(
  1279. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1280. )
  1281. result = await hass.config_entries.flow.async_configure(
  1282. flow["flow_id"], user_input={}
  1283. )
  1284. assert result["type"] == "form"
  1285. assert result["step_id"] == "local"
  1286. # ---------------------------------------------------------------------------
  1287. # async_test_connection with fixed protocol
  1288. # ---------------------------------------------------------------------------
  1289. @pytest.mark.asyncio
  1290. async def test_async_test_connection_fixed_protocol_success(hass, mocker):
  1291. """Test connection with a fixed protocol version (not auto)."""
  1292. mock_device = mocker.patch(
  1293. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  1294. )
  1295. mock_instance = mocker.AsyncMock()
  1296. mock_instance.has_returned_state = True
  1297. mock_device.return_value = mock_instance
  1298. device = await config_flow.async_test_connection(
  1299. {
  1300. CONF_DEVICE_ID: "deviceid",
  1301. CONF_LOCAL_KEY: TESTKEY,
  1302. CONF_HOST: "hostname",
  1303. CONF_PROTOCOL_VERSION: 3.3,
  1304. },
  1305. hass,
  1306. )
  1307. assert device == mock_instance
  1308. @pytest.mark.asyncio
  1309. async def test_async_test_connection_fixed_protocol_no_state(hass, mocker):
  1310. """Test fixed protocol returns None when device has no state."""
  1311. mock_device = mocker.patch(
  1312. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  1313. )
  1314. mock_instance = mocker.AsyncMock()
  1315. mock_instance.has_returned_state = False
  1316. mock_device.return_value = mock_instance
  1317. device = await config_flow.async_test_connection(
  1318. {
  1319. CONF_DEVICE_ID: "deviceid",
  1320. CONF_LOCAL_KEY: TESTKEY,
  1321. CONF_HOST: "hostname",
  1322. CONF_PROTOCOL_VERSION: 3.3,
  1323. },
  1324. hass,
  1325. )
  1326. assert device is None
  1327. @pytest.mark.asyncio
  1328. async def test_async_test_connection_fixed_protocol_exception(hass, mocker):
  1329. """Test fixed protocol returns None on exception."""
  1330. mock_device = mocker.patch(
  1331. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  1332. )
  1333. mock_instance = mocker.AsyncMock()
  1334. mock_instance.async_refresh = AsyncMock(side_effect=Exception("timeout"))
  1335. mock_device.return_value = mock_instance
  1336. device = await config_flow.async_test_connection(
  1337. {
  1338. CONF_DEVICE_ID: "deviceid",
  1339. CONF_LOCAL_KEY: TESTKEY,
  1340. CONF_HOST: "hostname",
  1341. CONF_PROTOCOL_VERSION: 3.3,
  1342. },
  1343. hass,
  1344. )
  1345. assert device is None
  1346. @pytest.mark.asyncio
  1347. async def test_async_test_connection_auto_all_protocols_fail(hass, mocker):
  1348. """Test auto mode returns None when all protocols fail."""
  1349. mock_device = mocker.patch(
  1350. "custom_components.tuya_local.config_flow.TuyaLocalDevice"
  1351. )
  1352. mock_instance = mocker.AsyncMock()
  1353. mock_instance.has_returned_state = False
  1354. mock_instance._api = mocker.MagicMock()
  1355. mock_instance._api.parent = None
  1356. mock_device.return_value = mock_instance
  1357. device = await config_flow.async_test_connection(
  1358. {
  1359. CONF_DEVICE_ID: "deviceid",
  1360. CONF_LOCAL_KEY: TESTKEY,
  1361. CONF_HOST: "hostname",
  1362. CONF_PROTOCOL_VERSION: "auto",
  1363. },
  1364. hass,
  1365. )
  1366. assert device is None
  1367. # ---------------------------------------------------------------------------
  1368. # _device_name_placeholder
  1369. # ---------------------------------------------------------------------------
  1370. @pytest.mark.asyncio
  1371. async def test_device_name_placeholder_with_cloud_device(hass, mocker):
  1372. """Test _device_name_placeholder returns formatted name when cloud device set."""
  1373. mock_cloud = mocker.MagicMock()
  1374. mock_cloud.is_authenticated = True
  1375. mock_cloud.async_get_devices = AsyncMock(
  1376. return_value={
  1377. "dev1": {
  1378. "name": "My Light",
  1379. "product_name": "Smart Bulb",
  1380. "local_key": "key",
  1381. "online": True,
  1382. "is_hub": False,
  1383. "exists": False,
  1384. "ip": "192.168.1.5",
  1385. }
  1386. }
  1387. )
  1388. mocker.patch(
  1389. "custom_components.tuya_local.config_flow.Cloud", return_value=mock_cloud
  1390. )
  1391. mocker.patch(
  1392. "custom_components.tuya_local.config_flow.scan_for_device",
  1393. return_value={"ip": None},
  1394. )
  1395. flow = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"})
  1396. await hass.config_entries.flow.async_configure(
  1397. flow["flow_id"], user_input={"setup_mode": "cloud"}
  1398. )
  1399. await hass.config_entries.flow.async_configure(
  1400. flow["flow_id"], user_input={"device_id": "dev1", "hub_id": "None"}
  1401. )
  1402. result = await hass.config_entries.flow.async_configure(
  1403. flow["flow_id"], user_input={}
  1404. )
  1405. # The local step description_placeholders should contain the device name
  1406. assert result["step_id"] == "local"
  1407. placeholder = result["description_placeholders"]["device_name"]
  1408. assert "My Light" in placeholder
  1409. assert "Smart Bulb" in placeholder
  1410. @pytest.mark.asyncio
  1411. async def test_device_name_placeholder_without_cloud_device(hass, mocker):
  1412. """Test _device_name_placeholder returns empty string when no cloud device."""
  1413. result = await hass.config_entries.flow.async_init(
  1414. DOMAIN, context={"source": "local"}
  1415. )
  1416. assert result["step_id"] == "local"
  1417. assert result["description_placeholders"]["device_name"] == ""
  1418. # ---------------------------------------------------------------------------
  1419. # async_step_select_type with auto-detected protocol
  1420. # ---------------------------------------------------------------------------
  1421. @pytest.mark.asyncio
  1422. async def test_flow_select_type_shows_auto_detected_form(hass, mocker):
  1423. """Test select_type shows the auto_detected variant when protocol was detected."""
  1424. mock_device = mocker.patch.object(config_flow.ConfigFlowHandler, "device")
  1425. mock_type = mocker.MagicMock()
  1426. mock_type.config_type = "smartplugv1"
  1427. mock_type.name = "Smart Plug"
  1428. mock_type.match_quality.return_value = 85
  1429. mock_type.product_display_entries.return_value = [(None, None)]
  1430. mock_device.async_possible_types = mocker.AsyncMock(return_value=[mock_type])
  1431. mock_device._get_cached_state.return_value = {"1": True}
  1432. mock_device._product_ids = []
  1433. mocker.patch.object(
  1434. config_flow.ConfigFlowHandler,
  1435. "_auto_detected_protocol",
  1436. new_callable=lambda: property(lambda self: 3.3),
  1437. create=True,
  1438. )
  1439. result = await hass.config_entries.flow.async_init(
  1440. DOMAIN, context={"source": "select_type"}
  1441. )
  1442. # Either select_type or select_type_auto_detected depending on attribute
  1443. assert result["step_id"] in ("select_type", "select_type_auto_detected")
  1444. # ---------------------------------------------------------------------------
  1445. # choose_entities with cloud device name as default
  1446. # ---------------------------------------------------------------------------
  1447. @pytest.mark.asyncio
  1448. async def test_flow_choose_entities_uses_cloud_name_as_default(
  1449. hass, bypass_setup, mocker
  1450. ):
  1451. """Test choose_entities uses cloud device name as the default entity name."""
  1452. mocker.patch.dict(config_flow.ConfigFlowHandler.data, {CONF_TYPE: "smartplugv1"})
  1453. # Patch __cloud_device on the handler class
  1454. mocker.patch.object(
  1455. config_flow.ConfigFlowHandler,
  1456. "_ConfigFlowHandler__cloud_device",
  1457. new={"name": "My Cloud Device", "product_name": "Plug"},
  1458. create=True,
  1459. )
  1460. result = await hass.config_entries.flow.async_init(
  1461. DOMAIN, context={"source": "choose_entities"}
  1462. )
  1463. assert result["type"] == "form"
  1464. assert result["step_id"] == "choose_entities"
  1465. # The schema default should be the cloud device name
  1466. schema = result["data_schema"]
  1467. # Validate it accepts the cloud device name
  1468. validated = schema({CONF_NAME: "My Cloud Device"})
  1469. assert validated[CONF_NAME] == "My Cloud Device"
  1470. @pytest.mark.asyncio
  1471. async def test_flow_integration_discovery_shows_user_form(hass):
  1472. """A device found by background discovery advances to the user setup form."""
  1473. result = await hass.config_entries.flow.async_init(
  1474. DOMAIN,
  1475. context={"source": "integration_discovery"},
  1476. data={
  1477. CONF_DEVICE_ID: "bfdiscovered000000",
  1478. CONF_HOST: "192.168.1.77",
  1479. "product_id": "keyxyz",
  1480. "version": "3.5",
  1481. },
  1482. )
  1483. assert result["type"] == "form"
  1484. assert result["step_id"] == "user"
  1485. @pytest.mark.asyncio
  1486. async def test_flow_integration_discovery_aborts_if_configured(hass):
  1487. """A discovered device that is already configured (or ignored) aborts."""
  1488. entry = MockConfigEntry(domain=DOMAIN, unique_id="bfdiscovered000000")
  1489. entry.add_to_hass(hass)
  1490. result = await hass.config_entries.flow.async_init(
  1491. DOMAIN,
  1492. context={"source": "integration_discovery"},
  1493. data={
  1494. CONF_DEVICE_ID: "bfdiscovered000000",
  1495. CONF_HOST: "192.168.1.77",
  1496. },
  1497. )
  1498. assert result["type"] == "abort"
  1499. assert result["reason"] == "already_configured"