""" Tests for Home Assistant routes """ import pytest from fastapi.testclient import TestClient from unittest.mock import patch, AsyncMock from main import app client = TestClient(app) class TestHomeAssistantRoutes: """Test Home Assistant API routes""" @patch('routes.home_assistant.httpx.AsyncClient') async def test_get_entities_success(self, mock_client_class): """Test successful retrieval of Home Assistant entities""" # Mock the HTTP client response mock_response = AsyncMock() mock_response.json.return_value = { "sensor.temperature": { "entity_id": "sensor.temperature", "state": "22.5", "attributes": { "unit_of_measurement": "°C", "friendly_name": "Temperature" } }, "light.living_room": { "entity_id": "light.living_room", "state": "on", "attributes": { "friendly_name": "Living Room Light" } } } mock_response.status_code = 200 mock_client = AsyncMock() mock_client.get.return_value = mock_response mock_client_class.return_value.__aenter__.return_value = mock_client response = client.get("/home-assistant/entities") assert response.status_code == 200 data = response.json() assert "entities" in data assert len(data["entities"]) == 2 # Check first entity temp_entity = data["entities"][0] assert temp_entity["entity_id"] == "sensor.temperature" assert temp_entity["state"] == "22.5" assert temp_entity["attributes"]["unit_of_measurement"] == "°C" @patch('routes.home_assistant.httpx.AsyncClient') async def test_get_entities_api_error(self, mock_client_class): """Test handling of Home Assistant API errors""" # Mock HTTP error response mock_response = AsyncMock() mock_response.status_code = 500 mock_response.text = "Internal Server Error" mock_client = AsyncMock() mock_client.get.return_value = mock_response mock_client_class.return_value.__aenter__.return_value = mock_client response = client.get("/home-assistant/entities") assert response.status_code == 500 @patch('routes.home_assistant.httpx.AsyncClient') async def test_get_entities_connection_error(self, mock_client_class): """Test handling of connection errors""" # Mock connection error mock_client_class.return_value.__aenter__.side_effect = Exception("Connection failed") response = client.get("/home-assistant/entities") assert response.status_code == 500 def test_get_entities_endpoint_exists(self): """Test that the entities endpoint exists""" # This will fail if the route doesn't exist, but we can't test the actual # functionality without mocking the Home Assistant API response = client.get("/home-assistant/entities") # Should return either 200 (success) or 500 (API error) assert response.status_code in [200, 500] def test_home_assistant_routes_available(self): """Test that Home Assistant routes are available""" # Check that the router is included by testing a known endpoint response = client.get("/home-assistant/entities") # Should not return 404 (route not found) assert response.status_code != 404