test_smart_plugs_api.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. @pytest.mark.asyncio
  460. @pytest.mark.integration
  461. async def test_create_homeassistant_script_plug(self, async_client: AsyncClient):
  462. """Verify Home Assistant script entity can be created as a plug.
  463. Scripts allow users to trigger HA automations that control multiple devices
  464. (e.g., turn on printer + fan together). Scripts can only be triggered (turn_on),
  465. not turned off.
  466. """
  467. data = {
  468. "name": "Turn On Printer Setup",
  469. "plug_type": "homeassistant",
  470. "ha_entity_id": "script.turn_on_printer_and_fan",
  471. "enabled": True,
  472. "auto_on": True,
  473. "auto_off": False, # Scripts don't support auto_off
  474. }
  475. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  476. assert response.status_code == 200
  477. result = response.json()
  478. assert result["name"] == "Turn On Printer Setup"
  479. assert result["plug_type"] == "homeassistant"
  480. assert result["ha_entity_id"] == "script.turn_on_printer_and_fan"
  481. @pytest.mark.asyncio
  482. @pytest.mark.integration
  483. async def test_control_homeassistant_script(
  484. self, async_client: AsyncClient, smart_plug_factory, mock_homeassistant_service, db_session
  485. ):
  486. """Verify HA script entity can be triggered via control endpoint."""
  487. plug = await smart_plug_factory(plug_type="homeassistant", ha_entity_id="script.turn_on_printer")
  488. # Scripts use "on" action to trigger
  489. response = await async_client.post(f"/api/v1/smart-plugs/{plug.id}/control", json={"action": "on"})
  490. assert response.status_code == 200
  491. result = response.json()
  492. assert result["success"] is True
  493. assert result["action"] == "on"
  494. @pytest.mark.asyncio
  495. @pytest.mark.integration
  496. async def test_invalid_ha_entity_domain(self, async_client: AsyncClient):
  497. """Verify invalid HA entity domains are rejected."""
  498. data = {
  499. "name": "Invalid Entity",
  500. "plug_type": "homeassistant",
  501. "ha_entity_id": "sensor.some_sensor", # sensor domain not allowed
  502. "enabled": True,
  503. }
  504. response = await async_client.post("/api/v1/smart-plugs/", json=data)
  505. assert response.status_code == 422 # Validation error
  506. @pytest.mark.asyncio
  507. @pytest.mark.integration
  508. async def test_script_can_coexist_with_regular_plug(
  509. self, async_client: AsyncClient, smart_plug_factory, printer_factory, db_session
  510. ):
  511. """Verify HA scripts can be assigned to printers that already have a regular plug.
  512. Scripts are for multi-device control (e.g., turn on printer + fan together),
  513. so they should coexist with the main power plug.
  514. """
  515. # Create a printer
  516. printer = await printer_factory(name="Test Printer")
  517. # Create a regular Tasmota plug assigned to the printer
  518. main_plug = await smart_plug_factory(
  519. name="Main Power Plug",
  520. plug_type="tasmota",
  521. ip_address="192.168.1.100",
  522. printer_id=printer.id,
  523. )
  524. assert main_plug.printer_id == printer.id
  525. # Now try to create a script also assigned to the same printer
  526. script_data = {
  527. "name": "Turn On Everything",
  528. "plug_type": "homeassistant",
  529. "ha_entity_id": "script.turn_on_printer_setup",
  530. "printer_id": printer.id,
  531. "enabled": True,
  532. }
  533. response = await async_client.post("/api/v1/smart-plugs/", json=script_data)
  534. # Should succeed - scripts can coexist with regular plugs
  535. assert response.status_code == 200
  536. result = response.json()
  537. assert result["printer_id"] == printer.id
  538. assert result["ha_entity_id"] == "script.turn_on_printer_setup"
  539. @pytest.mark.asyncio
  540. @pytest.mark.integration
  541. async def test_regular_plug_blocked_when_another_exists(
  542. self, async_client: AsyncClient, smart_plug_factory, printer_factory, db_session
  543. ):
  544. """Verify regular plugs cannot be assigned if printer already has one."""
  545. # Create a printer
  546. printer = await printer_factory(name="Test Printer")
  547. # Create a regular plug assigned to the printer
  548. await smart_plug_factory(
  549. name="Main Power Plug",
  550. plug_type="tasmota",
  551. ip_address="192.168.1.100",
  552. printer_id=printer.id,
  553. )
  554. # Try to create another regular plug for the same printer
  555. another_plug = {
  556. "name": "Second Plug",
  557. "plug_type": "homeassistant",
  558. "ha_entity_id": "switch.another_plug",
  559. "printer_id": printer.id,
  560. "enabled": True,
  561. }
  562. response = await async_client.post("/api/v1/smart-plugs/", json=another_plug)
  563. # Should fail - only one regular plug per printer
  564. assert response.status_code == 400
  565. assert "already has a smart plug" in response.json()["detail"]
  566. @pytest.mark.asyncio
  567. @pytest.mark.integration
  568. async def test_get_scripts_by_printer_filters_by_show_on_printer_card(
  569. self, async_client: AsyncClient, smart_plug_factory, printer_factory, db_session
  570. ):
  571. """Verify scripts endpoint only returns scripts with show_on_printer_card=True."""
  572. printer = await printer_factory(name="Test Printer")
  573. # Create a script with show_on_printer_card=True (default)
  574. visible_script = await smart_plug_factory(
  575. name="Visible Script",
  576. plug_type="homeassistant",
  577. ha_entity_id="script.visible_script",
  578. printer_id=printer.id,
  579. show_on_printer_card=True,
  580. )
  581. # Create a script with show_on_printer_card=False
  582. await smart_plug_factory(
  583. name="Hidden Script",
  584. plug_type="homeassistant",
  585. ha_entity_id="script.hidden_script",
  586. printer_id=printer.id,
  587. show_on_printer_card=False,
  588. )
  589. response = await async_client.get(f"/api/v1/smart-plugs/by-printer/{printer.id}/scripts")
  590. assert response.status_code == 200
  591. scripts = response.json()
  592. # Should only return the visible script
  593. assert len(scripts) == 1
  594. assert scripts[0]["id"] == visible_script.id
  595. assert scripts[0]["name"] == "Visible Script"
  596. @pytest.mark.asyncio
  597. @pytest.mark.integration
  598. async def test_script_auto_on_auto_off_fields(
  599. self, async_client: AsyncClient, smart_plug_factory, printer_factory, db_session
  600. ):
  601. """Verify scripts can have auto_on and auto_off set for automation triggers."""
  602. printer = await printer_factory(name="Test Printer")
  603. # Create a script with custom auto_on/auto_off settings
  604. script_data = {
  605. "name": "Fan Control Script",
  606. "plug_type": "homeassistant",
  607. "ha_entity_id": "script.fan_control",
  608. "printer_id": printer.id,
  609. "auto_on": True,
  610. "auto_off": False,
  611. "show_on_printer_card": True,
  612. }
  613. response = await async_client.post("/api/v1/smart-plugs/", json=script_data)
  614. assert response.status_code == 200
  615. result = response.json()
  616. assert result["auto_on"] is True
  617. assert result["auto_off"] is False
  618. assert result["show_on_printer_card"] is True
  619. # Update the script's auto_off setting
  620. update_response = await async_client.patch(f"/api/v1/smart-plugs/{result['id']}", json={"auto_off": True})
  621. assert update_response.status_code == 200
  622. updated = update_response.json()
  623. assert updated["auto_off"] is True