fix: Clean up and standardize test code formatting
Some checks failed
LabFusion CI/CD Pipeline / service-adapters (push) Failing after 20s
Docker Build and Push / build-and-push (push) Failing after 37s
Integration Tests / integration-tests (push) Failing after 32s
Integration Tests / performance-tests (push) Has been skipped
Service Adapters (Python FastAPI) / test (3.1) (push) Failing after 15s
LabFusion CI/CD Pipeline / api-gateway (push) Failing after 1m18s
Service Adapters (Python FastAPI) / test (3.11) (push) Failing after 22s
Service Adapters (Python FastAPI) / test (3.12) (push) Failing after 23s
Service Adapters (Python FastAPI) / test (3.9) (push) Failing after 21s
LabFusion CI/CD Pipeline / frontend (push) Failing after 2m0s
Service Adapters (Python FastAPI) / build (push) Has been skipped
LabFusion CI/CD Pipeline / api-docs (push) Successful in 1m53s
LabFusion CI/CD Pipeline / integration-tests (push) Has been skipped

### Summary of Changes
- Removed unnecessary blank lines and standardized import statements across test files.
- Ensured consistent use of quotes in patch decorators and improved formatting of test data structures.
- Enhanced readability and maintainability of test code by applying clean code principles.

### Expected Results
- Improved clarity and consistency in test code, facilitating easier understanding and future modifications.
This commit is contained in:
GSRN
2025-09-15 21:12:15 +02:00
parent 64d4e405c5
commit 8c37bff103
6 changed files with 82 additions and 114 deletions

View File

@@ -2,9 +2,9 @@
""" """
Test runner script for LabFusion Service Adapters Test runner script for LabFusion Service Adapters
""" """
import os
import subprocess import subprocess
import sys import sys
import os
def run_tests(): def run_tests():
@@ -25,7 +25,7 @@ def run_tests():
"--cov-report=html", "--cov-report=html",
"--cov-report=xml", "--cov-report=xml",
"--junitxml=tests/reports/junit.xml", "--junitxml=tests/reports/junit.xml",
"--tb=short" "--tb=short",
] ]
print(f"Running: {' '.join(cmd)}") print(f"Running: {' '.join(cmd)}")

View File

@@ -1,9 +1,11 @@
""" """
Pytest configuration and fixtures for service adapters tests Pytest configuration and fixtures for service adapters tests
""" """
from unittest.mock import patch
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from unittest.mock import patch
from main import app from main import app
@@ -21,17 +23,14 @@ def mock_services_config():
"home_assistant": { "home_assistant": {
"enabled": True, "enabled": True,
"url": "http://homeassistant.local:8123", "url": "http://homeassistant.local:8123",
"token": "test_token" "token": "test_token",
},
"frigate": {
"enabled": True,
"url": "http://frigate.local:5000"
}, },
"frigate": {"enabled": True, "url": "http://frigate.local:5000"},
"immich": { "immich": {
"enabled": False, "enabled": False,
"url": "http://immich.local:2283", "url": "http://immich.local:2283",
"api_key": "test_key" "api_key": "test_key",
} },
} }
@@ -42,18 +41,13 @@ def sample_ha_entities():
"sensor.temperature": { "sensor.temperature": {
"entity_id": "sensor.temperature", "entity_id": "sensor.temperature",
"state": "22.5", "state": "22.5",
"attributes": { "attributes": {"unit_of_measurement": "°C", "friendly_name": "Temperature"},
"unit_of_measurement": "°C",
"friendly_name": "Temperature"
}
}, },
"light.living_room": { "light.living_room": {
"entity_id": "light.living_room", "entity_id": "light.living_room",
"state": "on", "state": "on",
"attributes": { "attributes": {"friendly_name": "Living Room Light"},
"friendly_name": "Living Room Light" },
}
}
} }
@@ -67,15 +61,15 @@ def sample_frigate_events():
"timestamp": "2024-01-01T12:00:00Z", "timestamp": "2024-01-01T12:00:00Z",
"camera": "front_door", "camera": "front_door",
"label": "person", "label": "person",
"confidence": 0.95 "confidence": 0.95,
}, },
{ {
"id": "event_456", "id": "event_456",
"timestamp": "2024-01-01T12:05:00Z", "timestamp": "2024-01-01T12:05:00Z",
"camera": "back_yard", "camera": "back_yard",
"label": "car", "label": "car",
"confidence": 0.87 "confidence": 0.87,
} },
] ]
} }
@@ -90,7 +84,7 @@ def sample_immich_assets():
"filename": "IMG_20240101_120000.jpg", "filename": "IMG_20240101_120000.jpg",
"created_at": "2024-01-01T12:00:00Z", "created_at": "2024-01-01T12:00:00Z",
"tags": ["family", "vacation"], "tags": ["family", "vacation"],
"faces": ["person_1", "person_2"] "faces": ["person_1", "person_2"],
} }
] ]
} }
@@ -99,7 +93,7 @@ def sample_immich_assets():
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def mock_redis(): def mock_redis():
"""Mock Redis client for all tests""" """Mock Redis client for all tests"""
with patch('services.redis_client.redis_client') as mock_redis: with patch("services.redis_client.redis_client") as mock_redis:
mock_redis.ping.return_value = True mock_redis.ping.return_value = True
mock_redis.set.return_value = True mock_redis.set.return_value = True
mock_redis.get.return_value = None mock_redis.get.return_value = None

