test_smart_plugs_api.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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_update_schedule_settings(self, async_client: AsyncClient, smart_plug_factory, db_session):
  150. """Verify schedule settings can be updated."""
  151. plug = await smart_plug_factory(schedule_enabled=False)
  152. response = await async_client.patch(
  153. f"/api/v1/smart-plugs/{plug.id}",
  154. json={
  155. "schedule_enabled": True,
  156. "schedule_on_time": "08:00",
  157. "schedule_off_time": "22:00",
  158. },
  159. )
  160. assert response.status_code == 200
  161. result = response.json()
  162. assert result["schedule_enabled"] is True
  163. assert result["schedule_on_time"] == "08:00"
  164. assert result["schedule_off_time"] == "22:00"
  165. @pytest.mark.asyncio
  166. @pytest.mark.integration
  167. async def test_update_multiple_fields(self, async_client: AsyncClient, smart_plug_factory, db_session):
  168. """Verify multiple fields can be updated at once."""
  169. plug = await smart_plug_factory(
  170. name="Old Name",
  171. auto_on=True,
  172. auto_off=True,
  173. )
  174. response = await async_client.patch(
  175. f"/api/v1/smart-plugs/{plug.id}",
  176. json={
  177. "name": "New Name",
  178. "auto_on": False,
  179. "auto_off": False,
  180. },
  181. )
  182. assert response.status_code == 200
  183. result = response.json()
  184. assert result["name"] == "New Name"
  185. assert result["auto_on"] is False
  186. assert result["auto_off"] is False
  187. # ========================================================================
  188. # Control endpoints
  189. # ========================================================================
  190. @pytest.mark.asyncio
  191. @pytest.mark.integration
  192. async def test_control_smart_plug_on(
  193. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  194. ):
  195. """Verify smart plug can be turned on."""
  196. plug = await smart_plug_factory()
  197. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  198. assert response.status_code == 200
  199. result = response.json()
  200. assert result["success"] is True
  201. assert result["action"] == "on"
  202. @pytest.mark.asyncio
  203. @pytest.mark.integration
  204. async def test_control_smart_plug_off(
  205. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  206. ):
  207. """Verify smart plug can be turned off."""
  208. plug = await smart_plug_factory()
  209. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "off"})
  210. assert response.status_code == 200
  211. result = response.json()
  212. assert result["success"] is True
  213. assert result["action"] == "off"
  214. @pytest.mark.asyncio
  215. @pytest.mark.integration
  216. async def test_control_smart_plug_toggle(
  217. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  218. ):
  219. """Verify smart plug can be toggled."""
  220. plug = await smart_plug_factory()
  221. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "toggle"})
  222. assert response.status_code == 200
  223. result = response.json()
  224. assert result["success"] is True
  225. assert result["action"] == "toggle"
  226. @pytest.mark.asyncio
  227. @pytest.mark.integration
  228. async def test_control_invalid_action(self, async_client: AsyncClient, smart_plug_factory, db_session):
  229. """Verify invalid action returns error."""
  230. plug = await smart_plug_factory()
  231. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "invalid"})
  232. # FastAPI returns 422 for pydantic validation errors
  233. assert response.status_code == 422
  234. # ========================================================================
  235. # Status endpoint
  236. # ========================================================================
  237. @pytest.mark.asyncio
  238. @pytest.mark.integration
  239. async def test_get_smart_plug_status(
  240. self, async_client: AsyncClient, smart_plug_factory, mock_tasmota_service, db_session
  241. ):
  242. """Verify smart plug status can be retrieved."""
  243. plug = await smart_plug_factory()
  244. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}/status")
  245. assert response.status_code == 200
  246. result = response.json()
  247. assert result["state"] == "ON"
  248. assert result["reachable"] is True
  249. # ========================================================================
  250. # Delete endpoint
  251. # ========================================================================
  252. @pytest.mark.asyncio
  253. @pytest.mark.integration
  254. async def test_delete_smart_plug(self, async_client: AsyncClient, smart_plug_factory, db_session):
  255. """Verify smart plug can be deleted."""
  256. plug = await smart_plug_factory()
  257. plug_id = plug.id
  258. response = await async_client.delete(f"/api/v1/smart-plugs/{plug_id}")
  259. assert response.status_code == 200
  260. # Verify deleted
  261. response = await async_client.get(f"/api/v1/smart-plugs/{plug_id}")
  262. assert response.status_code == 404
  263. @pytest.mark.asyncio
  264. @pytest.mark.integration
  265. async def test_delete_nonexistent_plug(self, async_client: AsyncClient):
  266. """Verify deleting non-existent plug returns 404."""
  267. response = await async_client.delete("/api/v1/smart-plugs/9999")
  268. assert response.status_code == 404
  269. # ========================================================================
  270. # Switchbar visibility
  271. # ========================================================================
  272. @pytest.mark.asyncio
  273. @pytest.mark.integration
  274. async def test_update_show_in_switchbar(self, async_client: AsyncClient, smart_plug_factory, db_session):
  275. """Verify show_in_switchbar toggle persists correctly."""
  276. plug = await smart_plug_factory(show_in_switchbar=False)
  277. response = await async_client.patch(f"/api/v1/smart-plugs/{plug.id}", json={"show_in_switchbar": True})
  278. assert response.status_code == 200
  279. assert response.json()["show_in_switchbar"] is True
  280. # Verify persistence
  281. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}")
  282. assert response.json()["show_in_switchbar"] is True
  283. # ========================================================================
  284. # Tasmota Discovery endpoints
  285. # ========================================================================
  286. @pytest.mark.asyncio
  287. @pytest.mark.integration
  288. async def test_tasmota_discovery_scan(self, async_client: AsyncClient):
  289. """Verify Tasmota discovery scan can be started."""
  290. response = await async_client.post("/api/v1/smart-plugs/discover/scan")
  291. assert response.status_code == 200
  292. data = response.json()
  293. assert "running" in data
  294. assert "scanned" in data
  295. assert "total" in data
  296. @pytest.mark.asyncio
  297. @pytest.mark.integration
  298. async def test_tasmota_discovery_status(self, async_client: AsyncClient):
  299. """Verify Tasmota discovery status endpoint works."""
  300. response = await async_client.get("/api/v1/smart-plugs/discover/status")
  301. assert response.status_code == 200
  302. data = response.json()
  303. assert "running" in data
  304. assert "scanned" in data
  305. assert "total" in data
  306. @pytest.mark.asyncio
  307. @pytest.mark.integration
  308. async def test_tasmota_discovery_devices(self, async_client: AsyncClient):
  309. """Verify Tasmota discovered devices endpoint works."""
  310. response = await async_client.get("/api/v1/smart-plugs/discover/devices")
  311. assert response.status_code == 200
  312. data = response.json()
  313. assert isinstance(data, list)
  314. @pytest.mark.asyncio
  315. @pytest.mark.integration
  316. async def test_tasmota_discovery_stop(self, async_client: AsyncClient):
  317. """Verify Tasmota discovery can be stopped."""
  318. response = await async_client.post("/api/v1/smart-plugs/discover/stop")
  319. assert response.status_code == 200
  320. data = response.json()
  321. assert "running" in data
  322. # ========================================================================
  323. # Home Assistant Integration tests
  324. # ========================================================================
  325. @pytest.mark.asyncio
  326. @pytest.mark.integration
  327. async def test_create_homeassistant_plug(self, async_client: AsyncClient):
  328. """Verify Home Assistant plug can be created."""
  329. data = {
  330. "name": "HA Plug",
  331. "plug_type": "homeassistant",
  332. "ha_entity_id": "switch.printer_plug",
  333. "enabled": True,
  334. "auto_on": True,
  335. "auto_off": False,
  336. }
  337. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  338. assert response.status_code == 200
  339. result = response.json()
  340. assert result["name"] == "HA Plug"
  341. assert result["plug_type"] == "homeassistant"
  342. assert result["ha_entity_id"] == "switch.printer_plug"
  343. assert result["ip_address"] is None
  344. @pytest.mark.asyncio
  345. @pytest.mark.integration
  346. async def test_create_homeassistant_plug_missing_entity_id(self, async_client: AsyncClient):
  347. """Verify creating HA plug without entity_id fails."""
  348. data = {
  349. "name": "HA Plug",
  350. "plug_type": "homeassistant",
  351. # Missing ha_entity_id
  352. "enabled": True,
  353. }
  354. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  355. assert response.status_code == 422 # Validation error
  356. @pytest.mark.asyncio
  357. @pytest.mark.integration
  358. async def test_create_tasmota_plug_missing_ip(self, async_client: AsyncClient):
  359. """Verify creating Tasmota plug without IP fails."""
  360. data = {
  361. "name": "Tasmota Plug",
  362. "plug_type": "tasmota",
  363. # Missing ip_address
  364. "enabled": True,
  365. }
  366. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  367. assert response.status_code == 422 # Validation error
  368. @pytest.mark.asyncio
  369. @pytest.mark.integration
  370. async def test_ha_entities_endpoint_not_configured(self, async_client: AsyncClient):
  371. """Verify HA entities endpoint returns error when not configured."""
  372. response = await async_client.get("/api/v1/smart-plugs/ha/entities")
  373. assert response.status_code == 400
  374. assert "not configured" in response.json()["detail"].lower()
  375. @pytest.mark.asyncio
  376. @pytest.mark.integration
  377. async def test_update_plug_type(self, async_client: AsyncClient, smart_plug_factory, db_session):
  378. """Verify plug_type can be updated."""
  379. plug = await smart_plug_factory(plug_type="tasmota", ip_address="192.168.1.100")
  380. response = await async_client.patch(
  381. f"/api/v1/smart-plugs/{plug.id}",
  382. json={
  383. "plug_type": "homeassistant",
  384. "ha_entity_id": "switch.test",
  385. },
  386. )
  387. assert response.status_code == 200
  388. result = response.json()
  389. assert result["plug_type"] == "homeassistant"
  390. assert result["ha_entity_id"] == "switch.test"
  391. @pytest.mark.asyncio
  392. @pytest.mark.integration
  393. async def test_control_homeassistant_plug(
  394. self, async_client: AsyncClient, smart_plug_factory, mock_homeassistant_service, db_session
  395. ):
  396. """Verify HA smart plug can be controlled."""
  397. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  398. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  399. assert response.status_code == 200
  400. result = response.json()
  401. assert result["success"] is True
  402. assert result["action"] == "on"
  403. @pytest.mark.asyncio
  404. @pytest.mark.integration
  405. async def test_get_homeassistant_plug_status(
  406. self, async_client: AsyncClient, smart_plug_factory, mock_homeassistant_service, db_session
  407. ):
  408. """Verify HA smart plug status can be retrieved."""
  409. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  410. response = await async_client.get(f"/api/v1/smart-plugs/{plug.id}/status")
  411. assert response.status_code == 200
  412. result = response.json()
  413. assert result["state"] == "ON"
  414. assert result["reachable"] is True
  415. @pytest.mark.asyncio
  416. @pytest.mark.integration
  417. async def test_create_homeassistant_plug_with_energy_sensors(self, async_client: AsyncClient):
  418. """Verify HA plug can be created with energy sensor entities."""
  419. data = {
  420. "name": "HA Plug with Energy",
  421. "plug_type": "homeassistant",
  422. "ha_entity_id": "switch.printer_plug",
  423. "ha_power_entity": "sensor.printer_power",
  424. "ha_energy_today_entity": "sensor.printer_energy_today",
  425. "ha_energy_total_entity": "sensor.printer_energy_total",
  426. "enabled": True,
  427. }
  428. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  429. assert response.status_code == 200
  430. result = response.json()
  431. assert result["ha_power_entity"] == "sensor.printer_power"
  432. assert result["ha_energy_today_entity"] == "sensor.printer_energy_today"
  433. assert result["ha_energy_total_entity"] == "sensor.printer_energy_total"
  434. @pytest.mark.asyncio
  435. @pytest.mark.integration
  436. async def test_update_ha_energy_sensor_entities(self, async_client: AsyncClient, smart_plug_factory, db_session):
  437. """Verify HA energy sensor entities can be updated."""
  438. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="switch.test")
  439. response = await async_client.patch(
  440. f"/api/v1/smart-plugs/{plug.id}",
  441. json={
  442. "ha_power_entity": "sensor.new_power",
  443. "ha_energy_today_entity": "sensor.new_today",
  444. "ha_energy_total_entity": "sensor.new_total",
  445. },
  446. )
  447. assert response.status_code == 200
  448. result = response.json()
  449. assert result["ha_power_entity"] == "sensor.new_power"
  450. assert result["ha_energy_today_entity"] == "sensor.new_today"
  451. assert result["ha_energy_total_entity"] == "sensor.new_total"
  452. @pytest.mark.asyncio
  453. @pytest.mark.integration
  454. async def test_ha_sensors_endpoint_not_configured(self, async_client: AsyncClient):
  455. """Verify HA sensors endpoint returns error when not configured."""
  456. response = await async_client.get("/api/v1/smart-plugs/ha/sensors")
  457. assert response.status_code == 400
  458. assert "not configured" in response.json()["detail"].lower()
  459. # ========================================================================
  460. # MQTT Integration tests
  461. # ========================================================================
  462. @pytest.mark.asyncio
  463. @pytest.mark.integration
  464. async def test_create_mqtt_plug(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  465. """Verify MQTT plug can be created with topic and JSON paths."""
  466. data = {
  467. "name": "MQTT Energy Monitor",
  468. "plug_type": "mqtt",
  469. "mqtt_topic": "zigbee2mqtt/shelly-working-room",
  470. "mqtt_power_path": "power_l1",
  471. "mqtt_energy_path": "energy_l1",
  472. "mqtt_state_path": "state_l1",
  473. "mqtt_multiplier": 1.0,
  474. "enabled": True,
  475. }
  476. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  477. assert response.status_code == 200
  478. result = response.json()
  479. assert result["name"] == "MQTT Energy Monitor"
  480. assert result["plug_type"] == "mqtt"
  481. assert result["mqtt_topic"] == "zigbee2mqtt/shelly-working-room"
  482. assert result["mqtt_power_path"] == "power_l1"
  483. assert result["mqtt_energy_path"] == "energy_l1"
  484. assert result["mqtt_state_path"] == "state_l1"
  485. assert result["mqtt_multiplier"] == 1.0
  486. assert result["ip_address"] is None
  487. @pytest.mark.asyncio
  488. @pytest.mark.integration
  489. async def test_create_mqtt_plug_missing_topic(self, async_client: AsyncClient):
  490. """Verify creating MQTT plug without topic fails."""
  491. data = {
  492. "name": "MQTT Plug",
  493. "plug_type": "mqtt",
  494. # Missing mqtt_topic
  495. "mqtt_power_path": "power",
  496. "enabled": True,
  497. }
  498. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  499. assert response.status_code == 422 # Validation error
  500. @pytest.mark.asyncio
  501. @pytest.mark.integration
  502. async def test_create_mqtt_plug_missing_topic(self, async_client: AsyncClient):
  503. """Verify creating MQTT plug without any topic fails."""
  504. data = {
  505. "name": "MQTT Plug",
  506. "plug_type": "mqtt",
  507. # No topic configured at all
  508. "enabled": True,
  509. }
  510. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  511. assert response.status_code == 422 # Validation error
  512. @pytest.mark.asyncio
  513. @pytest.mark.integration
  514. async def test_create_mqtt_plug_with_multiplier(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  515. """Verify MQTT plug can use multiplier for unit conversion."""
  516. data = {
  517. "name": "MQTT mW to W",
  518. "plug_type": "mqtt",
  519. "mqtt_topic": "sensors/power",
  520. "mqtt_power_path": "power_mw",
  521. "mqtt_multiplier": 0.001, # Convert mW to W
  522. "enabled": True,
  523. }
  524. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  525. assert response.status_code == 200
  526. result = response.json()
  527. assert result["mqtt_multiplier"] == 0.001
  528. @pytest.mark.asyncio
  529. @pytest.mark.integration
  530. async def test_control_mqtt_plug_returns_error(self, async_client: AsyncClient, smart_plug_factory, db_session):
  531. """Verify MQTT plugs cannot be controlled (monitor-only)."""
  532. plug = await smart_plug_factory(
  533. plug_type="mqtt",
  534. mqtt_topic="test/topic",
  535. mqtt_power_path="power",
  536. )
  537. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  538. assert response.status_code == 400
  539. assert "monitor-only" in response.json()["detail"].lower()
  540. @pytest.mark.asyncio
  541. @pytest.mark.integration
  542. async def test_update_mqtt_plug_topic(self, async_client: AsyncClient, smart_plug_factory, db_session):
  543. """Verify MQTT plug topic can be updated."""
  544. plug = await smart_plug_factory(
  545. plug_type="mqtt",
  546. mqtt_topic="old/topic",
  547. mqtt_power_path="power",
  548. )
  549. response = await async_client.patch(
  550. f"/api/v1/smart-plugs/{plug.id}",
  551. json={
  552. "mqtt_topic": "new/topic",
  553. "mqtt_power_path": "new_power",
  554. },
  555. )
  556. assert response.status_code == 200
  557. result = response.json()
  558. assert result["mqtt_topic"] == "new/topic"
  559. assert result["mqtt_power_path"] == "new_power"
  560. # ========================================================================
  561. # Enhanced MQTT Integration tests (separate topics per data type)
  562. # ========================================================================
  563. @pytest.mark.asyncio
  564. @pytest.mark.integration
  565. async def test_create_mqtt_plug_with_separate_topics(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  566. """Verify MQTT plug can be created with separate topics for power, energy, and state."""
  567. data = {
  568. "name": "MQTT Separate Topics",
  569. "plug_type": "mqtt",
  570. "mqtt_power_topic": "zigbee/power",
  571. "mqtt_power_path": "power_l1",
  572. "mqtt_power_multiplier": 0.001,
  573. "mqtt_energy_topic": "zigbee/energy",
  574. "mqtt_energy_path": "energy_total",
  575. "mqtt_energy_multiplier": 1.0,
  576. "mqtt_state_topic": "zigbee/state",
  577. "mqtt_state_path": "state",
  578. "mqtt_state_on_value": "ON",
  579. "enabled": True,
  580. }
  581. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  582. assert response.status_code == 200
  583. result = response.json()
  584. assert result["name"] == "MQTT Separate Topics"
  585. assert result["plug_type"] == "mqtt"
  586. # Power fields
  587. assert result["mqtt_power_topic"] == "zigbee/power"
  588. assert result["mqtt_power_path"] == "power_l1"
  589. assert result["mqtt_power_multiplier"] == 0.001
  590. # Energy fields
  591. assert result["mqtt_energy_topic"] == "zigbee/energy"
  592. assert result["mqtt_energy_path"] == "energy_total"
  593. assert result["mqtt_energy_multiplier"] == 1.0
  594. # State fields
  595. assert result["mqtt_state_topic"] == "zigbee/state"
  596. assert result["mqtt_state_path"] == "state"
  597. assert result["mqtt_state_on_value"] == "ON"
  598. @pytest.mark.asyncio
  599. @pytest.mark.integration
  600. async def test_create_mqtt_plug_energy_only(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  601. """Verify MQTT plug can be created with only energy monitoring."""
  602. data = {
  603. "name": "Energy Only Monitor",
  604. "plug_type": "mqtt",
  605. "mqtt_energy_topic": "sensors/energy",
  606. "mqtt_energy_path": "kwh",
  607. "mqtt_energy_multiplier": 0.001, # Wh to kWh
  608. "enabled": True,
  609. }
  610. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  611. assert response.status_code == 200
  612. result = response.json()
  613. assert result["mqtt_energy_topic"] == "sensors/energy"
  614. assert result["mqtt_energy_path"] == "kwh"
  615. assert result["mqtt_energy_multiplier"] == 0.001
  616. @pytest.mark.asyncio
  617. @pytest.mark.integration
  618. async def test_create_mqtt_plug_state_only(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  619. """Verify MQTT plug can be created with only state monitoring."""
  620. data = {
  621. "name": "State Only Monitor",
  622. "plug_type": "mqtt",
  623. "mqtt_state_topic": "switches/outlet",
  624. "mqtt_state_path": "state",
  625. "mqtt_state_on_value": "true",
  626. "enabled": True,
  627. }
  628. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  629. assert response.status_code == 200
  630. result = response.json()
  631. assert result["mqtt_state_topic"] == "switches/outlet"
  632. assert result["mqtt_state_path"] == "state"
  633. assert result["mqtt_state_on_value"] == "true"
  634. @pytest.mark.asyncio
  635. @pytest.mark.integration
  636. async def test_create_mqtt_plug_topic_only_succeeds(self, async_client: AsyncClient, mock_mqtt_smart_plug_service):
  637. """Verify creating MQTT plug with topic only (no path) succeeds for raw values."""
  638. data = {
  639. "name": "Raw MQTT Plug",
  640. "plug_type": "mqtt",
  641. # Topic only, no path - valid for raw numeric MQTT values
  642. "mqtt_power_topic": "zigbee/power",
  643. "enabled": True,
  644. }
  645. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  646. assert response.status_code == 200 # Should succeed
  647. result = response.json()
  648. assert result["mqtt_power_topic"] == "zigbee/power"
  649. assert result["mqtt_power_path"] is None
  650. @pytest.mark.asyncio
  651. @pytest.mark.integration
  652. async def test_update_mqtt_plug_separate_multipliers(
  653. self, async_client: AsyncClient, smart_plug_factory, db_session, mock_mqtt_smart_plug_service
  654. ):
  655. """Verify MQTT plug multipliers can be updated separately."""
  656. plug = await smart_plug_factory(
  657. plug_type="mqtt",
  658. mqtt_power_topic="test/power",
  659. mqtt_power_path="power",
  660. mqtt_power_multiplier=1.0,
  661. mqtt_energy_topic="test/energy",
  662. mqtt_energy_path="energy",
  663. mqtt_energy_multiplier=1.0,
  664. )
  665. response = await async_client.patch(
  666. f"/api/v1/smart-plugs/{plug.id}",
  667. json={
  668. "mqtt_power_multiplier": 0.001, # Change power multiplier only
  669. "mqtt_energy_multiplier": 0.001, # Change energy multiplier only
  670. },
  671. )
  672. assert response.status_code == 200
  673. result = response.json()
  674. assert result["mqtt_power_multiplier"] == 0.001
  675. assert result["mqtt_energy_multiplier"] == 0.001