test_smart_plugs_api.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. """Integration tests for Smart Plugs API endpoints.
  2. Tests the full request/response cycle for /api/v1/smart-plugs/ endpoints.
  3. """
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestSmartPlugsAPI:
  7. """Integration tests for /api/v1/smart-plugs/ endpoints."""
  8. # ========================================================================
  9. # List endpoints
  10. # ========================================================================
  11. @pytest.mark.asyncio
  12. @pytest.mark.integration
  13. async def test_list_smart_plugs_empty(self, async_client: AsyncClient):
  14. """Verify empty list is returned when no plugs exist."""
  15. response = await async_client.get("/api/v1/smart-plugs/")
  16. assert response.status_code == 200
  17. assert response.json() == []
  18. @pytest.mark.asyncio
  19. @pytest.mark.integration
  20. async def test_list_smart_plugs_with_data(self, async_client: AsyncClient, smart_plug_factory, db_session):
  21. """Verify list returns existing plugs."""
  22. await smart_plug_factory(name="Test Plug 1")
  23. response = await async_client.get("/api/v1/smart-plugs/")
  24. assert response.status_code == 200
  25. data = response.json()
  26. assert len(data) >= 1
  27. assert any(p["name"] == "Test Plug 1" for p in data)
  28. # ========================================================================
  29. # Create endpoints
  30. # ========================================================================
  31. @pytest.mark.asyncio
  32. @pytest.mark.integration
  33. async def test_create_smart_plug(self, async_client: AsyncClient):
  34. """Verify smart plug can be created."""
  35. data = {
  36. "name": "New Plug",
  37. "ip_address": "192.168.1.100",
  38. "enabled": True,
  39. "auto_on": True,
  40. "auto_off": False,
  41. }
  42. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  43. assert response.status_code == 200
  44. result = response.json()
  45. assert result["name"] == "New Plug"
  46. assert result["ip_address"] == "192.168.1.100"
  47. assert result["auto_off"] is False
  48. @pytest.mark.asyncio
  49. @pytest.mark.integration
  50. async def test_create_smart_plug_with_printer(self, async_client: AsyncClient, printer_factory, db_session):
  51. """Verify smart plug can be linked to a printer."""
  52. printer = await printer_factory(name="Test Printer")
  53. data = {
  54. "name": "Printer Plug",
  55. "ip_address": "192.168.1.101",
  56. "printer_id": printer.id,
  57. }
  58. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  59. assert response.status_code == 200
  60. result = response.json()
  61. assert result["printer_id"] == printer.id
  62. @pytest.mark.asyncio
  63. @pytest.mark.integration
  64. async def test_create_plug_with_invalid_printer_id(self, async_client: AsyncClient):
  65. """Verify creating plug with non-existent printer fails."""
  66. data = {
  67. "name": "Test Plug",
  68. "ip_address": "192.168.1.100",
  69. "printer_id": 9999,
  70. }
  71. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  72. assert response.status_code == 400
  73. assert "Printer not found" in response.json()["detail"]
  74. # ========================================================================
  75. # Get single endpoint
  76. # ========================================================================
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_get_smart_plug(self, async_client: AsyncClient, smart_plug_factory, db_session):
  80. """Verify single plug can be retrieved."""
  81. plug = await smart_plug_factory(name="Get Test Plug")
  82. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  83. assert response.status_code == 200
  84. result = response.json()
  85. assert result["id"] == plug.id
  86. assert result["name"] == "Get Test Plug"
  87. @pytest.mark.asyncio
  88. @pytest.mark.integration
  89. async def test_get_smart_plug_not_found(self, async_client: AsyncClient):
  90. """Verify 404 for non-existent plug."""
  91. response = await async_client.get("/api/v1/smart-plugs/9999")
  92. assert response.status_code == 404
  93. # ========================================================================
  94. # Update endpoints (CRITICAL - toggle persistence)
  95. # ========================================================================
  96. @pytest.mark.asyncio
  97. @pytest.mark.integration
  98. async def test_update_auto_off_toggle(self, async_client: AsyncClient, smart_plug_factory, db_session):
  99. """CRITICAL: Verify auto_off toggle persists correctly.
  100. This tests the regression scenario where toggling auto_off
  101. wasn't being saved properly.
  102. """
  103. # Create plug with auto_off=True
  104. plug = await smart_plug_factory(auto_off=True)
  105. # Verify initial state
  106. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  107. assert response.status_code == 200
  108. assert response.json()["auto_off"] is True
  109. # Toggle auto_off to False
  110. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json={"auto_off": False})
  111. assert response.status_code == 200
  112. assert response.json()["auto_off"] is False
  113. # Verify change persisted by fetching again
  114. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  115. assert response.json()["auto_off"] is False
  116. @pytest.mark.asyncio
  117. @pytest.mark.integration
  118. async def test_update_auto_on_toggle(self, async_client: AsyncClient, smart_plug_factory, db_session):
  119. """Verify auto_on toggle persists correctly."""
  120. plug = await smart_plug_factory(auto_on=True)
  121. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json={"auto_on": False})
  122. assert response.status_code == 200
  123. assert response.json()["auto_on"] is False
  124. # Verify persistence
  125. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  126. assert response.json()["auto_on"] is False
  127. @pytest.mark.asyncio
  128. @pytest.mark.integration
  129. async def test_update_enabled_toggle(self, async_client: AsyncClient, smart_plug_factory, db_session):
  130. """Verify enabled toggle persists correctly."""
  131. plug = await smart_plug_factory(enabled=True)
  132. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json={"enabled": False})
  133. assert response.status_code == 200
  134. assert response.json()["enabled"] is False
  135. @pytest.mark.asyncio
  136. @pytest.mark.integration
  137. async def test_update_off_delay_mode(self, async_client: AsyncClient, smart_plug_factory, db_session):
  138. """Verify off_delay_mode can be changed."""
  139. plug = await smart_plug_factory(off_delay_mode="time")
  140. response = await async_client.patch(
  141. f"/api/v1/smart-plugs/{plug.id}", json={"off_delay_mode": "temperature", "off_temp_threshold": 50}
  142. )
  143. assert response.status_code == 200
  144. result = response.json()
  145. assert result["off_delay_mode"] == "temperature"
  146. assert result["off_temp_threshold"] == 50
  147. @pytest.mark.asyncio
  148. @pytest.mark.integration
  149. async def test_temp_mode_waits_for_the_nozzle_by_default(self, async_client: AsyncClient, smart_plug_factory):
  150. """#3464: plugs that never chose a source keep the nozzle-only behaviour."""
  151. plug = await smart_plug_factory()
  152. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  153. assert response.status_code == 200
  154. assert response.json()["off_temp_source"] == "nozzle"
  155. assert response.json()["off_bed_temp_threshold"] == 35
  156. @pytest.mark.asyncio
  157. @pytest.mark.integration
  158. async def test_update_off_temp_source(self, async_client: AsyncClient, smart_plug_factory):
  159. """#3464: temperature mode can wait for the bed, with its own threshold."""
  160. plug = await smart_plug_factory(off_delay_mode="temperature")
  161. response = await async_client.patch(
  162. f"/api/v1/smart-plugs/{plug.id}", json={"off_temp_source": "bed", "off_bed_temp_threshold": 40}
  163. )
  164. assert response.status_code == 200
  165. result = response.json()
  166. assert result["off_temp_source"] == "bed"
  167. assert result["off_bed_temp_threshold"] == 40
  168. assert result["off_temp_threshold"] == 70 # the nozzle's own threshold is untouched
  169. @pytest.mark.asyncio
  170. @pytest.mark.integration
  171. @pytest.mark.parametrize(
  172. "payload",
  173. [
  174. {"off_temp_source": "chamber"},
  175. {"off_temp_source": "both"},
  176. {"off_bed_temp_threshold": 10},
  177. {"off_bed_temp_threshold": 130},
  178. ],
  179. )
  180. async def test_update_rejects_invalid_temp_source_settings(
  181. self, async_client: AsyncClient, smart_plug_factory, payload
  182. ):
  183. plug = await smart_plug_factory()
  184. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json=payload)
  185. assert response.status_code == 422
  186. @pytest.mark.asyncio
  187. @pytest.mark.integration
  188. async def test_update_schedule_settings(self, async_client: AsyncClient, smart_plug_factory, db_session):
  189. """Verify schedule settings can be updated."""
  190. plug = await smart_plug_factory(schedule_enabled=False)
  191. response = await async_client.patch(
  192. f"/api/v1/smart-plugs/{plug.id}",
  193. json={
  194. "schedule_enabled": True,
  195. "schedule_on_time": "08:00",
  196. "schedule_off_time": "22:00",
  197. },
  198. )
  199. assert response.status_code == 200
  200. result = response.json()
  201. assert result["schedule_enabled"] is True
  202. assert result["schedule_on_time"] == "08:00"
  203. assert result["schedule_off_time"] == "22:00"
  204. @pytest.mark.asyncio
  205. @pytest.mark.integration
  206. async def test_update_multiple_fields(self, async_client: AsyncClient, smart_plug_factory, db_session):
  207. """Verify multiple fields can be updated at once."""
  208. plug = await smart_plug_factory(
  209. name="Old Name",
  210. auto_on=True,
  211. auto_off=True,
  212. )
  213. response = await async_client.patch(
  214. f"/api/v1/smart-plugs/{plug.id}",
  215. json={
  216. "name": "New Name",
  217. "auto_on": False,
  218. "auto_off": False,
  219. },
  220. )
  221. assert response.status_code == 200
  222. result = response.json()
  223. assert result["name"] == "New Name"
  224. assert result["auto_on"] is False
  225. assert result["auto_off"] is False
  226. # ========================================================================
  227. # Control endpoints
  228. # ========================================================================
  229. @pytest.mark.asyncio
  230. @pytest.mark.integration
  231. async def test_control_smart_plug_on(
  232. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  233. ):
  234. """Verify smart plug can be turned on."""
  235. plug = await smart_plug_factory()
  236. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  237. assert response.status_code == 200
  238. result = response.json()
  239. assert result["success"] is True
  240. assert result["action"] == "on"
  241. @pytest.mark.asyncio
  242. @pytest.mark.integration
  243. async def test_control_smart_plug_off(
  244. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  245. ):
  246. """Verify smart plug can be turned off."""
  247. plug = await smart_plug_factory()
  248. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "off"})
  249. assert response.status_code == 200
  250. result = response.json()
  251. assert result["success"] is True
  252. assert result["action"] == "off"
  253. @pytest.mark.asyncio
  254. @pytest.mark.integration
  255. async def test_control_smart_plug_toggle(
  256. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  257. ):
  258. """Verify smart plug can be toggled."""
  259. plug = await smart_plug_factory()
  260. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "toggle"})
  261. assert response.status_code == 200
  262. result = response.json()
  263. assert result["success"] is True
  264. assert result["action"] == "toggle"
  265. @pytest.mark.asyncio
  266. @pytest.mark.integration
  267. async def test_a_toggle_tells_the_mqtt_relay_the_resulting_state(
  268. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  269. ):
  270. """The SpoolBuddy quick menu and the printer card switch plugs with
  271. toggle, so the state it ends in is read back and published."""
  272. from unittest.mock import AsyncMock, patch
  273. plug = await smart_plug_factory()
  274. mock_tasmota_service.get_status.return_value = {"state": "OFF", "reachable": True}
  275. with patch("backend.app.api.routes.smart_plugs.publish_plug_state", new_callable=AsyncMock) as publish:
  276. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "toggle"})
  277. assert response.status_code == 200
  278. publish.assert_awaited_once()
  279. assert publish.await_args.kwargs["on"] is False
  280. @pytest.mark.asyncio
  281. @pytest.mark.integration
  282. async def test_control_invalid_action(self, async_client: AsyncClient, smart_plug_factory, db_session):
  283. """Verify invalid action returns error."""
  284. plug = await smart_plug_factory()
  285. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "invalid"})
  286. # FastAPI returns 422 for pydantic validation errors
  287. assert response.status_code == 422
  288. # ========================================================================
  289. # Status endpoint
  290. # ========================================================================
  291. @pytest.mark.asyncio
  292. @pytest.mark.integration
  293. async def test_get_smart_plug_status(
  294. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  295. ):
  296. """Verify smart plug status can be retrieved."""
  297. plug = await smart_plug_factory()
  298. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}/status")
  299. assert response.status_code == 200
  300. result = response.json()
  301. assert result["state"] == "ON"
  302. assert result["reachable"] is True
  303. # ========================================================================
  304. # Delete endpoint
  305. # ========================================================================
  306. @pytest.mark.asyncio
  307. @pytest.mark.integration
  308. async def test_delete_smart_plug(self, async_client: AsyncClient, smart_plug_factory, db_session):
  309. """Verify smart plug can be deleted."""
  310. plug = await smart_plug_factory()
  311. plug_id = plug.id
  312. response = await async_client.delete(f"/api/v1/smart-plugs/{plug_id}")
  313. assert response.status_code == 200
  314. # Verify deleted
  315. response = await async_client.get(f"/api/v1/smart-plugs/{plug_id}")
  316. assert response.status_code == 404
  317. @pytest.mark.asyncio
  318. @pytest.mark.integration
  319. async def test_delete_nonexistent_plug(self, async_client: AsyncClient):
  320. """Verify deleting non-existent plug returns 404."""
  321. response = await async_client.delete("/api/v1/smart-plugs/9999")
  322. assert response.status_code == 404
  323. # ========================================================================
  324. # Switchbar visibility
  325. # ========================================================================
  326. @pytest.mark.asyncio
  327. @pytest.mark.integration
  328. async def test_update_show_in_switchbar(self, async_client: AsyncClient, smart_plug_factory, db_session):
  329. """Verify show_in_switchbar toggle persists correctly."""
  330. plug = await smart_plug_factory(show_in_switchbar=False)
  331. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json={"show_in_switchbar": True})
  332. assert response.status_code == 200
  333. assert response.json()["show_in_switchbar"] is True
  334. # Verify persistence
  335. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  336. assert response.json()["show_in_switchbar"] is True
  337. # ========================================================================
  338. # Tasmota Discovery endpoints
  339. # ========================================================================
  340. @pytest.mark.asyncio
  341. @pytest.mark.integration
  342. async def test_tasmota_discovery_scan(self, async_client: AsyncClient):
  343. """Verify Tasmota discovery scan can be started."""
  344. response = await async_client.post("/api/v1/smart-plugs/discover/scan")
  345. assert response.status_code == 200
  346. data = response.json()
  347. assert "running" in data
  348. assert "scanned" in data
  349. assert "total" in data
  350. @pytest.mark.asyncio
  351. @pytest.mark.integration
  352. async def test_tasmota_discovery_status(self, async_client: AsyncClient):
  353. """Verify Tasmota discovery status endpoint works."""
  354. response = await async_client.get("/api/v1/smart-plugs/discover/status")
  355. assert response.status_code == 200
  356. data = response.json()
  357. assert "running" in data
  358. assert "scanned" in data
  359. assert "total" in data
  360. @pytest.mark.asyncio
  361. @pytest.mark.integration
  362. async def test_tasmota_discovery_devices(self, async_client: AsyncClient):
  363. """Verify Tasmota discovered devices endpoint works."""
  364. response = await async_client.get("/api/v1/smart-plugs/discover/devices")
  365. assert response.status_code == 200
  366. data = response.json()
  367. assert isinstance(data, list)
  368. @pytest.mark.asyncio
  369. @pytest.mark.integration
  370. async def test_tasmota_discovery_stop(self, async_client: AsyncClient):
  371. """Verify Tasmota discovery can be stopped."""
  372. response = await async_client.post("/api/v1/smart-plugs/discover/stop")
  373. assert response.status_code == 200
  374. data = response.json()
  375. assert "running" in data
  376. # ========================================================================
  377. # Home Assistant Integration tests
  378. # ========================================================================
  379. @pytest.mark.asyncio
  380. @pytest.mark.integration
  381. async def test_create_homeassistant_plug(self, async_client: AsyncClient):
  382. """Verify Home Assistant plug can be created."""
  383. data = {
  384. "name": "HA Plug",
  385. "plug_type": "homeassistant",
  386. "ha_entity_id": "switch.printer_plug",
  387. "enabled": True,
  388. "auto_on": True,
  389. "auto_off": False,
  390. }
  391. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  392. assert response.status_code == 200
  393. result = response.json()
  394. assert result["name"] == "HA Plug"
  395. assert result["plug_type"] == "homeassistant"
  396. assert result["ha_entity_id"] == "switch.printer_plug"
  397. assert result["ip_address"] is None
  398. @pytest.mark.asyncio
  399. @pytest.mark.integration
  400. async def test_create_homeassistant_plug_missing_entity_id(self, async_client: AsyncClient):
  401. """Verify creating HA plug without entity_id fails."""
  402. data = {
  403. "name": "HA Plug",
  404. "plug_type": "homeassistant",
  405. # Missing ha_entity_id
  406. "enabled": True,
  407. }
  408. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  409. assert response.status_code == 422 # Validation error
  410. @pytest.mark.asyncio
  411. @pytest.mark.integration
  412. async def test_create_tasmota_plug_missing_ip(self, async_client: AsyncClient):
  413. """Verify creating Tasmota plug without IP fails."""
  414. data = {
  415. "name": "Tasmota Plug",
  416. "plug_type": "tasmota",
  417. # Missing ip_address
  418. "enabled": True,
  419. }
  420. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  421. assert response.status_code == 422 # Validation error
  422. @pytest.mark.asyncio
  423. @pytest.mark.integration
  424. async def test_ha_entities_endpoint_not_configured(self, async_client: AsyncClient):
  425. """Verify HA entities endpoint returns error when not configured."""
  426. response = await async_client.get("/api/v1/smart-plugs/ha/entities")
  427. assert response.status_code == 400
  428. assert "not configured" in response.json()["detail"].lower()
  429. @pytest.mark.asyncio
  430. @pytest.mark.integration
  431. async def test_update_plug_type(self, async_client: AsyncClient, smart_plug_factory, db_session):
  432. """Verify plug_type can be updated."""
  433. plug = await smart_plug_factory(plug_type="tasmota", ip_address="192.168.1.100")
  434. response = await async_client.patch(
  435. f"/api/v1/smart-plugs/{plug.id}",
  436. json={
  437. "plug_type": "homeassistant",
  438. "ha_entity_id": "switch.test",
  439. },
  440. )
  441. assert response.status_code == 200
  442. result = response.json()
  443. assert result["plug_type"] == "homeassistant"
  444. assert result["ha_entity_id"] == "switch.test"
  445. @pytest.mark.asyncio
  446. @pytest.mark.integration
  447. async def test_control_homeassistant_plug(
  448. self, async_client: AsyncClient, smart_plug_factory, mock_homeassistant_service, db_session
  449. ):
  450. """Verify HA smart plug can be controlled."""
  451. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  452. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  453. assert response.status_code == 200
  454. result = response.json()
  455. assert result["success"] is True
  456. assert result["action"] == "on"
  457. @pytest.mark.asyncio
  458. @pytest.mark.integration
  459. async def test_get_homeassistant_plug_status(
  460. self, async_client: AsyncClient, smart_plug_factory, mock_homeassistant_service, db_session
  461. ):
  462. """Verify HA smart plug status can be retrieved."""
  463. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  464. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}/status")
  465. assert response.status_code == 200
  466. result = response.json()
  467. assert result["state"] == "ON"
  468. assert result["reachable"] is True
  469. @pytest.mark.asyncio
  470. @pytest.mark.integration
  471. async def test_create_homeassistant_plug_with_energy_sensors(self, async_client: AsyncClient):
  472. """Verify HA plug can be created with energy sensor entities."""
  473. data = {
  474. "name": "HA Plug with Energy",
  475. "plug_type": "homeassistant",
  476. "ha_entity_id": "switch.printer_plug",
  477. "ha_power_entity": "sensor.printer_power",
  478. "ha_energy_today_entity": "sensor.printer_energy_today",
  479. "ha_energy_total_entity": "sensor.printer_energy_total",
  480. "enabled": True,
  481. }
  482. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  483. assert response.status_code == 200
  484. result = response.json()
  485. assert result["ha_power_entity"] == "sensor.printer_power"
  486. assert result["ha_energy_today_entity"] == "sensor.printer_energy_today"
  487. assert result["ha_energy_total_entity"] == "sensor.printer_energy_total"
  488. @pytest.mark.asyncio
  489. @pytest.mark.integration
  490. async def test_update_ha_energy_sensor_entities(self, async_client: AsyncClient, smart_plug_factory, db_session):
  491. """Verify HA energy sensor entities can be updated."""
  492. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  493. response = await async_client.patch(
  494. f"/api/v1/smart-plugs/{plug.id}",
  495. json={
  496. "ha_power_entity": "sensor.new_power",
  497. "ha_energy_today_entity": "sensor.new_today",
  498. "ha_energy_total_entity": "sensor.new_total",
  499. },
  500. )
  501. assert response.status_code == 200
  502. result = response.json()
  503. assert result["ha_power_entity"] == "sensor.new_power"
  504. assert result["ha_energy_today_entity"] == "sensor.new_today"
  505. assert result["ha_energy_total_entity"] == "sensor.new_total"
  506. @pytest.mark.asyncio
  507. @pytest.mark.integration
  508. async def test_ha_sensors_endpoint_not_configured(self, async_client: AsyncClient):
  509. """Verify HA sensors endpoint returns error when not configured."""
  510. response = await async_client.get("/api/v1/smart-plugs/ha/sensors")
  511. assert response.status_code == 400
  512. assert "not configured" in response.json()["detail"].lower()
  513. # ========================================================================
  514. # MQTT Integration tests
  515. # ========================================================================
  516. @pytest.mark.asyncio
  517. @pytest.mark.integration
  518. async def test_create_mqtt_plug(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  519. """Verify MQTT plug can be created with topic and JSON paths."""
  520. data = {
  521. "name": "MQTT Energy Monitor",
  522. "plug_type": "mqtt",
  523. "mqtt_topic": "zigbee2mqtt/shelly-working-room",
  524. "mqtt_power_path": "power_l1",
  525. "mqtt_energy_path": "energy_l1",
  526. "mqtt_state_path": "state_l1",
  527. "mqtt_multiplier": 1.0,
  528. "enabled": True,
  529. }
  530. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  531. assert response.status_code == 200
  532. result = response.json()
  533. assert result["name"] == "MQTT Energy Monitor"
  534. assert result["plug_type"] == "mqtt"
  535. assert result["mqtt_topic"] == "zigbee2mqtt/shelly-working-room"
  536. assert result["mqtt_power_path"] == "power_l1"
  537. assert result["mqtt_energy_path"] == "energy_l1"
  538. assert result["mqtt_state_path"] == "state_l1"
  539. assert result["mqtt_multiplier"] == 1.0
  540. assert result["ip_address"] is None
  541. @pytest.mark.asyncio
  542. @pytest.mark.integration
  543. async def test_create_mqtt_plug_missing_topic(self, async_client: AsyncClient):
  544. """Verify creating MQTT plug without topic fails."""
  545. data = {
  546. "name": "MQTT Plug",
  547. "plug_type": "mqtt",
  548. # Missing mqtt_topic
  549. "mqtt_power_path": "power",
  550. "enabled": True,
  551. }
  552. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  553. assert response.status_code == 422 # Validation error
  554. @pytest.mark.asyncio
  555. @pytest.mark.integration
  556. async def test_create_mqtt_plug_missing_topic(self, async_client: AsyncClient):
  557. """Verify creating MQTT plug without any topic fails."""
  558. data = {
  559. "name": "MQTT Plug",
  560. "plug_type": "mqtt",
  561. # No topic configured at all
  562. "enabled": True,
  563. }
  564. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  565. assert response.status_code == 422 # Validation error
  566. @pytest.mark.asyncio
  567. @pytest.mark.integration
  568. async def test_create_mqtt_plug_with_multiplier(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  569. """Verify MQTT plug can use multiplier for unit conversion."""
  570. data = {
  571. "name": "MQTT mW to W",
  572. "plug_type": "mqtt",
  573. "mqtt_topic": "sensors/power",
  574. "mqtt_power_path": "power_mw",
  575. "mqtt_multiplier": 0.001, # Convert mW to W
  576. "enabled": True,
  577. }
  578. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  579. assert response.status_code == 200
  580. result = response.json()
  581. assert result["mqtt_multiplier"] == 0.001
  582. @pytest.mark.asyncio
  583. @pytest.mark.integration
  584. async def test_control_mqtt_plug_returns_error(self, async_client: AsyncClient, smart_plug_factory, db_session):
  585. """Verify MQTT plugs cannot be controlled (monitor-only)."""
  586. plug = await smart_plug_factory(
  587. plug_type="mqtt",
  588. mqtt_topic="test/topic",
  589. mqtt_power_path="power",
  590. )
  591. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  592. assert response.status_code == 400
  593. assert "monitor-only" in response.json()["detail"].lower()
  594. @pytest.mark.asyncio
  595. @pytest.mark.integration
  596. async def test_update_mqtt_plug_topic(self, async_client: AsyncClient, smart_plug_factory, db_session):
  597. """Verify MQTT plug topic can be updated."""
  598. plug = await smart_plug_factory(
  599. plug_type="mqtt",
  600. mqtt_topic="old/topic",
  601. mqtt_power_path="power",
  602. )
  603. response = await async_client.patch(
  604. f"/api/v1/smart-plugs/{plug.id}",
  605. json={
  606. "mqtt_topic": "new/topic",
  607. "mqtt_power_path": "new_power",
  608. },
  609. )
  610. assert response.status_code == 200
  611. result = response.json()
  612. assert result["mqtt_topic"] == "new/topic"
  613. assert result["mqtt_power_path"] == "new_power"
  614. # ========================================================================
  615. # Enhanced MQTT Integration tests (separate topics per data type)
  616. # ========================================================================
  617. @pytest.mark.asyncio
  618. @pytest.mark.integration
  619. async def test_create_mqtt_plug_with_separate_topics(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  620. """Verify MQTT plug can be created with separate topics for power, energy, and state."""
  621. data = {
  622. "name": "MQTT Separate Topics",
  623. "plug_type": "mqtt",
  624. "mqtt_power_topic": "zigbee/power",
  625. "mqtt_power_path": "power_l1",
  626. "mqtt_power_multiplier": 0.001,
  627. "mqtt_energy_topic": "zigbee/energy",
  628. "mqtt_energy_path": "energy_total",
  629. "mqtt_energy_multiplier": 1.0,
  630. "mqtt_state_topic": "zigbee/state",
  631. "mqtt_state_path": "state",
  632. "mqtt_state_on_value": "ON",
  633. "enabled": True,
  634. }
  635. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  636. assert response.status_code == 200
  637. result = response.json()
  638. assert result["name"] == "MQTT Separate Topics"
  639. assert result["plug_type"] == "mqtt"
  640. # Power fields
  641. assert result["mqtt_power_topic"] == "zigbee/power"
  642. assert result["mqtt_power_path"] == "power_l1"
  643. assert result["mqtt_power_multiplier"] == 0.001
  644. # Energy fields
  645. assert result["mqtt_energy_topic"] == "zigbee/energy"
  646. assert result["mqtt_energy_path"] == "energy_total"
  647. assert result["mqtt_energy_multiplier"] == 1.0
  648. # State fields
  649. assert result["mqtt_state_topic"] == "zigbee/state"
  650. assert result["mqtt_state_path"] == "state"
  651. assert result["mqtt_state_on_value"] == "ON"
  652. @pytest.mark.asyncio
  653. @pytest.mark.integration
  654. async def test_create_mqtt_plug_energy_only(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  655. """Verify MQTT plug can be created with only energy monitoring."""
  656. data = {
  657. "name": "Energy Only Monitor",
  658. "plug_type": "mqtt",
  659. "mqtt_energy_topic": "sensors/energy",
  660. "mqtt_energy_path": "kwh",
  661. "mqtt_energy_multiplier": 0.001, # Wh to kWh
  662. "enabled": True,
  663. }
  664. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  665. assert response.status_code == 200
  666. result = response.json()
  667. assert result["mqtt_energy_topic"] == "sensors/energy"
  668. assert result["mqtt_energy_path"] == "kwh"
  669. assert result["mqtt_energy_multiplier"] == 0.001
  670. @pytest.mark.asyncio
  671. @pytest.mark.integration
  672. async def test_create_mqtt_plug_state_only(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  673. """Verify MQTT plug can be created with only state monitoring."""
  674. data = {
  675. "name": "State Only Monitor",
  676. "plug_type": "mqtt",
  677. "mqtt_state_topic": "switches/outlet",
  678. "mqtt_state_path": "state",
  679. "mqtt_state_on_value": "true",
  680. "enabled": True,
  681. }
  682. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  683. assert response.status_code == 200
  684. result = response.json()
  685. assert result["mqtt_state_topic"] == "switches/outlet"
  686. assert result["mqtt_state_path"] == "state"
  687. assert result["mqtt_state_on_value"] == "true"
  688. @pytest.mark.asyncio
  689. @pytest.mark.integration
  690. async def test_create_mqtt_plug_topic_only_succeeds(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  691. """Verify creating MQTT plug with topic only (no path) succeeds for raw values."""
  692. data = {
  693. "name": "Raw MQTT Plug",
  694. "plug_type": "mqtt",
  695. # Topic only, no path - valid for raw numeric MQTT values
  696. "mqtt_power_topic": "zigbee/power",
  697. "enabled": True,
  698. }
  699. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  700. assert response.status_code == 200 # Should succeed
  701. result = response.json()
  702. assert result["mqtt_power_topic"] == "zigbee/power"
  703. assert result["mqtt_power_path"] is None
  704. @pytest.mark.asyncio
  705. @pytest.mark.integration
  706. async def test_update_mqtt_plug_separate_multipliers(
  707. self, async_client: AsyncClient, smart_plug_factory, db_session, mock_mqtt_smart_plug_service
  708. ):
  709. """Verify MQTT plug multipliers can be updated separately."""
  710. plug = await smart_plug_factory(
  711. plug_type="mqtt",
  712. mqtt_power_topic="test/power",
  713. mqtt_power_path="power",
  714. mqtt_power_multiplier=1.0,
  715. mqtt_energy_topic="test/energy",
  716. mqtt_energy_path="energy",
  717. mqtt_energy_multiplier=1.0,
  718. )
  719. response = await async_client.patch(
  720. f"/api/v1/smart-plugs/{plug.id}",
  721. json={
  722. "mqtt_power_multiplier": 0.001, # Change power multiplier only
  723. "mqtt_energy_multiplier": 0.001, # Change energy multiplier only
  724. },
  725. )
  726. assert response.status_code == 200
  727. result = response.json()
  728. assert result["mqtt_power_multiplier"] == 0.001
  729. assert result["mqtt_energy_multiplier"] == 0.001
  730. # ========================================================================
  731. # REST Smart Plug Integration tests
  732. # ========================================================================
  733. @pytest.mark.asyncio
  734. @pytest.mark.integration
  735. async def test_create_rest_plug(self, async_client: AsyncClient):
  736. """Verify REST plug can be created with ON/OFF URLs."""
  737. data = {
  738. "name": "REST Plug",
  739. "plug_type": "rest",
  740. "rest_on_url": "http://openhab:8080/rest/items/MyPlug",
  741. "rest_on_body": "ON",
  742. "rest_off_url": "http://openhab:8080/rest/items/MyPlug",
  743. "rest_off_body": "OFF",
  744. "rest_method": "POST",
  745. "enabled": True,
  746. }
  747. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  748. assert response.status_code == 200
  749. result = response.json()
  750. assert result["name"] == "REST Plug"
  751. assert result["plug_type"] == "rest"
  752. assert result["rest_on_url"] == "http://openhab:8080/rest/items/MyPlug"
  753. assert result["rest_on_body"] == "ON"
  754. assert result["rest_off_url"] == "http://openhab:8080/rest/items/MyPlug"
  755. assert result["rest_off_body"] == "OFF"
  756. assert result["rest_method"] == "POST"
  757. assert result["ip_address"] is None
  758. assert result["ha_entity_id"] is None
  759. @pytest.mark.asyncio
  760. @pytest.mark.integration
  761. async def test_create_rest_plug_on_url_only(self, async_client: AsyncClient):
  762. """Verify REST plug can be created with only ON URL."""
  763. data = {
  764. "name": "REST ON Only",
  765. "plug_type": "rest",
  766. "rest_on_url": "http://iobroker:8087/set/plug?value=true",
  767. "rest_method": "GET",
  768. "enabled": True,
  769. }
  770. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  771. assert response.status_code == 200
  772. result = response.json()
  773. assert result["rest_on_url"] == "http://iobroker:8087/set/plug?value=true"
  774. assert result["rest_off_url"] is None
  775. assert result["rest_method"] == "GET"
  776. @pytest.mark.asyncio
  777. @pytest.mark.integration
  778. async def test_create_rest_plug_missing_urls_fails(self, async_client: AsyncClient):
  779. """Verify creating REST plug without any URL fails."""
  780. data = {
  781. "name": "REST Plug",
  782. "plug_type": "rest",
  783. "enabled": True,
  784. }
  785. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  786. assert response.status_code == 422 # Validation error
  787. @pytest.mark.asyncio
  788. @pytest.mark.integration
  789. async def test_create_rest_plug_with_status_and_energy(self, async_client: AsyncClient):
  790. """Verify REST plug with status polling and energy monitoring."""
  791. data = {
  792. "name": "REST Full",
  793. "plug_type": "rest",
  794. "rest_on_url": "http://ha:8080/api/plug/on",
  795. "rest_off_url": "http://ha:8080/api/plug/off",
  796. "rest_method": "POST",
  797. "rest_headers": '{"Authorization": "Bearer test-token"}',
  798. "rest_status_url": "http://ha:8080/api/plug/status",
  799. "rest_status_path": "state",
  800. "rest_status_on_value": "ON",
  801. "rest_power_path": "power.current",
  802. "rest_energy_path": "energy.today",
  803. "enabled": True,
  804. }
  805. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  806. assert response.status_code == 200
  807. result = response.json()
  808. assert result["rest_headers"] == "********" # write-only
  809. assert result["rest_status_url"] == "http://ha:8080/api/plug/status"
  810. assert result["rest_status_path"] == "state"
  811. assert result["rest_status_on_value"] == "ON"
  812. assert result["rest_power_path"] == "power.current"
  813. assert result["rest_energy_path"] == "energy.today"
  814. @pytest.mark.asyncio
  815. @pytest.mark.integration
  816. async def test_update_rest_plug(self, async_client: AsyncClient, smart_plug_factory, db_session):
  817. """Verify REST plug fields can be updated."""
  818. plug = await smart_plug_factory(plug_type="rest")
  819. response = await async_client.patch(
  820. f"/api/v1/smart-plugs/{plug.id}",
  821. json={
  822. "rest_on_url": "http://new-host:8080/on",
  823. "rest_method": "PUT",
  824. },
  825. )
  826. assert response.status_code == 200
  827. result = response.json()
  828. assert result["rest_on_url"] == "http://new-host:8080/on"
  829. assert result["rest_method"] == "PUT"
  830. @pytest.mark.asyncio
  831. @pytest.mark.integration
  832. async def test_rest_plug_is_controllable(self, async_client: AsyncClient, smart_plug_factory, db_session):
  833. """Verify REST plugs can be controlled (not monitor-only like MQTT)."""
  834. plug = await smart_plug_factory(plug_type="rest")
  835. # REST plugs should NOT return 400 like MQTT plugs
  836. response = await async_client.post(
  837. f"/api/v1/smart-plugs/{plug.id}/control",
  838. json={"action": "on"},
  839. )
  840. # Should attempt to send the request (may fail with 503 since URL is not real,
  841. # but should NOT return 400 "monitor-only")
  842. assert response.status_code != 400