View File

@@ -1,10 +1,11 @@
""" """
Tests for general API routes Tests for general API routes
""" """
import pytest
from fastapi.testclient import TestClient
from unittest.mock import patch from unittest.mock import patch
from fastapi.testclient import TestClient
from main import app from main import app
client = TestClient(app) client = TestClient(app)
@@ -33,23 +34,17 @@ class TestGeneralRoutes:
# Verify timestamp is in ISO format # Verify timestamp is in ISO format
assert "T" in data["timestamp"] or "Z" in data["timestamp"] assert "T" in data["timestamp"] or "Z" in data["timestamp"]
@patch('services.config.SERVICES') @patch("services.config.SERVICES")
def test_get_services(self, mock_services): def test_get_services(self, mock_services):
"""Test the get services endpoint""" """Test the get services endpoint"""
# Mock the services configuration # Mock the services configuration
mock_services.items.return_value = [ mock_services.items.return_value = [
("home_assistant", { (
"enabled": True, "home_assistant",
"url": "http://homeassistant.local:8123" {"enabled": True, "url": "http://homeassistant.local:8123"},
}), ),
("frigate", { ("frigate", {"enabled": True, "url": "http://frigate.local:5000"}),
"enabled": True, ("immich", {"enabled": False, "url": "http://immich.local:2283"}),
"url": "http://frigate.local:5000"
}),
("immich", {
"enabled": False,
"url": "http://immich.local:2283"
})
] ]
response = client.get("/services") response = client.get("/services")

View File

