test_smart_plugs_api.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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