test_rest_smart_plug.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. """Unit tests for REST smart plug service."""
  2. import json
  3. from unittest.mock import AsyncMock, MagicMock, patch
  4. import httpx
  5. import pytest
  6. from backend.app.services.rest_smart_plug import RESTSmartPlugService
  7. @pytest.fixture
  8. def service():
  9. return RESTSmartPlugService(timeout=5.0)
  10. @pytest.fixture
  11. def mock_plug():
  12. plug = MagicMock()
  13. plug.name = "Test REST Plug"
  14. plug.plug_type = "rest"
  15. plug.rest_on_url = "http://192.168.1.50:8080/api/plug/on"
  16. plug.rest_on_body = '{"state": "on"}'
  17. plug.rest_off_url = "http://192.168.1.50:8080/api/plug/off"
  18. plug.rest_off_body = '{"state": "off"}'
  19. plug.rest_method = "POST"
  20. plug.rest_headers = '{"Authorization": "Bearer test-token"}'
  21. plug.rest_status_url = "http://192.168.1.50:8080/api/plug/status"
  22. plug.rest_status_path = "state"
  23. plug.rest_status_on_value = "ON"
  24. plug.rest_power_url = None
  25. plug.rest_power_path = "power"
  26. plug.rest_power_multiplier = 1.0
  27. plug.rest_energy_url = None
  28. plug.rest_energy_path = "energy.today"
  29. plug.rest_energy_multiplier = 1.0
  30. # Pinned to None rather than left as a MagicMock: an auto-created attribute is
  31. # truthy, so get_energy would think a lifetime path was configured and take a
  32. # branch no test meant to exercise.
  33. plug.rest_energy_total_path = None
  34. plug.rest_energy_total_multiplier = 1.0
  35. return plug
  36. class TestURLValidation:
  37. def test_valid_ip_url(self, service):
  38. assert service._validate_url("http://192.168.1.50:8080/api") is True
  39. def test_hostname_url(self, service):
  40. assert service._validate_url("http://openhab.local:8080/api") is True
  41. def test_loopback_blocked(self, service):
  42. assert service._validate_url("http://127.0.0.1/api") is False
  43. def test_link_local_blocked(self, service):
  44. assert service._validate_url("http://169.254.1.1/api") is False
  45. def test_empty_hostname(self, service):
  46. assert service._validate_url("http:///api") is False
  47. class TestParseHeaders:
  48. def test_valid_json(self, service):
  49. headers = service._parse_headers('{"Authorization": "Bearer abc", "X-Custom": "val"}')
  50. assert headers == {"Authorization": "Bearer abc", "X-Custom": "val"}
  51. def test_none_headers(self, service):
  52. assert service._parse_headers(None) == {}
  53. def test_empty_string(self, service):
  54. assert service._parse_headers("") == {}
  55. def test_invalid_json(self, service):
  56. assert service._parse_headers("not json") == {}
  57. class TestExtractJsonPath:
  58. def test_simple_path(self, service):
  59. data = {"state": "ON"}
  60. assert service._extract_json_path(data, "state") == "ON"
  61. def test_nested_path(self, service):
  62. data = {"data": {"power": {"current": 42.5}}}
  63. assert service._extract_json_path(data, "data.power.current") == 42.5
  64. def test_missing_path(self, service):
  65. data = {"state": "ON"}
  66. assert service._extract_json_path(data, "missing") is None
  67. def test_empty_path(self, service):
  68. assert service._extract_json_path({"a": 1}, "") is None
  69. def test_none_path(self, service):
  70. assert service._extract_json_path({"a": 1}, None) is None
  71. class TestTurnOn:
  72. @pytest.mark.asyncio
  73. async def test_turn_on_success(self, service, mock_plug):
  74. mock_response = MagicMock()
  75. mock_response.status_code = 200
  76. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  77. result = await service.turn_on(mock_plug)
  78. assert result is True
  79. @pytest.mark.asyncio
  80. async def test_turn_on_failure(self, service, mock_plug):
  81. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=None):
  82. result = await service.turn_on(mock_plug)
  83. assert result is False
  84. @pytest.mark.asyncio
  85. async def test_turn_on_no_url(self, service, mock_plug):
  86. mock_plug.rest_on_url = None
  87. result = await service.turn_on(mock_plug)
  88. assert result is False
  89. class TestTurnOff:
  90. @pytest.mark.asyncio
  91. async def test_turn_off_success(self, service, mock_plug):
  92. mock_response = MagicMock()
  93. mock_response.status_code = 200
  94. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  95. result = await service.turn_off(mock_plug)
  96. assert result is True
  97. @pytest.mark.asyncio
  98. async def test_turn_off_no_url(self, service, mock_plug):
  99. mock_plug.rest_off_url = None
  100. result = await service.turn_off(mock_plug)
  101. assert result is False
  102. class TestGetStatus:
  103. @pytest.mark.asyncio
  104. async def test_status_on(self, service, mock_plug):
  105. mock_response = MagicMock()
  106. mock_response.json.return_value = {"state": "ON"}
  107. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  108. result = await service.get_status(mock_plug)
  109. assert result["state"] == "ON"
  110. assert result["reachable"] is True
  111. @pytest.mark.asyncio
  112. async def test_status_off(self, service, mock_plug):
  113. mock_response = MagicMock()
  114. mock_response.json.return_value = {"state": "OFF"}
  115. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  116. result = await service.get_status(mock_plug)
  117. assert result["state"] == "OFF"
  118. assert result["reachable"] is True
  119. @pytest.mark.asyncio
  120. async def test_status_unreachable(self, service, mock_plug):
  121. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=None):
  122. result = await service.get_status(mock_plug)
  123. assert result["state"] is None
  124. assert result["reachable"] is False
  125. @pytest.mark.asyncio
  126. async def test_status_no_url(self, service, mock_plug):
  127. mock_plug.rest_status_url = None
  128. result = await service.get_status(mock_plug)
  129. assert result["state"] is None
  130. assert result["reachable"] is True # No URL = assume reachable
  131. class TestGetEnergy:
  132. @pytest.mark.asyncio
  133. async def test_energy_with_paths(self, service, mock_plug):
  134. mock_response = MagicMock()
  135. mock_response.json.return_value = {"power": 42.5, "energy": {"today": 1.23}}
  136. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  137. result = await service.get_energy(mock_plug)
  138. assert result["power"] == 42.5
  139. assert result["today"] == 1.23
  140. class TestGetEnergyLifetimeCounter:
  141. """#2539. A Shelly Plug S Gen3 reports exactly one energy figure, and it is
  142. cumulative. It has to land in ``total``, not ``today``.
  143. """
  144. # The reporter's own Switch.GetStatus payload.
  145. SHELLY = {"apower": 84.0, "aenergy": {"total": 2620.197}}
  146. @pytest.fixture
  147. def shelly(self, mock_plug):
  148. mock_plug.rest_power_path = "apower"
  149. mock_plug.rest_power_multiplier = 1.0
  150. mock_plug.rest_energy_path = None # a Shelly has no notion of "today"
  151. mock_plug.rest_energy_total_path = "aenergy.total"
  152. mock_plug.rest_energy_total_multiplier = 0.001 # Wh -> kWh
  153. return mock_plug
  154. @pytest.mark.asyncio
  155. async def test_lifetime_counter_lands_in_total_not_today(self, service, shelly):
  156. response = MagicMock()
  157. response.json.return_value = self.SHELLY
  158. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=response):
  159. result = await service.get_energy(shelly)
  160. assert result["power"] == 84.0
  161. assert result["total"] == pytest.approx(2.620197)
  162. # The bug: this used to be 2.620197, a lifetime figure wearing today's
  163. # label, which then never reset at midnight.
  164. assert "today" not in result
  165. @pytest.mark.asyncio
  166. async def test_a_plug_reporting_both_counters_keeps_them_apart(self, service, mock_plug):
  167. """A Tasmota behind a REST bridge exposes Today and Total. Neither may
  168. overwrite the other.
  169. """
  170. mock_plug.rest_power_path = "power"
  171. mock_plug.rest_energy_path = "energy.today"
  172. mock_plug.rest_energy_multiplier = 1.0
  173. mock_plug.rest_energy_total_path = "energy.total"
  174. mock_plug.rest_energy_total_multiplier = 1.0
  175. response = MagicMock()
  176. response.json.return_value = {"power": 42.5, "energy": {"today": 1.23, "total": 987.6}}
  177. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=response):
  178. result = await service.get_energy(mock_plug)
  179. assert result["today"] == 1.23
  180. assert result["total"] == 987.6
  181. @pytest.mark.asyncio
  182. async def test_total_path_alone_is_enough_to_read_energy(self, service, mock_plug):
  183. """No power path, no today path — only the lifetime counter. get_energy
  184. used to bail out entirely, since its guard only knew about the other two.
  185. """
  186. mock_plug.rest_power_path = None
  187. mock_plug.rest_energy_path = None
  188. mock_plug.rest_energy_total_path = "aenergy.total"
  189. mock_plug.rest_energy_total_multiplier = 0.001
  190. response = MagicMock()
  191. response.json.return_value = self.SHELLY
  192. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=response):
  193. result = await service.get_energy(mock_plug)
  194. assert result == {"total": pytest.approx(2.620197)}
  195. @pytest.mark.asyncio
  196. async def test_both_counters_share_one_fetch(self, service, shelly):
  197. """Today and Total ride on the same Shelly response. Reading them must not
  198. cost two HTTP round-trips against a device on the end of a wifi link.
  199. """
  200. shelly.rest_energy_path = "aenergy.total" # same URL as the total path
  201. response = MagicMock()
  202. response.json.return_value = self.SHELLY
  203. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=response) as send:
  204. await service.get_energy(shelly)
  205. assert send.await_count == 1
  206. @pytest.mark.asyncio
  207. async def test_energy_no_status_url_no_separate_urls(self, service, mock_plug):
  208. """No URLs at all (status=None, power_url=None, energy_url=None) → None."""
  209. mock_plug.rest_status_url = None
  210. mock_plug.rest_power_url = None
  211. mock_plug.rest_energy_url = None
  212. result = await service.get_energy(mock_plug)
  213. assert result is None
  214. @pytest.mark.asyncio
  215. async def test_energy_no_paths(self, service, mock_plug):
  216. mock_plug.rest_power_path = None
  217. mock_plug.rest_energy_path = None
  218. result = await service.get_energy(mock_plug)
  219. assert result is None
  220. @pytest.mark.asyncio
  221. async def test_energy_with_separate_urls(self, service, mock_plug):
  222. """Power and energy fetched from different URLs."""
  223. mock_plug.rest_power_url = "http://192.168.1.50:8087/power"
  224. mock_plug.rest_energy_url = "http://192.168.1.50:8087/energy"
  225. power_response = MagicMock()
  226. power_response.json.return_value = {"power": 9.5}
  227. energy_response = MagicMock()
  228. energy_response.json.return_value = {"energy": {"today": 30947.07}}
  229. call_count = 0
  230. async def mock_send(url, method="GET", headers=None, body=None):
  231. nonlocal call_count
  232. call_count += 1
  233. if "power" in url:
  234. return power_response
  235. return energy_response
  236. with patch.object(service, "_send_request", side_effect=mock_send):
  237. result = await service.get_energy(mock_plug)
  238. assert call_count == 2
  239. assert result["power"] == 9.5
  240. assert result["today"] == 30947.07
  241. @pytest.mark.asyncio
  242. async def test_energy_with_multipliers(self, service, mock_plug):
  243. """Multipliers convert units (e.g., Wh → kWh)."""
  244. mock_plug.rest_energy_multiplier = 0.001 # Wh → kWh
  245. mock_response = MagicMock()
  246. mock_response.json.return_value = {"power": 9.5, "energy": {"today": 30947.07}}
  247. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  248. result = await service.get_energy(mock_plug)
  249. assert result["power"] == 9.5 # No multiplier (default 1.0)
  250. assert result["today"] == pytest.approx(30.94707) # 30947.07 * 0.001
  251. @pytest.mark.asyncio
  252. async def test_energy_separate_url_falls_back_to_status(self, service, mock_plug):
  253. """When no separate URL is set, falls back to status URL."""
  254. mock_plug.rest_power_url = None
  255. mock_plug.rest_energy_url = None
  256. mock_response = MagicMock()
  257. mock_response.json.return_value = {"power": 42.5, "energy": {"today": 1.23}}
  258. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response):
  259. result = await service.get_energy(mock_plug)
  260. assert result["power"] == 42.5
  261. assert result["today"] == 1.23
  262. @pytest.mark.asyncio
  263. async def test_energy_no_urls_at_all(self, service, mock_plug):
  264. """No status URL and no separate URLs → None."""
  265. mock_plug.rest_status_url = None
  266. mock_plug.rest_power_url = None
  267. mock_plug.rest_energy_url = None
  268. result = await service.get_energy(mock_plug)
  269. assert result is None
  270. @pytest.mark.asyncio
  271. async def test_energy_deduplicates_same_url(self, service, mock_plug):
  272. """When power and energy both fall back to status URL, only one HTTP request is made."""
  273. mock_plug.rest_power_url = None
  274. mock_plug.rest_energy_url = None
  275. mock_response = MagicMock()
  276. mock_response.json.return_value = {"power": 42.5, "energy": {"today": 1.23}}
  277. with patch.object(service, "_send_request", new_callable=AsyncMock, return_value=mock_response) as mock_send:
  278. result = await service.get_energy(mock_plug)
  279. assert mock_send.call_count == 1
  280. assert result["power"] == 42.5
  281. assert result["today"] == 1.23
  282. class TestTestConnection:
  283. @pytest.mark.asyncio
  284. async def test_connection_success(self, service):
  285. with patch("httpx.AsyncClient") as mock_client_cls:
  286. mock_client = AsyncMock()
  287. mock_response = MagicMock()
  288. mock_response.raise_for_status = MagicMock()
  289. mock_client.request = AsyncMock(return_value=mock_response)
  290. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  291. mock_client.__aexit__ = AsyncMock(return_value=None)
  292. mock_client_cls.return_value = mock_client
  293. result = await service.test_connection("http://192.168.1.50:8080/api")
  294. assert result["success"] is True
  295. @pytest.mark.asyncio
  296. async def test_connection_timeout(self, service):
  297. with patch("httpx.AsyncClient") as mock_client_cls:
  298. mock_client = AsyncMock()
  299. mock_client.request = AsyncMock(side_effect=httpx.TimeoutException("timeout"))
  300. mock_client.__aenter__ = AsyncMock(return_value=mock_client)
  301. mock_client.__aexit__ = AsyncMock(return_value=None)
  302. mock_client_cls.return_value = mock_client
  303. result = await service.test_connection("http://192.168.1.50:8080/api")
  304. assert result["success"] is False
  305. assert "timed out" in result["error"]
  306. @pytest.mark.asyncio
  307. async def test_connection_invalid_url(self, service):
  308. result = await service.test_connection("http://127.0.0.1/api")
  309. assert result["success"] is False
  310. assert "blocked" in result["error"].lower()