@@ -1,9 +1,10 @@
""" """
Tests for Home Assistant routes Tests for Home Assistant routes
""" """
import pytest
from unittest.mock import AsyncMock, patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from unittest.mock import patch, AsyncMock
from main import app from main import app
@@ -13,7 +14,7 @@ client = TestClient(app)
class TestHomeAssistantRoutes: class TestHomeAssistantRoutes:
"""Test Home Assistant API routes""" """Test Home Assistant API routes"""
@patch('routes.home_assistant.httpx.AsyncClient') @patch("routes.home_assistant.httpx.AsyncClient")
async def test_get_entities_success(self, mock_client_class): async def test_get_entities_success(self, mock_client_class):
"""Test successful retrieval of Home Assistant entities""" """Test successful retrieval of Home Assistant entities"""
# Mock the HTTP client response # Mock the HTTP client response
@@ -24,16 +25,14 @@ class TestHomeAssistantRoutes:
"state": "22.5", "state": "22.5",
"attributes": { "attributes": {
"unit_of_measurement": "°C", "unit_of_measurement": "°C",
"friendly_name": "Temperature" "friendly_name": "Temperature",
} },
}, },
"light.living_room": { "light.living_room": {
"entity_id": "light.living_room", "entity_id": "light.living_room",
"state": "on", "state": "on",
"attributes": { "attributes": {"friendly_name": "Living Room Light"},
"friendly_name": "Living Room Light" },
}
}
} }
mock_response.status_code = 200 mock_response.status_code = 200
@@ -54,7 +53,7 @@ class TestHomeAssistantRoutes:
assert temp_entity["state"] == "22.5" assert temp_entity["state"] == "22.5"
assert temp_entity["attributes"]["unit_of_measurement"] == "°C" assert temp_entity["attributes"]["unit_of_measurement"] == "°C"
@patch('routes.home_assistant.httpx.AsyncClient') @patch("routes.home_assistant.httpx.AsyncClient")
async def test_get_entities_api_error(self, mock_client_class): async def test_get_entities_api_error(self, mock_client_class):
"""Test handling of Home Assistant API errors""" """Test handling of Home Assistant API errors"""
# Mock HTTP error response # Mock HTTP error response
@@ -69,11 +68,13 @@ class TestHomeAssistantRoutes:
response = client.get("/home-assistant/entities") response = client.get("/home-assistant/entities")
assert response.status_code == 500 assert response.status_code == 500
@patch('routes.home_assistant.httpx.AsyncClient') @patch("routes.home_assistant.httpx.AsyncClient")
async def test_get_entities_connection_error(self, mock_client_class): async def test_get_entities_connection_error(self, mock_client_class):
"""Test handling of connection errors""" """Test handling of connection errors"""
# Mock connection error # Mock connection error
mock_client_class.return_value.__aenter__.side_effect = Exception("Connection failed") mock_client_class.return_value.__aenter__.side_effect = Exception(
"Connection failed"
)
response = client.get("/home-assistant/entities") response = client.get("/home-assistant/entities")
assert response.status_code == 500 assert response.status_code == 500

View File

@@ -1,7 +1,7 @@
""" """
Tests for the main FastAPI application Tests for the main FastAPI application
""" """
import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from main import app from main import app

View File

@@ -1,16 +1,13 @@
""" """
Tests for Pydantic models and schemas Tests for Pydantic models and schemas
""" """
import pytest
from datetime import datetime
from typing import Dict, Any
from models.schemas import ( from datetime import datetime
ServiceStatus, HAAttributes, HAEntity, HAEntitiesResponse,
FrigateEvent, FrigateEventsResponse, ImmichAsset, ImmichAssetsResponse, import pytest
EventData, EventResponse, Event, EventsResponse,
HealthResponse, RootResponse from models.schemas import (EventData, FrigateEvent, HAAttributes, HAEntity,
) HealthResponse, RootResponse, ServiceStatus)
class TestServiceStatus: class TestServiceStatus:
@@ -19,9 +16,7 @@ class TestServiceStatus:
def test_service_status_creation(self): def test_service_status_creation(self):
"""Test creating a ServiceStatus instance""" """Test creating a ServiceStatus instance"""
service = ServiceStatus( service = ServiceStatus(
enabled=True, enabled=True, url="http://example.com", status="healthy"
url="http://example.com",
status="healthy"
) )
assert service.enabled is True assert service.enabled is True
assert service.url == "http://example.com" assert service.url == "http://example.com"
@@ -31,9 +26,7 @@ class TestServiceStatus:
"""Test ServiceStatus validation""" """Test ServiceStatus validation"""
# Valid data # Valid data
service = ServiceStatus( service = ServiceStatus(
enabled=False, enabled=False, url="https://api.example.com", status="unhealthy"
url="https://api.example.com",
status="unhealthy"
) )
assert service.enabled is False assert service.enabled is False
@@ -49,8 +42,7 @@ class TestHAAttributes:
def test_ha_attributes_creation(self): def test_ha_attributes_creation(self):
"""Test creating HAAttributes instance""" """Test creating HAAttributes instance"""
attrs = HAAttributes( attrs = HAAttributes(
unit_of_measurement="°C", unit_of_measurement="°C", friendly_name="Living Room Temperature"
friendly_name="Living Room Temperature"
) )
assert attrs.unit_of_measurement == "°C" assert attrs.unit_of_measurement == "°C"
assert attrs.friendly_name == "Living Room Temperature" assert attrs.friendly_name == "Living Room Temperature"
@@ -67,14 +59,9 @@ class TestHAEntity:
def test_ha_entity_creation(self): def test_ha_entity_creation(self):
"""Test creating HAEntity instance""" """Test creating HAEntity instance"""
attributes = HAAttributes( attributes = HAAttributes(unit_of_measurement="°C", friendly_name="Temperature")
unit_of_measurement="°C",
friendly_name="Temperature"
)
entity = HAEntity( entity = HAEntity(
entity_id="sensor.temperature", entity_id="sensor.temperature", state="22.5", attributes=attributes
state="22.5",
attributes=attributes
) )
assert entity.entity_id == "sensor.temperature" assert entity.entity_id == "sensor.temperature"
assert entity.state == "22.5" assert entity.state == "22.5"
@@ -91,7 +78,7 @@ class TestFrigateEvent:
timestamp="2024-01-01T12:00:00Z", timestamp="2024-01-01T12:00:00Z",
camera="front_door", camera="front_door",
label="person", label="person",
confidence=0.95 confidence=0.95,
) )
assert event.id == "event_123" assert event.id == "event_123"
assert event.camera == "front_door" assert event.camera == "front_door"
@@ -106,7 +93,7 @@ class TestFrigateEvent:
timestamp="2024-01-01T12:00:00Z", timestamp="2024-01-01T12:00:00Z",
camera="front_door", camera="front_door",
label="person", label="person",
confidence=0.5 confidence=0.5,
) )
assert event.confidence == 0.5 assert event.confidence == 0.5
@@ -117,7 +104,7 @@ class TestFrigateEvent:
timestamp="2024-01-01T12:00:00Z", timestamp="2024-01-01T12:00:00Z",
camera="front_door", camera="front_door",
label="person", label="person",
confidence=1.5 confidence=1.5,
) )
# Invalid confidence (negative) # Invalid confidence (negative)
@@ -127,7 +114,7 @@ class TestFrigateEvent:
timestamp="2024-01-01T12:00:00Z", timestamp="2024-01-01T12:00:00Z",
camera="front_door", camera="front_door",
label="person", label="person",
confidence=-0.1 confidence=-0.1,
) )
@@ -139,7 +126,7 @@ class TestEventData:
event = EventData( event = EventData(
service="home_assistant", service="home_assistant",
event_type="state_changed", event_type="state_changed",
metadata={"entity_id": "sensor.temperature", "new_state": "22.5"} metadata={"entity_id": "sensor.temperature", "new_state": "22.5"},
) )
assert event.service == "home_assistant" assert event.service == "home_assistant"
assert event.event_type == "state_changed" assert event.event_type == "state_changed"
@@ -147,10 +134,7 @@ class TestEventData:
def test_event_data_default_metadata(self): def test_event_data_default_metadata(self):
"""Test default metadata is empty dict""" """Test default metadata is empty dict"""
event = EventData( event = EventData(service="test_service", event_type="test_event")
service="test_service",
event_type="test_event"
)
assert event.metadata == {} assert event.metadata == {}
@@ -160,10 +144,7 @@ class TestHealthResponse:
def test_health_response_creation(self): def test_health_response_creation(self):
"""Test creating HealthResponse instance""" """Test creating HealthResponse instance"""
timestamp = datetime.now().isoformat() timestamp = datetime.now().isoformat()
health = HealthResponse( health = HealthResponse(status="healthy", timestamp=timestamp)
status="healthy",
timestamp=timestamp
)
assert health.status == "healthy" assert health.status == "healthy"
assert health.timestamp == timestamp assert health.timestamp == timestamp
@@ -173,9 +154,6 @@ class TestRootResponse:
def test_root_response_creation(self): def test_root_response_creation(self):
"""Test creating RootResponse instance""" """Test creating RootResponse instance"""
response = RootResponse( response = RootResponse(message="Test API", version="1.0.0")
message="Test API",
version="1.0.0"
)
assert response.message == "Test API" assert response.message == "Test API"
assert response.version == "1.0.0" assert response.version == "1.0.0"