Creating Controller service which will control WROLPi services, admin, SMART, disks, and status. nginx will fallback to Controller UI when React UI is unavailable (such as during upgrades).

This commit is contained in:
Roland 2025-12-11 18:32:55 -07:00 • committed by lrnselfreliance
parent 344fe9035f
commit b9158b60fe
66 changed files with 9920 additions and 327 deletions

View file

@ -0,0 +1 @@
"""Controller tests."""

View file

@ -0,0 +1,242 @@
"""
Unit tests for controller.lib.admin module.
"""
from unittest import mock
import pytest
from controller.lib.admin import (
disable_hotspot,
disable_throttle,
enable_hotspot,
enable_throttle,
get_hotspot_status,
get_throttle_status,
reboot_system,
restart_all_services,
shutdown_system,
HotspotStatus,
GovernorStatus,
)
class TestGetHotspotStatus:
"""Tests for get_hotspot_status function."""
def test_returns_hotspot_status_enum(self):
"""Should return a HotspotStatus enum value."""
result = get_hotspot_status()
assert isinstance(result, HotspotStatus)
def test_returns_unknown_in_docker_mode(self):
"""Should return unknown when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = get_hotspot_status()
assert result == HotspotStatus.unknown
def test_handles_nmcli_not_found(self):
"""Should handle nmcli not being available."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_current_ssid", return_value=None):
with mock.patch("subprocess.run", side_effect=FileNotFoundError()):
result = get_hotspot_status()
assert result == HotspotStatus.unknown
def test_handles_timeout(self):
"""Should handle subprocess timeout."""
import subprocess
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_current_ssid", return_value=None):
with mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("nmcli", 5)):
result = get_hotspot_status()
assert result == HotspotStatus.unknown
class TestEnableHotspot:
"""Tests for enable_hotspot function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = enable_hotspot()
assert result["success"] is False
assert "Docker" in result.get("error", "")
def test_handles_nmcli_not_found(self):
"""Should handle nmcli not being available."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("controller.lib.admin.get_config", return_value={}):
with mock.patch("subprocess.run", side_effect=FileNotFoundError()):
result = enable_hotspot()
assert result["success"] is False
assert "nmcli" in result.get("error", "").lower()
class TestDisableHotspot:
"""Tests for disable_hotspot function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = disable_hotspot()
assert result["success"] is False
assert "Docker" in result.get("error", "")
def test_handles_nmcli_not_found(self):
"""Should handle nmcli not being available."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("subprocess.run", side_effect=FileNotFoundError()):
result = disable_hotspot()
assert result["success"] is False
assert "nmcli" in result.get("error", "").lower()
class TestGetThrottleStatus:
"""Tests for get_throttle_status function."""
def test_returns_governor_status_enum(self):
"""Should return a GovernorStatus enum value."""
result = get_throttle_status()
assert isinstance(result, GovernorStatus)
def test_returns_unknown_in_docker_mode(self):
"""Should return unknown when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = get_throttle_status()
assert result == GovernorStatus.unknown
def test_returns_unknown_when_cpufreq_not_available(self, tmp_path):
"""Should return unknown when cpufreq doesn't exist."""
from pathlib import Path
nonexistent_path = tmp_path / "nonexistent"
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch.object(Path, "exists", return_value=False):
result = get_throttle_status()
assert result == GovernorStatus.unknown
def test_reads_governor_from_sysfs(self, tmp_path):
"""Should read governor from sysfs when available."""
from pathlib import Path
governor_path = tmp_path / "scaling_governor"
governor_path.write_text("ondemand")
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
# This test verifies the function structure - actual sysfs testing
# would require a real Raspberry Pi environment
result = get_throttle_status()
assert isinstance(result, GovernorStatus)
class TestEnableThrottle:
"""Tests for enable_throttle function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = enable_throttle()
assert result["success"] is False
assert "Docker" in result.get("error", "")
class TestDisableThrottle:
"""Tests for disable_throttle function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = disable_throttle()
assert result["success"] is False
assert "Docker" in result.get("error", "")
class TestShutdownSystem:
"""Tests for shutdown_system function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = shutdown_system()
assert result["success"] is False
assert "Docker" in result.get("error", "")
def test_handles_shutdown_not_found(self):
"""Should handle shutdown command not being available."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("subprocess.Popen", side_effect=FileNotFoundError()):
result = shutdown_system()
assert result["success"] is False
assert "not found" in result.get("error", "").lower()
def test_calls_shutdown_command(self):
"""Should call shutdown command with correct args."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
mock_popen = mock.Mock()
with mock.patch("subprocess.Popen", mock_popen):
result = shutdown_system()
mock_popen.assert_called_once_with(["shutdown", "-h", "now"])
assert result["success"] is True
class TestRebootSystem:
"""Tests for reboot_system function."""
def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = reboot_system()
assert result["success"] is False
assert "Docker" in result.get("error", "")
def test_handles_reboot_not_found(self):
"""Should handle reboot command not being available."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
with mock.patch("subprocess.Popen", side_effect=FileNotFoundError()):
result = reboot_system()
assert result["success"] is False
assert "not found" in result.get("error", "").lower()
def test_calls_reboot_command(self):
"""Should call reboot command."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
mock_popen = mock.Mock()
with mock.patch("subprocess.Popen", mock_popen):
result = reboot_system()
mock_popen.assert_called_once_with(["reboot"])
assert result["success"] is True
class TestRestartAllServices:
"""Tests for restart_all_services function."""
@pytest.mark.asyncio
async def test_returns_error_in_docker_mode(self):
"""Should return error when in Docker mode."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=True):
result = await restart_all_services()
assert result["success"] is False
assert "Docker" in result.get("error", "")
@pytest.mark.asyncio
async def test_restarts_services(self):
"""Should attempt to restart all services."""
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False):
# Mock subprocess.run to succeed
mock_result = mock.Mock()
mock_result.returncode = 0
mock_result.stderr = ""
# Mock _restart_self to avoid actual restart
with mock.patch("subprocess.run", return_value=mock_result):
with mock.patch("controller.lib.admin._restart_self"):
with mock.patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.call_later = mock.Mock()
result = await restart_all_services()
assert result["success"] is True
assert "services" in result
# Should include controller as pending
assert result["services"]["wrolpi-controller"]["pending"] is True

View file

@ -0,0 +1,145 @@
"""
Integration tests for Controller admin API endpoints.
"""
class TestHotspotStatusEndpoint:
"""Tests for /api/hotspot/status endpoint."""
def test_hotspot_status_returns_200(self, test_client):
"""Hotspot status endpoint should return 200 OK."""
response = test_client.get("/api/hotspot/status")
assert response.status_code == 200
def test_hotspot_status_returns_expected_fields(self, test_client):
"""Hotspot status should return enabled and available fields."""
response = test_client.get("/api/hotspot/status")
data = response.json()
assert "enabled" in data
assert "available" in data
def test_hotspot_status_shows_unavailable_in_docker(self, test_client_docker_mode):
"""Hotspot should be unavailable in Docker mode."""
response = test_client_docker_mode.get("/api/hotspot/status")
data = response.json()
assert data["available"] is False
class TestHotspotEnableEndpoint:
"""Tests for /api/hotspot/enable endpoint."""
def test_hotspot_enable_fails_in_docker(self, test_client_docker_mode):
"""Hotspot enable should fail in Docker mode."""
response = test_client_docker_mode.post("/api/hotspot/enable")
assert response.status_code == 500
assert "Docker" in response.json()["detail"]
class TestHotspotDisableEndpoint:
"""Tests for /api/hotspot/disable endpoint."""
def test_hotspot_disable_fails_in_docker(self, test_client_docker_mode):
"""Hotspot disable should fail in Docker mode."""
response = test_client_docker_mode.post("/api/hotspot/disable")
assert response.status_code == 500
assert "Docker" in response.json()["detail"]
class TestThrottleStatusEndpoint:
"""Tests for /api/throttle/status endpoint."""
def test_throttle_status_returns_200(self, test_client):
"""Throttle status endpoint should return 200 OK."""
response = test_client.get("/api/throttle/status")
assert response.status_code == 200
def test_throttle_status_returns_expected_fields(self, test_client):
"""Throttle status should return enabled and available fields."""
response = test_client.get("/api/throttle/status")
data = response.json()
assert "enabled" in data
assert "available" in data
def test_throttle_status_shows_unavailable_in_docker(self, test_client_docker_mode):
"""Throttle should be unavailable in Docker mode."""
response = test_client_docker_mode.get("/api/throttle/status")
data = response.json()
assert data["available"] is False
class TestThrottleEnableEndpoint:
"""Tests for /api/throttle/enable endpoint."""
def test_throttle_enable_fails_in_docker(self, test_client_docker_mode):
"""Throttle enable should fail in Docker mode."""
response = test_client_docker_mode.post("/api/throttle/enable")
assert response.status_code == 500
assert "Docker" in response.json()["detail"]
class TestThrottleDisableEndpoint:
"""Tests for /api/throttle/disable endpoint."""
def test_throttle_disable_fails_in_docker(self, test_client_docker_mode):
"""Throttle disable should fail in Docker mode."""
response = test_client_docker_mode.post("/api/throttle/disable")
assert response.status_code == 500
assert "Docker" in response.json()["detail"]
class TestShutdownEndpoint:
"""Tests for /api/shutdown endpoint."""
def test_shutdown_returns_501_in_docker(self, test_client_docker_mode):
"""Shutdown should return 501 in Docker mode."""
response = test_client_docker_mode.post("/api/shutdown")
assert response.status_code == 501
assert "Docker" in response.json()["detail"]
class TestRebootEndpoint:
"""Tests for /api/reboot endpoint."""
def test_reboot_returns_501_in_docker(self, test_client_docker_mode):
"""Reboot should return 501 in Docker mode."""
response = test_client_docker_mode.post("/api/reboot")
assert response.status_code == 501
assert "Docker" in response.json()["detail"]
class TestRestartEndpoint:
"""Tests for /api/restart endpoint."""
def test_restart_returns_501_in_docker(self, test_client_docker_mode):
"""Restart should return 501 in Docker mode."""
response = test_client_docker_mode.post("/api/restart")
assert response.status_code == 501
assert "Docker" in response.json()["detail"]
class TestOpenAPIIncludesAdminEndpoints:
"""Tests that OpenAPI documentation includes admin endpoints."""
def test_openapi_has_hotspot_paths(self, test_client):
"""OpenAPI schema should include hotspot paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/hotspot/status" in data["paths"]
assert "/api/hotspot/enable" in data["paths"]
assert "/api/hotspot/disable" in data["paths"]
def test_openapi_has_throttle_paths(self, test_client):
"""OpenAPI schema should include throttle paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/throttle/status" in data["paths"]
assert "/api/throttle/enable" in data["paths"]
assert "/api/throttle/disable" in data["paths"]
def test_openapi_has_system_control_paths(self, test_client):
"""OpenAPI schema should include system control paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/shutdown" in data["paths"]
assert "/api/reboot" in data["paths"]
assert "/api/restart" in data["paths"]

222
controller/test/test_api.py Normal file
View file

@ -0,0 +1,222 @@
"""
Integration tests for Controller API endpoints.
"""
from unittest import mock
import pytest
from fastapi.testclient import TestClient
from controller import __version__
class TestHealthEndpoint:
"""Tests for /api/health endpoint."""
def test_health_returns_200(self, test_client):
"""Health endpoint should return 200 OK."""
response = test_client.get("/api/health")
assert response.status_code == 200
def test_health_returns_expected_fields(self, test_client):
"""Health endpoint should return expected fields."""
response = test_client.get("/api/health")
data = response.json()
assert data["status"] == "healthy"
assert data["version"] == __version__
assert data["docker_mode"] is False
assert "drive_mounted" in data
assert isinstance(data["drive_mounted"], bool)
def test_health_returns_docker_mode_true(self, test_client_docker_mode):
"""Health endpoint should return docker_mode=true when in Docker."""
response = test_client_docker_mode.get("/api/health")
data = response.json()
assert data["docker_mode"] is True
class TestDashboardEndpoint:
"""Tests for / dashboard endpoint (UI)."""
def test_dashboard_returns_200(self, test_client):
"""Dashboard endpoint should return 200 OK."""
response = test_client.get("/")
assert response.status_code == 200
def test_dashboard_returns_html(self, test_client):
"""Dashboard endpoint should return HTML."""
response = test_client.get("/")
assert "text/html" in response.headers["content-type"]
def test_dashboard_contains_title(self, test_client):
"""Dashboard should contain title."""
response = test_client.get("/")
assert b"WROLPi Controller" in response.content
def test_dashboard_contains_version(self, test_client):
"""Dashboard should contain version."""
response = test_client.get("/")
assert __version__.encode() in response.content
def test_dashboard_contains_status_cards(self, test_client):
"""Dashboard should contain status cards."""
response = test_client.get("/")
content = response.text
assert "CPU" in content
assert "Memory" in content
assert "Load" in content
assert "Storage" in content
def test_dashboard_contains_disks_section(self, test_client):
"""Dashboard should contain disks section."""
response = test_client.get("/")
content = response.text
assert "Disks" in content
assert 'id="disks"' in content
def test_dashboard_contains_services_section(self, test_client):
"""Dashboard should contain services section."""
response = test_client.get("/")
content = response.text
assert "Services" in content
assert 'id="services"' in content
def test_dashboard_contains_system_actions(self, test_client):
"""Dashboard should contain system actions section."""
response = test_client.get("/")
content = response.text
assert "System Actions" in content
assert "Restart All Services" in content
def test_dashboard_shows_docker_banner_when_dockerized(self, test_client_docker_mode):
"""Dashboard should show Docker mode banner when in Docker."""
response = test_client_docker_mode.get("/")
content = response.text
assert "Running in Docker mode" in content
def test_dashboard_no_docker_banner_when_not_dockerized(self, test_client):
"""Dashboard should not show Docker mode banner when not in Docker."""
response = test_client.get("/")
content = response.text
assert "Running in Docker mode" not in content
def test_dashboard_shows_boot_column_when_not_dockerized(self, test_client):
"""Dashboard should show Boot column in services table when not in Docker."""
response = test_client.get("/")
content = response.text
assert "<th>Boot</th>" in content
# Should have toggle switches
assert 'class="toggle"' in content
def test_dashboard_no_boot_column_when_dockerized(self, test_client_docker_mode):
"""Dashboard should not show Boot column in services table when in Docker."""
response = test_client_docker_mode.get("/")
content = response.text
assert "<th>Boot</th>" not in content
# The table body (rendered server-side) should not have boot toggles
# Note: JavaScript template literals may contain 'id="boot-' for dynamic updates,
# but the actual rendered <tbody> should not have boot toggles in Docker mode
import re
tbody_match = re.search(r'<tbody>(.*?)</tbody>', content, re.DOTALL)
if tbody_match:
tbody_content = tbody_match.group(1)
assert 'id="boot-' not in tbody_content
def test_dashboard_has_upgrade_banner_element(self, test_client):
"""Dashboard should have upgrade banner element for upgrade mode."""
response = test_client.get("/")
content = response.text
assert 'id="upgrade-banner"' in content
assert "Upgrade in Progress" in content
assert "Do not power off" in content
def test_dashboard_has_mount_modal(self, test_client):
"""Dashboard should have mount modal for disk mounting."""
response = test_client.get("/")
content = response.text
assert 'id="mount-modal"' in content
assert 'id="mount-point-input"' in content
assert 'id="mount-persist-checkbox"' in content
assert "Persistent (survive reboots)" in content
def test_dashboard_has_persist_column_in_disks_js(self, test_client):
"""Dashboard JavaScript should include Persist column in disk table."""
response = test_client.get("/")
content = response.text
# The loadDisks() function should create a table with Persist column
assert "<th>Persist</th>" in content
# Should have togglePersist function
assert "function togglePersist" in content
# Should fetch fstab entries
assert "api/disks/fstab" in content
class TestOpenAPIEndpoint:
"""Tests for OpenAPI documentation endpoint."""
def test_openapi_returns_200(self, test_client):
"""OpenAPI endpoint should return 200 OK."""
response = test_client.get("/openapi.json")
assert response.status_code == 200
def test_openapi_has_title(self, test_client):
"""OpenAPI schema should have correct title."""
response = test_client.get("/openapi.json")
data = response.json()
assert data["info"]["title"] == "WROLPi Controller"
def test_openapi_has_version(self, test_client):
"""OpenAPI schema should have version."""
response = test_client.get("/openapi.json")
data = response.json()
assert data["info"]["version"] == __version__
def test_openapi_has_api_paths(self, test_client):
"""OpenAPI schema should have API paths defined."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/health" in data["paths"]
class TestDocsEndpoint:
"""Tests for Swagger UI documentation endpoint."""
def test_docs_returns_200(self, test_client):
"""Docs endpoint should return 200 OK."""
response = test_client.get("/docs")
assert response.status_code == 200
def test_docs_returns_html(self, test_client):
"""Docs endpoint should return HTML."""
response = test_client.get("/docs")
assert "text/html" in response.headers["content-type"]
class TestDriveMountedStatus:
"""Tests for drive mounted status in responses."""
@pytest.mark.parametrize("endpoint,mounted,expected", [
("/api/health", True, True),
("/api/health", False, False),
])
def test_drive_mounted_status(self, reset_runtime_config, mock_docker_mode, endpoint, mounted, expected):
"""Endpoints should return correct drive_mounted status."""
from controller.main import app
with mock.patch(
"controller.main.is_primary_drive_mounted", return_value=mounted
):
with TestClient(app) as client:
response = client.get(endpoint)
data = response.json()
assert data["drive_mounted"] is expected
def test_dashboard_shows_drive_not_mounted_banner(self, reset_runtime_config, mock_docker_mode):
"""Dashboard should show banner when drive is not mounted."""
from controller.main import app
with mock.patch(
"controller.main.is_primary_drive_mounted", return_value=False
):
with TestClient(app) as client:
response = client.get("/")
assert "Primary drive not mounted" in response.text

View file

@ -0,0 +1,268 @@
"""
Unit tests for controller.lib.config module.
"""
import copy
import pytest
import yaml
from controller.lib.config import (
get_config,
get_config_value,
is_docker_mode,
is_primary_drive_mounted,
reload_config_from_drive,
save_config,
update_config,
_deep_merge,
_get_config_diff,
)
class TestGetConfig:
"""Tests for get_config function."""
def test_get_config_returns_dict(self, reset_runtime_config):
"""get_config should return a dictionary."""
config = get_config()
assert isinstance(config, dict)
def test_get_config_has_default_keys(self, reset_runtime_config):
"""get_config should have all default keys."""
config = get_config()
assert "port" in config
assert "media_directory" in config
assert "drives" in config
assert "managed_services" in config
assert "hotspot" in config
assert "throttle" in config
def test_get_config_default_port(self, reset_runtime_config):
"""Default port should be 8087."""
config = get_config()
assert config["port"] == 8087
class TestGetConfigValue:
"""Tests for get_config_value function."""
@pytest.mark.parametrize("key,expected", [
("port", 8087),
("media_directory", "/media/wrolpi"),
("drives.auto_mount", True),
("hotspot.ssid", "WROLPi"),
("throttle.default_governor", "ondemand"),
])
def test_get_value(self, reset_runtime_config, key, expected):
"""Should get values using dot notation for nested keys."""
assert get_config_value(key) == expected
@pytest.mark.parametrize("key,default,expected", [
("nonexistent", None, None),
("nonexistent", "fallback", "fallback"),
("drives.nonexistent", 42, 42),
("a.b.c.d.e", "default", "default"),
])
def test_get_missing_value_returns_default(self, reset_runtime_config, key, default, expected):
"""Should return default for missing keys."""
assert get_config_value(key, default) == expected
class TestIsDockerMode:
"""Tests for is_docker_mode function."""
def test_docker_mode_false_when_not_set(self, mock_docker_mode):
"""Docker mode should be False when env var not set."""
assert is_docker_mode() is False
def test_docker_mode_true_when_set(self, mock_docker_mode_enabled):
"""Docker mode should be True when DOCKERIZED=true."""
assert is_docker_mode() is True
class TestIsPrimaryDriveMounted:
"""Tests for is_primary_drive_mounted function."""
def test_drive_mounted_when_config_dir_exists(self, test_config_directory):
"""Should return True when /media/wrolpi/config exists."""
# We need to mock the path check to use our test directory
from unittest import mock
with mock.patch(
"controller.lib.config.Path"
) as mock_path:
mock_path.return_value.exists.return_value = True
# Re-import to get fresh function
# Actually test with real path
# The real test - check that the function works correctly
assert test_config_directory.exists()
def test_drive_not_mounted_when_config_dir_missing(self, test_directory):
"""Should return False when config dir doesn't exist."""
from unittest import mock
with mock.patch(
"controller.lib.config.Path"
) as mock_path:
mock_instance = mock.MagicMock()
mock_instance.exists.return_value = False
mock_path.return_value = mock_instance
assert is_primary_drive_mounted() is False
class TestReloadConfigFromDrive:
"""Tests for reload_config_from_drive function."""
def test_reload_returns_false_when_no_config_file(
self, reset_runtime_config, mock_config_path
):
"""Should return False when controller.yaml doesn't exist."""
result = reload_config_from_drive()
assert result is False
def test_reload_returns_true_when_config_exists(
self, reset_runtime_config, mock_config_path
):
"""Should return True and load config when file exists."""
# Write a test config
mock_config_path.write_text(yaml.dump({"port": 9999}))
result = reload_config_from_drive()
assert result is True
assert get_config_value("port") == 9999
def test_reload_merges_with_defaults(
self, reset_runtime_config, mock_config_path
):
"""Config from file should be merged with defaults."""
# Write partial config - only override port
mock_config_path.write_text(yaml.dump({"port": 8888}))
reload_config_from_drive()
# Port should be overridden
assert get_config_value("port") == 8888
# Other defaults should still exist
assert get_config_value("media_directory") == "/media/wrolpi"
assert get_config_value("drives.auto_mount") is True
def test_reload_handles_invalid_yaml(
self, reset_runtime_config, mock_config_path
):
"""Should return False and keep defaults for invalid YAML."""
mock_config_path.write_text("invalid: yaml: content: [}")
result = reload_config_from_drive()
assert result is False
# Should still have defaults
assert get_config_value("port") == 8087
def test_reload_handles_empty_file(
self, reset_runtime_config, mock_config_path
):
"""Should handle empty config file gracefully."""
mock_config_path.write_text("")
result = reload_config_from_drive()
# Empty file is valid YAML (returns None), merged with defaults
# File exists and was processed, so returns True
assert result is True
# Config should still have all defaults
assert get_config_value("port") == 8087
class TestSaveConfig:
"""Tests for save_config function."""
def test_save_config_raises_when_drive_not_mounted(
self, reset_runtime_config, mock_drive_not_mounted
):
"""Should raise RuntimeError when drive not mounted."""
with pytest.raises(RuntimeError, match="primary drive not mounted"):
save_config()
def test_save_config_creates_file(
self, reset_runtime_config, mock_config_path, mock_drive_mounted
):
"""Should create config file when saving."""
update_config("port", 9999)
save_config()
assert mock_config_path.exists()
saved = yaml.safe_load(mock_config_path.read_text())
assert saved["port"] == 9999
def test_save_config_only_saves_diff(
self, reset_runtime_config, mock_config_path, mock_drive_mounted
):
"""Should only save values that differ from defaults."""
# Only change port
update_config("port", 9999)
save_config()
saved = yaml.safe_load(mock_config_path.read_text())
# Only port should be in the file
assert saved == {"port": 9999}
class TestUpdateConfig:
"""Tests for update_config function."""
def test_update_simple_value(self, reset_runtime_config):
"""Should update simple top-level values."""
update_config("port", 9999)
assert get_config_value("port") == 9999
def test_update_nested_value(self, reset_runtime_config):
"""Should update nested values using dot notation."""
update_config("hotspot.ssid", "MyNetwork")
assert get_config_value("hotspot.ssid") == "MyNetwork"
def test_update_creates_nested_structure(self, reset_runtime_config):
"""Should create nested structure if it doesn't exist."""
update_config("new.nested.key", "value")
assert get_config_value("new.nested.key") == "value"
class TestDeepMerge:
"""Tests for _deep_merge helper function."""
@pytest.mark.parametrize("base,override,expected", [
# Flat dict merge
({"a": 1, "b": 2}, {"b": 3, "c": 4}, {"a": 1, "b": 3, "c": 4}),
# Nested dict merge
({"a": {"x": 1, "y": 2}}, {"a": {"y": 3, "z": 4}}, {"a": {"x": 1, "y": 3, "z": 4}}),
# Override replaces non-dict
({"a": {"x": 1}}, {"a": "string"}, {"a": "string"}),
])
def test_merge_dicts(self, base, override, expected):
"""Should merge dictionaries correctly."""
result = _deep_merge(base, override)
assert result == expected
def test_merge_does_not_modify_original(self):
"""Should not modify original dictionaries."""
base = {"a": 1}
override = {"b": 2}
original_base = copy.deepcopy(base)
_deep_merge(base, override)
assert base == original_base
class TestGetConfigDiff:
"""Tests for _get_config_diff helper function."""
@pytest.mark.parametrize("config,default,expected", [
# Equal configs return empty
({"a": 1, "b": 2}, {"a": 1, "b": 2}, {}),
# Changed values only
({"a": 1, "b": 3}, {"a": 1, "b": 2}, {"b": 3}),
# New keys
({"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 2}, {"c": 3}),
# Nested changes
({"a": {"x": 1, "y": 3}}, {"a": {"x": 1, "y": 2}}, {"a": {"y": 3}}),
])
def test_get_config_diff(self, config, default, expected):
"""Should return only values that differ from defaults."""
assert _get_config_diff(config, default) == expected

View file

@ -0,0 +1,130 @@
"""
Unit tests for controller.defaults module.
"""
import pytest
from controller.defaults import DEFAULT_CONFIG
class TestDefaultConfig:
"""Tests for DEFAULT_CONFIG structure."""
def test_default_config_is_dict(self):
"""DEFAULT_CONFIG should be a dictionary."""
assert isinstance(DEFAULT_CONFIG, dict)
def test_default_port(self):
"""Default port should be 8087."""
assert DEFAULT_CONFIG["port"] == 8087
def test_default_media_directory(self):
"""Default media directory should be /media/wrolpi."""
assert DEFAULT_CONFIG["media_directory"] == "/media/wrolpi"
class TestDrivesConfig:
"""Tests for drives configuration."""
def test_drives_config_exists(self):
"""Drives config should exist."""
assert "drives" in DEFAULT_CONFIG
assert isinstance(DEFAULT_CONFIG["drives"], dict)
@pytest.mark.parametrize("filesystem", ["ext4", "btrfs", "vfat", "exfat"])
def test_supported_filesystem(self, filesystem):
"""Should have expected filesystems in supported list."""
filesystems = DEFAULT_CONFIG["drives"]["supported_filesystems"]
assert isinstance(filesystems, list)
assert filesystem in filesystems
def test_auto_mount_default(self):
"""Auto mount should be True by default."""
assert DEFAULT_CONFIG["drives"]["auto_mount"] is True
def test_mounts_empty_by_default(self):
"""Mounts list should be empty by default."""
assert DEFAULT_CONFIG["drives"]["mounts"] == []
class TestManagedServicesConfig:
"""Tests for managed services configuration."""
def test_managed_services_exists(self):
"""Managed services config should exist."""
assert "managed_services" in DEFAULT_CONFIG
assert isinstance(DEFAULT_CONFIG["managed_services"], list)
def test_managed_services_count(self):
"""Should have expected number of managed services."""
services = DEFAULT_CONFIG["managed_services"]
assert len(services) == 10
@pytest.mark.parametrize("name,expected", [
("wrolpi-api",
{"systemd_name": "wrolpi-api", "port": 8081, "viewable": True, "description": "Python API (Sanic)"}),
("wrolpi-app", {"port": 3000, "viewable": False}),
("nginx", {"port": 80}),
("postgresql", {"port": 5432, "viewable": False}),
("wrolpi-upgrade", {"port": None, "viewable": False, "show_only_when_running": True}),
])
def test_service_config(self, name, expected):
"""Should have service configured with expected values."""
services = DEFAULT_CONFIG["managed_services"]
service = next((s for s in services if s["name"] == name), None)
assert service is not None, f"Service {name} not found"
for key, value in expected.items():
assert service[key] == value, f"Service {name} has {key}={service.get(key)}, expected {value}"
@pytest.mark.parametrize("name,use_https", [
("wrolpi-help", True),
("wrolpi-kiwix", True),
("apache2", True),
("wrolpi-api", False),
("wrolpi-app", False),
("postgresql", False),
])
def test_service_use_https(self, name, use_https):
"""HTTPS services should have use_https=True, others should have False."""
services = DEFAULT_CONFIG["managed_services"]
service = next((s for s in services if s["name"] == name), None)
assert service is not None, f"Service {name} not found"
assert service.get("use_https", False) == use_https, \
f"Service {name} should have use_https={use_https}"
def test_all_services_have_required_fields(self):
"""All services should have required fields."""
required_fields = ["name", "systemd_name", "port", "viewable", "use_https", "description"]
for service in DEFAULT_CONFIG["managed_services"]:
for field in required_fields:
assert field in service, f"Service {service.get('name')} missing {field}"
class TestHotspotConfig:
"""Tests for hotspot configuration."""
def test_hotspot_config_exists(self):
"""Hotspot config should exist."""
assert "hotspot" in DEFAULT_CONFIG
assert isinstance(DEFAULT_CONFIG["hotspot"], dict)
@pytest.mark.parametrize("key,expected", [
("device", "wlan0"),
("ssid", "WROLPi"),
("password", "wrolpi hotspot"),
])
def test_hotspot_defaults(self, key, expected):
"""Hotspot should have expected default values."""
assert DEFAULT_CONFIG["hotspot"][key] == expected
class TestThrottleConfig:
"""Tests for throttle configuration."""
def test_throttle_config_exists(self):
"""Throttle config should exist."""
assert "throttle" in DEFAULT_CONFIG
assert isinstance(DEFAULT_CONFIG["throttle"], dict)
def test_default_governor(self):
"""Default governor should be ondemand."""
assert DEFAULT_CONFIG["throttle"]["default_governor"] == "ondemand"

View file

@ -0,0 +1,285 @@
"""
Unit tests for controller.lib.disks module.
"""
import json
from unittest import mock
import pytest
from controller.lib.disks import (
BlockDevice,
get_block_devices,
get_uuid,
validate_mount_point,
mount_drive,
unmount_drive,
is_mount_busy,
get_mounts,
)
class TestBlockDevice:
"""Tests for BlockDevice dataclass."""
def test_create_block_device(self):
"""Should create a BlockDevice instance."""
device = BlockDevice(
name="sda1",
path="/dev/sda1",
size="100G",
fstype="ext4",
mountpoint="/media/data",
label="DATA",
uuid="1234-5678",
model="Samsung SSD",
)
assert device.name == "sda1"
assert device.path == "/dev/sda1"
assert device.is_wrolpi_drive is False
def test_block_device_defaults(self):
"""Should have default values."""
device = BlockDevice(
name="sda1",
path="/dev/sda1",
size="100G",
fstype=None,
mountpoint=None,
label=None,
uuid=None,
model=None,
)
assert device.is_wrolpi_drive is False
class TestGetBlockDevices:
"""Tests for get_block_devices function."""
def test_returns_empty_in_docker_mode(self):
"""Should return empty list in Docker mode."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=True):
result = get_block_devices()
assert result == []
def test_returns_devices_from_lsblk(self):
"""Should parse lsblk output and return devices."""
lsblk_output = json.dumps({
"blockdevices": [
{
"name": "sda",
"path": "/dev/sda",
"size": "500G",
"type": "disk",
"model": "Samsung SSD",
"children": [
{
"name": "sda1",
"path": "/dev/sda1",
"size": "500G",
"type": "part",
"fstype": "ext4",
"mountpoint": "/media/data",
"label": "DATA",
"uuid": "1234-5678",
}
]
}
]
})
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout=lsblk_output)
result = get_block_devices()
assert len(result) == 1
assert result[0].name == "sda1"
assert result[0].fstype == "ext4"
assert result[0].model == "Samsung SSD"
def test_filters_unsupported_filesystems(self):
"""Should only return devices with supported filesystems."""
lsblk_output = json.dumps({
"blockdevices": [
{
"name": "sda",
"type": "disk",
"children": [
{"name": "sda1", "path": "/dev/sda1", "size": "100G", "type": "part", "fstype": "ext4"},
{"name": "sda2", "path": "/dev/sda2", "size": "100G", "type": "part", "fstype": "ntfs"},
]
}
]
})
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout=lsblk_output)
result = get_block_devices()
assert len(result) == 1
assert result[0].name == "sda1"
def test_handles_lsblk_failure(self):
"""Should return empty list on lsblk failure."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=1, stdout="", stderr="error")
result = get_block_devices()
assert result == []
class TestGetUuid:
"""Tests for get_uuid function."""
def test_returns_uuid_from_blkid(self):
"""Should return UUID from blkid output."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="1234-5678-90ab\n")
result = get_uuid("/dev/sda1")
assert result == "1234-5678-90ab"
def test_returns_none_on_failure(self):
"""Should return None if blkid fails."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=1, stdout="")
result = get_uuid("/dev/sda1")
assert result is None
class TestValidateMountPoint:
"""Tests for validate_mount_point function."""
def test_accepts_media_path(self):
"""Should accept paths under /media."""
validate_mount_point("/media/wrolpi")
validate_mount_point("/media/usb")
validate_mount_point("/media/wrolpi/data")
def test_rejects_non_media_paths(self):
"""Should reject paths not under /media."""
with pytest.raises(ValueError, match="must be under /media"):
validate_mount_point("/mnt/data")
with pytest.raises(ValueError, match="must be under /media"):
validate_mount_point("/home/user")
with pytest.raises(ValueError, match="must be under /media"):
validate_mount_point("/")
def test_rejects_path_traversal(self):
"""Should reject path traversal attempts."""
with pytest.raises(ValueError):
validate_mount_point("/media/../etc")
class TestMountDrive:
"""Tests for mount_drive function."""
def test_returns_error_in_docker_mode(self):
"""Should return error in Docker mode."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=True):
result = mount_drive("/dev/sda1", "/media/test")
assert result["success"] is False
assert "Docker" in result["error"]
def test_validates_mount_point(self):
"""Should validate mount point."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
result = mount_drive("/dev/sda1", "/mnt/test")
assert result["success"] is False
assert "must be under /media" in result["error"]
def test_mounts_drive_successfully(self):
"""Should mount drive successfully."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("pathlib.Path.mkdir"):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="", stderr="")
result = mount_drive("/dev/sda1", "/media/test")
assert result["success"] is True
assert result["mount_point"] == "/media/test"
def test_handles_mount_failure(self):
"""Should handle mount failure."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("pathlib.Path.mkdir"):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=1, stdout="", stderr="mount failed")
result = mount_drive("/dev/sda1", "/media/test")
assert result["success"] is False
assert "mount failed" in result["error"]
class TestUnmountDrive:
"""Tests for unmount_drive function."""
def test_returns_error_in_docker_mode(self):
"""Should return error in Docker mode."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=True):
result = unmount_drive("/media/test")
assert result["success"] is False
assert "Docker" in result["error"]
def test_protects_primary_wrolpi_mount(self):
"""Should protect /media/wrolpi from accidental unmount."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("controller.lib.disks.get_config", return_value={"drives": {}}):
result = unmount_drive("/media/wrolpi")
assert result["success"] is False
assert "Cannot unmount /media/wrolpi" in result["error"]
def test_unmounts_successfully(self):
"""Should unmount successfully."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("controller.lib.disks.is_mount_busy", return_value=False):
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0)
result = unmount_drive("/media/test")
assert result["success"] is True
def test_checks_if_mount_busy(self):
"""Should check if mount is busy."""
with mock.patch("controller.lib.disks.is_docker_mode", return_value=False):
with mock.patch("controller.lib.disks.is_mount_busy", return_value=True):
result = unmount_drive("/media/test", lazy=False)
assert result["success"] is False
assert "busy" in result["error"]
class TestIsMountBusy:
"""Tests for is_mount_busy function."""
def test_returns_true_if_processes_using(self):
"""Should return True if processes are using mount."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="python /media/test/file.py")
result = is_mount_busy("/media/test")
# is_mount_busy returns truthy value (non-empty string) when busy
assert result
def test_returns_false_if_no_processes(self):
"""Should return False if no processes using mount."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=1, stdout="")
result = is_mount_busy("/media/test")
assert not result
class TestGetMounts:
"""Tests for get_mounts function."""
def test_returns_mounts_under_media(self):
"""Should return mounts under /media."""
findmnt_output = json.dumps({
"filesystems": [
{"target": "/", "source": "/dev/sda1", "fstype": "ext4", "options": "rw"},
{"target": "/media/wrolpi", "source": "/dev/sdb1", "fstype": "ext4", "options": "rw"},
{"target": "/media/usb", "source": "/dev/sdc1", "fstype": "vfat", "options": "rw"},
]
})
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout=findmnt_output)
result = get_mounts()
assert len(result) == 2
assert result[0]["mount_point"] == "/media/wrolpi"
assert result[1]["mount_point"] == "/media/usb"

View file

@ -0,0 +1,184 @@
"""
Integration tests for Controller disks API endpoints.
"""
from unittest import mock
class TestDisksListEndpoint:
"""Tests for /api/disks endpoint."""
def test_returns_501_in_docker_mode(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.get("/api/disks")
assert response.status_code == 501
def test_returns_list_in_native_mode(self, test_client):
"""Should return list of disks in native mode."""
with mock.patch("controller.api.disks.get_block_devices", return_value=[]):
response = test_client.get("/api/disks")
assert response.status_code == 200
assert isinstance(response.json(), list)
class TestMountsEndpoint:
"""Tests for /api/disks/mounts endpoint."""
def test_returns_501_in_docker_mode(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.get("/api/disks/mounts")
assert response.status_code == 501
def test_returns_mounts(self, test_client):
"""Should return current mounts."""
mock_mounts = [{"mount_point": "/media/wrolpi", "device": "/dev/sda1"}]
with mock.patch("controller.api.disks.get_mounts", return_value=mock_mounts):
response = test_client.get("/api/disks/mounts")
assert response.status_code == 200
assert response.json() == mock_mounts
class TestMountEndpoint:
"""Tests for /api/disks/mount endpoint."""
def test_returns_501_in_docker_mode(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.post(
"/api/disks/mount",
json={"device": "/dev/sda1", "mount_point": "/media/test"}
)
assert response.status_code == 501
def test_mounts_drive_successfully(self, test_client):
"""Should mount drive successfully."""
with mock.patch(
"controller.api.disks.mount_drive",
return_value={"success": True, "mount_point": "/media/test"}
):
response = test_client.post(
"/api/disks/mount",
json={"device": "/dev/sda1", "mount_point": "/media/test"}
)
assert response.status_code == 200
assert response.json()["success"] is True
def test_returns_500_on_failure(self, test_client):
"""Should return 500 on mount failure."""
with mock.patch(
"controller.api.disks.mount_drive",
return_value={"success": False, "error": "Mount failed"}
):
response = test_client.post(
"/api/disks/mount",
json={"device": "/dev/sda1", "mount_point": "/media/test"}
)
assert response.status_code == 500
class TestUnmountEndpoint:
"""Tests for /api/disks/unmount endpoint."""
def test_returns_501_in_docker_mode(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.post(
"/api/disks/unmount",
json={"mount_point": "/media/test"}
)
assert response.status_code == 501
def test_unmounts_drive_successfully(self, test_client):
"""Should unmount drive successfully."""
with mock.patch(
"controller.api.disks.unmount_drive",
return_value={"success": True, "mount_point": "/media/test"}
):
response = test_client.post(
"/api/disks/unmount",
json={"mount_point": "/media/test"}
)
assert response.status_code == 200
class TestFstabEndpoints:
"""Tests for /api/disks/fstab endpoints."""
def test_list_fstab_returns_501_in_docker(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.get("/api/disks/fstab")
assert response.status_code == 501
def test_list_fstab_returns_entries(self, test_client):
"""Should return fstab entries."""
mock_entries = [{"mount_point": "/media/wrolpi", "device": "UUID=1234"}]
with mock.patch("controller.api.disks.get_wrolpi_fstab_entries", return_value=mock_entries):
response = test_client.get("/api/disks/fstab")
assert response.status_code == 200
assert response.json() == mock_entries
def test_add_fstab_returns_501_in_docker(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.post(
"/api/disks/fstab",
json={"device": "/dev/sda1", "mount_point": "/media/test", "fstype": "ext4"}
)
assert response.status_code == 501
def test_add_fstab_entry(self, test_client):
"""Should add fstab entry."""
with mock.patch(
"controller.api.disks.add_fstab_entry",
return_value={"success": True, "mount_point": "/media/test"}
):
response = test_client.post(
"/api/disks/fstab",
json={"device": "/dev/sda1", "mount_point": "/media/test", "fstype": "ext4"}
)
assert response.status_code == 200
def test_delete_fstab_returns_501_in_docker(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.delete("/api/disks/fstab/media/test")
assert response.status_code == 501
class TestSmartEndpoints:
"""Tests for /api/disks/smart endpoints."""
def test_list_smart_returns_501_in_docker(self, test_client_docker_mode):
"""Should return 501 in Docker mode."""
response = test_client_docker_mode.get("/api/disks/smart")
assert response.status_code == 501
def test_list_smart_when_not_available(self, test_client):
"""Should return unavailable when SMART not available."""
with mock.patch("controller.api.disks.is_smart_available", return_value=False):
response = test_client.get("/api/disks/smart")
assert response.status_code == 200
data = response.json()
assert data["available"] is False
def test_list_smart_returns_drives(self, test_client):
"""Should return SMART data for all drives."""
mock_drives = [{"device": "sda", "assessment": "PASS"}]
with mock.patch("controller.api.disks.is_smart_available", return_value=True):
with mock.patch("controller.api.disks.get_all_smart_status", return_value=mock_drives):
response = test_client.get("/api/disks/smart")
assert response.status_code == 200
data = response.json()
assert data["available"] is True
assert len(data["drives"]) == 1
class TestOpenAPIIncludesDisksEndpoints:
"""Tests that OpenAPI documentation includes disks endpoints."""
def test_openapi_has_disks_paths(self, test_client):
"""OpenAPI schema should include disks paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/disks" in data["paths"]
assert "/api/disks/mounts" in data["paths"]
assert "/api/disks/mount" in data["paths"]
assert "/api/disks/unmount" in data["paths"]
assert "/api/disks/fstab" in data["paths"]
assert "/api/disks/smart" in data["paths"]

View file

@ -0,0 +1,297 @@
"""
Unit tests for controller.lib.docker_services module.
"""
from unittest import mock
import pytest
from controller.lib.docker_services import (
can_manage_containers,
get_container_status,
get_all_containers_status,
start_container,
stop_container,
restart_container,
get_container_logs,
_get_container_name,
CONTAINER_PREFIX,
)
class TestCanManageContainers:
"""Tests for can_manage_containers function."""
def test_returns_false_when_not_docker_mode(self):
"""Should return False when not in Docker mode."""
with mock.patch("controller.lib.docker_services.is_docker_mode", return_value=False):
assert can_manage_containers() is False
def test_returns_false_when_docker_not_available(self):
"""Should return False when docker library not available."""
with mock.patch("controller.lib.docker_services.is_docker_mode", return_value=True):
with mock.patch("controller.lib.docker_services.DOCKER_AVAILABLE", False):
assert can_manage_containers() is False
def test_returns_false_when_socket_missing(self):
"""Should return False when Docker socket doesn't exist."""
with mock.patch("controller.lib.docker_services.is_docker_mode", return_value=True):
with mock.patch("controller.lib.docker_services.DOCKER_AVAILABLE", True):
with mock.patch("os.path.exists", return_value=False):
assert can_manage_containers() is False
def test_returns_true_when_all_conditions_met(self):
"""Should return True when Docker mode, library, and socket available."""
with mock.patch("controller.lib.docker_services.is_docker_mode", return_value=True):
with mock.patch("controller.lib.docker_services.DOCKER_AVAILABLE", True):
with mock.patch("os.path.exists", return_value=True):
assert can_manage_containers() is True
class TestGetContainerName:
"""Tests for _get_container_name function."""
def test_formats_container_name(self):
"""Should format container name with prefix and suffix."""
result = _get_container_name("api")
assert result == f"{CONTAINER_PREFIX}-api-1"
def test_uses_service_name(self):
"""Should use service name in container name."""
result = _get_container_name("web")
assert "web" in result
class TestGetContainerStatus:
"""Tests for get_container_status function."""
def test_returns_unavailable_when_cannot_manage(self):
"""Should return unavailable when can't manage containers."""
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=False):
result = get_container_status("api")
assert result["status"] == "unknown"
assert result["available"] is False
def test_returns_running_status(self):
"""Should return running status for running container."""
mock_container = mock.Mock()
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"8080/tcp": [{"HostPort": "8081"}]}}}
mock_client = mock.Mock()
mock_client.containers.get.return_value = mock_container
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_container_status("api")
assert result["status"] == "running"
assert result["available"] is True
def test_returns_stopped_for_exited_container(self):
"""Should return stopped for exited container."""
mock_container = mock.Mock()
mock_container.status = "exited"
mock_container.attrs = {"NetworkSettings": {"Ports": {}}}
mock_client = mock.Mock()
mock_client.containers.get.return_value = mock_container
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_container_status("api")
assert result["status"] == "stopped"
class TestGetAllContainersStatus:
"""Tests for get_all_containers_status function."""
def test_returns_empty_when_cannot_manage(self):
"""Should return empty list when can't manage containers."""
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=False):
result = get_all_containers_status()
assert result == []
def test_returns_container_list(self):
"""Should return list of container statuses."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-api-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "api"
def test_db_container_not_viewable(self):
"""Database container should not be viewable (port 5432 is not HTTP)."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-db-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"5432/tcp": [{"HostPort": "5432"}]}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "db"
assert result[0]["viewable"] is False
def test_api_container_is_viewable(self):
"""API container should be viewable (HTTP service)."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-api-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"8081/tcp": [{"HostPort": "8081"}]}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "api"
assert result[0]["viewable"] is True
def test_https_container_uses_https(self):
"""Containers with _https suffix should have use_https=True."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-help_https-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"8086/tcp": [{"HostPort": "8086"}]}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "help_https"
assert result[0]["use_https"] is True
def test_non_https_container_uses_http(self):
"""Containers without _https suffix should have use_https=False."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-api-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"8081/tcp": [{"HostPort": "8081"}]}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "api"
assert result[0].get("use_https", False) is False
def test_web_container_uses_https(self):
"""Web container (nginx proxy) should have use_https=True."""
mock_container = mock.Mock()
mock_container.name = f"{CONTAINER_PREFIX}-web-1"
mock_container.status = "running"
mock_container.attrs = {"NetworkSettings": {"Ports": {"443/tcp": [{"HostPort": "8443"}]}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "web"
assert result[0]["use_https"] is True
def test_filters_by_prefix(self):
"""Should only return containers with correct prefix."""
mock_container1 = mock.Mock()
mock_container1.name = f"{CONTAINER_PREFIX}-api-1"
mock_container1.status = "running"
mock_container1.attrs = {"NetworkSettings": {"Ports": {}}}
mock_container2 = mock.Mock()
mock_container2.name = "other-container"
mock_container2.status = "running"
mock_container2.attrs = {"NetworkSettings": {"Ports": {}}}
mock_client = mock.Mock()
mock_client.containers.list.return_value = [mock_container1, mock_container2]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_all_containers_status()
assert len(result) == 1
assert result[0]["name"] == "api"
class TestContainerActions:
"""Tests for container action functions."""
@pytest.mark.parametrize("func", [
start_container,
stop_container,
restart_container,
])
def test_returns_error_when_cannot_manage(self, func):
"""Should return error when can't manage containers."""
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=False):
result = func("api")
assert result["success"] is False
@pytest.mark.parametrize("func,method_name,expected_action,call_kwargs", [
(start_container, "start", "start", {}),
(stop_container, "stop", "stop", {"timeout": 30}),
(restart_container, "restart", "restart", {"timeout": 30}),
])
def test_performs_container_action(self, func, method_name, expected_action, call_kwargs):
"""Should perform the correct container action."""
mock_container = mock.Mock()
mock_client = mock.Mock()
mock_client.containers.get.return_value = mock_container
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = func("api")
method = getattr(mock_container, method_name)
if call_kwargs:
method.assert_called_once_with(**call_kwargs)
else:
method.assert_called_once()
assert result["success"] is True
assert result["action"] == expected_action
class TestGetContainerLogs:
"""Tests for get_container_logs function."""
def test_returns_error_when_cannot_manage(self):
"""Should return error when can't manage containers."""
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=False):
result = get_container_logs("api")
assert "error" in result
def test_returns_logs(self):
"""Should return container logs."""
mock_container = mock.Mock()
mock_container.logs.return_value = b"log line 1\nlog line 2"
mock_client = mock.Mock()
mock_client.containers.get.return_value = mock_container
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True):
with mock.patch("controller.lib.docker_services._get_client", return_value=mock_client):
result = get_container_logs("api", lines=50)
mock_container.logs.assert_called_once_with(tail=50)
assert result["logs"] == "log line 1\nlog line 2"
assert result["service"] == "api"
assert result["lines"] == 50

View file

@ -0,0 +1,154 @@
"""
Unit tests for controller.lib.fstab module.
"""
from unittest import mock
from controller.lib.fstab import (
parse_fstab,
add_fstab_entry,
remove_fstab_entry,
get_wrolpi_fstab_entries,
)
class TestParseFstab:
"""Tests for parse_fstab function."""
def test_parses_mount_entries(self):
"""Should parse mount entries from fstab."""
fstab_content = """\
# /etc/fstab
UUID=1234-5678 / ext4 defaults 0 1
UUID=abcd-efgh /media/wrolpi ext4 defaults,nofail 0 2
"""
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = parse_fstab()
mounts = [e for e in result if e["type"] == "mount"]
assert len(mounts) == 2
assert mounts[0]["device"] == "UUID=1234-5678"
assert mounts[0]["mount_point"] == "/"
assert mounts[1]["mount_point"] == "/media/wrolpi"
def test_preserves_comments(self):
"""Should preserve comments and blank lines."""
fstab_content = """\
# This is a comment
UUID=1234 / ext4 defaults 0 1
"""
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = parse_fstab()
comments = [e for e in result if e["type"] == "comment"]
assert len(comments) == 2
def test_handles_minimal_entries(self):
"""Should handle entries with minimal fields."""
fstab_content = "UUID=1234 /media/data ext4 defaults\n"
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = parse_fstab()
mount = [e for e in result if e["type"] == "mount"][0]
assert mount["dump"] == "0"
assert mount["pass"] == "0"
class TestAddFstabEntry:
"""Tests for add_fstab_entry function."""
def test_blocked_in_wrol_mode(self):
"""Should be blocked in WROL mode."""
with mock.patch("controller.lib.fstab.require_normal_mode", side_effect=PermissionError("WROL")):
result = add_fstab_entry("/dev/sda1", "/media/test", "ext4")
assert result["success"] is False
assert "WROL" in result["error"]
def test_validates_mount_point(self):
"""Should validate mount point."""
with mock.patch("controller.lib.fstab.require_normal_mode"):
result = add_fstab_entry("/dev/sda1", "/mnt/test", "ext4")
assert result["success"] is False
assert "must be under /media" in result["error"]
def test_converts_device_to_uuid(self):
"""Should convert device path to UUID."""
fstab_content = "# empty\n"
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value="1234-5678"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
with mock.patch("subprocess.run"):
result = add_fstab_entry("/dev/sda1", "/media/test", "ext4")
assert result["success"] is True
assert result["device"] == "UUID=1234-5678"
def test_adds_entry_to_fstab(self):
"""Should add entry to fstab."""
fstab_content = "# existing\n"
written_content = []
def mock_write(content):
written_content.append(content)
mock_file = mock.mock_open(read_data=fstab_content)
mock_file().write = mock_write
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.get_uuid", return_value=None):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("builtins.open", mock_file):
with mock.patch("subprocess.run"):
result = add_fstab_entry("/dev/sda1", "/media/test", "ext4")
assert result["success"] is True
# Check that something was written
assert len(written_content) > 0
class TestRemoveFstabEntry:
"""Tests for remove_fstab_entry function."""
def test_blocked_in_wrol_mode(self):
"""Should be blocked in WROL mode."""
with mock.patch("controller.lib.fstab.require_normal_mode", side_effect=PermissionError("WROL")):
result = remove_fstab_entry("/media/test")
assert result["success"] is False
def test_validates_mount_point(self):
"""Should validate mount point."""
with mock.patch("controller.lib.fstab.require_normal_mode"):
result = remove_fstab_entry("/mnt/test")
assert result["success"] is False
def test_returns_error_if_not_found(self):
"""Should return error if entry not found."""
fstab_content = "UUID=1234 / ext4 defaults 0 1\n"
with mock.patch("controller.lib.fstab.require_normal_mode"):
with mock.patch("controller.lib.fstab.backup_fstab"):
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = remove_fstab_entry("/media/nonexistent")
assert result["success"] is False
assert "No entry found" in result["error"]
class TestGetWrolpiFstabEntries:
"""Tests for get_wrolpi_fstab_entries function."""
def test_returns_wrolpi_entries(self):
"""Should return entries for /media/wrolpi."""
fstab_content = """\
UUID=1234 / ext4 defaults 0 1
UUID=5678 /media/wrolpi ext4 defaults 0 2
UUID=9abc /media/wrolpi/data ext4 defaults 0 2
UUID=defg /media/usb vfat defaults 0 0
"""
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = get_wrolpi_fstab_entries()
assert len(result) == 2
assert result[0]["mount_point"] == "/media/wrolpi"
assert result[1]["mount_point"] == "/media/wrolpi/data"
def test_returns_empty_if_no_wrolpi_entries(self):
"""Should return empty list if no WROLPi entries."""
fstab_content = "UUID=1234 / ext4 defaults 0 1\n"
with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)):
result = get_wrolpi_fstab_entries()
assert result == []

View file

@ -0,0 +1,50 @@
"""
Unit tests for controller.api.schemas module.
"""
import pytest
from pydantic import ValidationError
from controller.api.schemas import HealthResponse
class TestHealthResponse:
"""Tests for HealthResponse model."""
def test_valid_health_response(self):
"""Should create valid health response."""
response = HealthResponse(
status="healthy",
version="1.0.0",
docker_mode=False,
drive_mounted=True,
)
assert response.status == "healthy"
assert response.version == "1.0.0"
assert response.docker_mode is False
assert response.drive_mounted is True
def test_health_response_serialization(self):
"""Should serialize to dict correctly."""
response = HealthResponse(
status="healthy",
version="1.0.0",
docker_mode=True,
drive_mounted=False,
)
data = response.model_dump()
assert data == {
"status": "healthy",
"version": "1.0.0",
"docker_mode": True,
"drive_mounted": False,
}
def test_health_response_missing_field(self):
"""Should raise validation error for missing required field."""
with pytest.raises(ValidationError):
HealthResponse(
status="healthy",
version="1.0.0",
# missing docker_mode and drive_mounted
)

View file

@ -0,0 +1,179 @@
"""
Integration tests for Controller services API endpoints.
"""
from unittest import mock
import pytest
class TestServicesListEndpoint:
"""Tests for /api/services endpoint."""
def test_services_list_returns_200(self, test_client):
"""Services list endpoint should return 200 OK."""
response = test_client.get("/api/services")
assert response.status_code == 200
def test_services_list_returns_list_or_error(self, test_client):
"""Services list should return list of services or error object."""
response = test_client.get("/api/services")
data = response.json()
# Should be a list (when docker can manage) or error dict
assert isinstance(data, (list, dict))
class TestServicesListDockerMode:
"""Tests for /api/services in Docker mode."""
def test_returns_containers_when_docker_available(self, test_client_docker_mode):
"""Should return container status when Docker is available."""
mock_containers = [
{"name": "api", "status": "running", "container_name": "wrolpi-api-1"}
]
with mock.patch(
"controller.lib.docker_services.can_manage_containers",
return_value=True
):
with mock.patch(
"controller.lib.docker_services.get_all_containers_status",
return_value=mock_containers
):
# Also patch in the main module
with mock.patch(
"controller.main.can_manage_containers",
return_value=True
):
with mock.patch(
"controller.main.get_all_containers_status",
return_value=mock_containers
):
with mock.patch(
"controller.api.services.can_manage_containers",
return_value=True
):
with mock.patch(
"controller.api.services.get_all_containers_status",
return_value=mock_containers
):
response = test_client_docker_mode.get("/api/services")
assert response.status_code == 200
class TestServiceStatusEndpoint:
"""Tests for /api/services/{name} endpoint."""
def test_service_status_returns_status(self, test_client):
"""Should return service status."""
with mock.patch(
"controller.api.services.get_service_status",
return_value={
"name": "wrolpi-api",
"status": "running",
"systemd_name": "wrolpi-api.service",
}
):
response = test_client.get("/api/services/wrolpi-api")
assert response.status_code == 200
data = response.json()
assert data["name"] == "wrolpi-api"
def test_unknown_service_returns_404(self, test_client):
"""Should return 404 for unknown service."""
with mock.patch(
"controller.api.services.get_service_status",
return_value={"error": "Unknown service: nonexistent"}
):
response = test_client.get("/api/services/nonexistent")
assert response.status_code == 404
class TestServiceActionEndpoints:
"""Tests for service action endpoints (start, stop, restart, enable, disable)."""
@pytest.mark.parametrize("action,endpoint,mock_func", [
("start", "/api/services/wrolpi-api/start", "start_service"),
("stop", "/api/services/wrolpi-api/stop", "stop_service"),
("restart", "/api/services/wrolpi-api/restart", "restart_service"),
("enable", "/api/services/wrolpi-api/enable", "enable_service"),
("disable", "/api/services/wrolpi-api/disable", "disable_service"),
])
def test_action_success(self, test_client, action, endpoint, mock_func):
"""Should perform service action successfully."""
with mock.patch(
f"controller.api.services.{mock_func}",
return_value={"success": True, "service": "wrolpi-api", "action": action}
):
response = test_client.post(endpoint)
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert data["action"] == action
def test_start_failure_returns_500(self, test_client):
"""Should return 500 on start failure."""
with mock.patch(
"controller.api.services.start_service",
return_value={"success": False, "error": "Failed to start"}
):
response = test_client.post("/api/services/wrolpi-api/start")
assert response.status_code == 500
@pytest.mark.parametrize("endpoint", [
"/api/services/wrolpi-api/enable",
"/api/services/wrolpi-api/disable",
])
def test_enable_disable_not_available_in_docker(self, test_client_docker_mode, endpoint):
"""Should return 501 in Docker mode for enable/disable."""
response = test_client_docker_mode.post(endpoint)
assert response.status_code == 501
class TestServiceLogsEndpoint:
"""Tests for /api/services/{name}/logs endpoint."""
def test_logs_returns_200(self, test_client):
"""Should return logs successfully."""
with mock.patch(
"controller.api.services.get_service_logs",
return_value={"service": "wrolpi-api", "lines": 100, "logs": "test logs"}
):
response = test_client.get("/api/services/wrolpi-api/logs")
assert response.status_code == 200
data = response.json()
assert "logs" in data
def test_logs_accepts_lines_parameter(self, test_client):
"""Should accept lines query parameter."""
with mock.patch(
"controller.api.services.get_service_logs",
return_value={"service": "wrolpi-api", "lines": 50, "logs": "logs"}
):
response = test_client.get("/api/services/wrolpi-api/logs?lines=50")
assert response.status_code == 200
def test_logs_accepts_since_parameter(self, test_client):
"""Should accept since query parameter."""
with mock.patch(
"controller.api.services.get_service_logs",
return_value={"service": "wrolpi-api", "lines": 100, "since": "1h", "logs": "logs"}
):
response = test_client.get("/api/services/wrolpi-api/logs?since=1h")
assert response.status_code == 200
class TestOpenAPIIncludesServicesEndpoints:
"""Tests that OpenAPI documentation includes services endpoints."""
def test_openapi_has_services_paths(self, test_client):
"""OpenAPI schema should include services paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/services" in data["paths"]
assert "/api/services/{name}" in data["paths"]
assert "/api/services/{name}/start" in data["paths"]
assert "/api/services/{name}/stop" in data["paths"]
assert "/api/services/{name}/restart" in data["paths"]
assert "/api/services/{name}/enable" in data["paths"]
assert "/api/services/{name}/disable" in data["paths"]
assert "/api/services/{name}/logs" in data["paths"]

View file

@ -0,0 +1,169 @@
"""
Unit tests for controller.lib.smart module.
"""
from unittest import mock
from controller.lib.smart import (
is_smart_available,
get_all_smart_status,
_get_device_smart,
_get_temperature,
_get_attribute,
)
class TestIsSmartAvailable:
"""Tests for is_smart_available function."""
def test_returns_false_in_docker_mode(self):
"""Should return False in Docker mode."""
with mock.patch("controller.lib.smart.is_docker_mode", return_value=True):
assert is_smart_available() is False
def test_returns_false_when_pysmart_not_installed(self):
"""Should return False when pySMART not installed."""
with mock.patch("controller.lib.smart.is_docker_mode", return_value=False):
with mock.patch("controller.lib.smart.SMART_AVAILABLE", False):
assert is_smart_available() is False
def test_returns_true_when_available(self):
"""Should return True when pySMART available and not Docker."""
with mock.patch("controller.lib.smart.is_docker_mode", return_value=False):
with mock.patch("controller.lib.smart.SMART_AVAILABLE", True):
assert is_smart_available() is True
class TestGetAllSmartStatus:
"""Tests for get_all_smart_status function."""
def test_returns_empty_when_not_available(self):
"""Should return empty list when SMART not available."""
with mock.patch("controller.lib.smart.is_smart_available", return_value=False):
result = get_all_smart_status()
assert result == []
def test_returns_device_list(self):
"""Should return list of device statuses."""
mock_device = mock.Mock()
mock_device.name = "sda"
mock_device.model = "Samsung SSD"
mock_device.serial = "S1234"
mock_device.capacity = "500 GB"
mock_device.assessment = "PASS"
mock_device.smart_enabled = True
mock_device.attributes = []
mock_device_list = mock.Mock()
mock_device_list.devices = [mock_device]
with mock.patch("controller.lib.smart.is_smart_available", return_value=True):
with mock.patch("controller.lib.smart.DeviceList", return_value=mock_device_list):
result = get_all_smart_status()
assert len(result) == 1
assert result[0]["device"] == "sda"
assert result[0]["model"] == "Samsung SSD"
class TestGetDeviceSmart:
"""Tests for _get_device_smart function."""
def test_extracts_device_info(self):
"""Should extract device information."""
mock_device = mock.Mock()
mock_device.name = "sda"
mock_device.model = "Samsung SSD"
mock_device.serial = "S1234"
mock_device.capacity = "500 GB"
mock_device.assessment = "PASS"
mock_device.smart_enabled = True
mock_device.attributes = []
result = _get_device_smart(mock_device)
assert result["device"] == "sda"
assert result["path"] == "/dev/sda"
assert result["model"] == "Samsung SSD"
assert result["serial"] == "S1234"
assert result["capacity"] == "500 GB"
assert result["assessment"] == "PASS"
assert result["smart_enabled"] is True
class TestGetTemperature:
"""Tests for _get_temperature function."""
def test_returns_temperature_celsius(self):
"""Should return temperature from Temperature_Celsius attribute."""
mock_attr = mock.Mock()
mock_attr.name = "Temperature_Celsius"
mock_attr.raw = "35"
mock_device = mock.Mock()
mock_device.attributes = [mock_attr]
result = _get_temperature(mock_device)
assert result == 35
def test_falls_back_to_airflow_temperature(self):
"""Should fall back to Airflow_Temperature_Cel."""
mock_attr = mock.Mock()
mock_attr.name = "Airflow_Temperature_Cel"
mock_attr.raw = "40"
mock_device = mock.Mock()
mock_device.attributes = [mock_attr]
result = _get_temperature(mock_device)
assert result == 40
def test_returns_none_if_not_found(self):
"""Should return None if no temperature attribute."""
mock_device = mock.Mock()
mock_device.attributes = []
result = _get_temperature(mock_device)
assert result is None
class TestGetAttribute:
"""Tests for _get_attribute function."""
def test_returns_attribute_value(self):
"""Should return attribute raw value."""
mock_attr = mock.Mock()
mock_attr.name = "Power_On_Hours"
mock_attr.raw = "12345"
mock_device = mock.Mock()
mock_device.attributes = [mock_attr]
result = _get_attribute(mock_device, "Power_On_Hours")
assert result == 12345
def test_returns_none_for_missing_attribute(self):
"""Should return None if attribute not found."""
mock_device = mock.Mock()
mock_device.attributes = []
result = _get_attribute(mock_device, "Nonexistent")
assert result is None
def test_returns_none_if_no_attributes(self):
"""Should return None if device has no attributes."""
mock_device = mock.Mock()
mock_device.attributes = None
result = _get_attribute(mock_device, "Power_On_Hours")
assert result is None
def test_handles_invalid_raw_value(self):
"""Should handle non-numeric raw values."""
mock_attr = mock.Mock()
mock_attr.name = "Power_On_Hours"
mock_attr.raw = "invalid"
mock_device = mock.Mock()
mock_device.attributes = [mock_attr]
result = _get_attribute(mock_device, "Power_On_Hours")
assert result is None

View file

@ -0,0 +1,209 @@
"""
Unit tests for controller.lib.status module.
The status module now returns formats compatible with the main WROLPi API
so the React app can seamlessly use either source.
"""
from unittest import mock
from controller.lib.status import (
get_cpu_status,
get_drive_status,
get_load_status,
get_memory_status,
get_network_status,
get_power_status,
get_primary_drive_status,
)
class TestGetCpuStatus:
"""Tests for get_cpu_status function."""
def test_returns_dict(self):
"""Should return a dictionary."""
result = get_cpu_status()
assert isinstance(result, dict)
def test_has_required_keys(self):
"""Should have all required keys (main API format)."""
result = get_cpu_status()
assert "percent" in result
assert "cores" in result
assert "cur_frequency" in result
assert "max_frequency" in result
assert "min_frequency" in result
assert "temperature" in result
assert "high_temperature" in result
assert "critical_temperature" in result
def test_percent_is_numeric(self):
"""CPU percent should be a number."""
result = get_cpu_status()
assert isinstance(result["percent"], (int, float))
assert 0 <= result["percent"] <= 100
def test_cores_is_positive(self):
"""Core count should be a positive integer."""
result = get_cpu_status()
assert isinstance(result["cores"], int)
assert result["cores"] > 0
class TestGetMemoryStatus:
"""Tests for get_memory_status function."""
def test_returns_dict(self):
"""Should return a dictionary."""
result = get_memory_status()
assert isinstance(result, dict)
def test_has_required_keys(self):
"""Should have all required keys (main API format)."""
result = get_memory_status()
assert "total" in result
assert "used" in result
assert "free" in result
assert "cached" in result
def test_total_is_positive(self):
"""Memory total should be positive."""
result = get_memory_status()
assert result["total"] > 0
def test_bytes_are_non_negative(self):
"""Memory bytes should be non-negative."""
result = get_memory_status()
assert result["used"] >= 0
assert result["free"] >= 0
assert result["cached"] >= 0
class TestGetLoadStatus:
"""Tests for get_load_status function."""
def test_returns_dict(self):
"""Should return a dictionary."""
result = get_load_status()
assert isinstance(result, dict)
def test_has_required_keys(self):
"""Should have all required keys (main API format)."""
result = get_load_status()
assert "minute_1" in result
assert "minute_5" in result
assert "minute_15" in result
def test_values_are_strings(self):
"""Load values should be string representations of numbers (main API format)."""
result = get_load_status()
# Values are strings in the main API format
assert isinstance(result["minute_1"], str)
assert isinstance(result["minute_5"], str)
assert isinstance(result["minute_15"], str)
# But they should be parseable as floats
assert float(result["minute_1"]) >= 0
assert float(result["minute_5"]) >= 0
assert float(result["minute_15"]) >= 0
class TestGetDriveStatus:
"""Tests for get_drive_status function."""
def test_returns_list(self):
"""Should return a list."""
result = get_drive_status()
assert isinstance(result, list)
def test_returns_drives_or_empty(self):
"""Should return drives list (may be empty in Docker containers)."""
result = get_drive_status()
# The result should be a valid list
# May be empty in Docker containers where root fs is not visible
assert isinstance(result, list)
def test_drive_has_required_keys(self):
"""Each drive should have all required keys (main API format)."""
result = get_drive_status()
if result: # Only test if we have drives
drive = result[0]
assert "mount" in drive
assert "percent" in drive
assert "size" in drive
assert "used" in drive
class TestGetPrimaryDriveStatus:
"""Tests for get_primary_drive_status function."""
def test_returns_none_when_not_mounted(self):
"""Should return None when /media/wrolpi is not mounted."""
# In most test environments, /media/wrolpi won't be mounted
result = get_primary_drive_status()
# This could be None or a dict depending on the environment
assert result is None or isinstance(result, dict)
def test_returns_dict_when_mounted(self):
"""Should return drive info when /media/wrolpi is mounted."""
# Mock the get_drive_status to return a drive at /media/wrolpi
mock_drives = [
{
"mount": "/media/wrolpi",
"percent": 50,
"size": 1000000000,
"used": 500000000,
}
]
with mock.patch(
"controller.lib.status.get_drive_status", return_value=mock_drives
):
result = get_primary_drive_status()
assert result is not None
assert result["mount"] == "/media/wrolpi"
class TestGetNetworkStatus:
"""Tests for get_network_status function."""
def test_returns_dict(self):
"""Should return a dict (main API format: dict of interface name -> stats)."""
result = get_network_status()
assert isinstance(result, dict)
def test_excludes_loopback(self):
"""Should not include the loopback interface."""
result = get_network_status()
assert "lo" not in result
def test_interface_has_required_keys(self):
"""Each interface should have required keys (main API format)."""
result = get_network_status()
if result: # Only test if we have interfaces
iface = list(result.values())[0]
assert "name" in iface
assert "bytes_sent" in iface
assert "bytes_recv" in iface
assert "speed" in iface
assert "now" in iface
class TestGetPowerStatus:
"""Tests for get_power_status function."""
def test_returns_dict(self):
"""Should return a dictionary."""
result = get_power_status()
assert isinstance(result, dict)
def test_has_required_keys(self):
"""Should have all required keys (main API format)."""
result = get_power_status()
assert "under_voltage" in result
assert "over_current" in result
def test_values_are_bool(self):
"""All values should be boolean."""
result = get_power_status()
assert isinstance(result["under_voltage"], bool)
assert isinstance(result["over_current"], bool)

View file

@ -0,0 +1,191 @@
"""
Integration tests for Controller stats API endpoints.
The stats endpoints return system statistics (CPU, memory, etc).
Note: These are separate from the main WROLPi API's /api/status endpoint.
"""
class TestCpuEndpoint:
"""Tests for /api/stats/cpu endpoint."""
def test_cpu_returns_200(self, test_client):
"""CPU endpoint should return 200 OK."""
response = test_client.get("/api/stats/cpu")
assert response.status_code == 200
def test_cpu_returns_expected_fields(self, test_client):
"""CPU endpoint should return expected fields (main API format)."""
response = test_client.get("/api/stats/cpu")
data = response.json()
assert "percent" in data
assert "cores" in data
assert "cur_frequency" in data
assert "max_frequency" in data
assert "min_frequency" in data
assert "temperature" in data
assert "high_temperature" in data
assert "critical_temperature" in data
def test_cpu_percent_valid_range(self, test_client):
"""CPU percent should be between 0 and 100."""
response = test_client.get("/api/stats/cpu")
data = response.json()
assert 0 <= data["percent"] <= 100
class TestMemoryEndpoint:
"""Tests for /api/stats/memory endpoint."""
def test_memory_returns_200(self, test_client):
"""Memory endpoint should return 200 OK."""
response = test_client.get("/api/stats/memory")
assert response.status_code == 200
def test_memory_returns_expected_fields(self, test_client):
"""Memory endpoint should return expected fields (main API format)."""
response = test_client.get("/api/stats/memory")
data = response.json()
assert "total" in data
assert "used" in data
assert "free" in data
assert "cached" in data
def test_memory_bytes_positive(self, test_client):
"""Memory total should be positive."""
response = test_client.get("/api/stats/memory")
data = response.json()
assert data["total"] > 0
class TestLoadEndpoint:
"""Tests for /api/stats/load endpoint."""
def test_load_returns_200(self, test_client):
"""Load endpoint should return 200 OK."""
response = test_client.get("/api/stats/load")
assert response.status_code == 200
def test_load_returns_expected_fields(self, test_client):
"""Load endpoint should return expected fields (main API format)."""
response = test_client.get("/api/stats/load")
data = response.json()
assert "minute_1" in data
assert "minute_5" in data
assert "minute_15" in data
def test_load_values_non_negative(self, test_client):
"""Load values should be non-negative."""
response = test_client.get("/api/stats/load")
data = response.json()
# Values are strings in main API format
assert float(data["minute_1"]) >= 0
assert float(data["minute_5"]) >= 0
assert float(data["minute_15"]) >= 0
class TestPrimaryDriveEndpoint:
"""Tests for /api/stats/drives/primary endpoint."""
def test_primary_drive_returns_200(self, test_client):
"""Primary drive endpoint should return 200 OK."""
response = test_client.get("/api/stats/drives/primary")
assert response.status_code == 200
def test_primary_drive_returns_mounted_false_when_not_mounted(self, test_client):
"""Primary drive should return mounted=false when not present."""
response = test_client.get("/api/stats/drives/primary")
data = response.json()
# In test environment, /media/wrolpi likely not mounted
assert "mounted" in data
class TestNetworkEndpoint:
"""Tests for /api/stats/network endpoint."""
def test_network_returns_200(self, test_client):
"""Network endpoint should return 200 OK."""
response = test_client.get("/api/stats/network")
assert response.status_code == 200
def test_network_returns_dict(self, test_client):
"""Network endpoint should return a dict (main API format)."""
response = test_client.get("/api/stats/network")
data = response.json()
assert isinstance(data, dict)
def test_network_excludes_loopback(self, test_client):
"""Network should not include loopback interface."""
response = test_client.get("/api/stats/network")
data = response.json()
assert "lo" not in data
class TestPowerEndpoint:
"""Tests for /api/stats/power endpoint."""
def test_power_returns_200(self, test_client):
"""Power endpoint should return 200 OK."""
response = test_client.get("/api/stats/power")
assert response.status_code == 200
def test_power_returns_expected_fields(self, test_client):
"""Power endpoint should return expected fields (main API format)."""
response = test_client.get("/api/stats/power")
data = response.json()
assert "under_voltage" in data
assert "over_current" in data
def test_power_values_are_bool(self, test_client):
"""Power values should be booleans."""
response = test_client.get("/api/stats/power")
data = response.json()
assert isinstance(data["under_voltage"], bool)
assert isinstance(data["over_current"], bool)
class TestDashboardWithRealData:
"""Tests for dashboard rendering with real status data."""
def test_dashboard_shows_cpu_percent(self, test_client):
"""Dashboard should show CPU percentage (not placeholder)."""
response = test_client.get("/")
content = response.text
# CPU value should be a number, not "--"
# The template shows: {{ cpu.percent|default('--') }}%
# We verify the page loads and contains CPU section
assert "CPU" in content
# The dashboard should have some numeric value, not all placeholders
def test_dashboard_shows_memory_data(self, test_client):
"""Dashboard should show memory data."""
response = test_client.get("/")
content = response.text
assert "Memory" in content
def test_dashboard_shows_load_data(self, test_client):
"""Dashboard should show load data."""
response = test_client.get("/")
content = response.text
assert "Load" in content
def test_dashboard_shows_storage_data(self, test_client):
"""Dashboard should show storage data."""
response = test_client.get("/")
content = response.text
assert "Storage" in content
class TestOpenAPIIncludesStatsEndpoints:
"""Tests that OpenAPI documentation includes stats endpoints."""
def test_openapi_has_stats_paths(self, test_client):
"""OpenAPI schema should include stats paths."""
response = test_client.get("/openapi.json")
data = response.json()
assert "/api/stats/cpu" in data["paths"]
assert "/api/stats/memory" in data["paths"]
assert "/api/stats/load" in data["paths"]
assert "/api/stats/drives/primary" in data["paths"]
assert "/api/stats/network" in data["paths"]
assert "/api/stats/power" in data["paths"]

View file

@ -0,0 +1,248 @@
"""
Tests for the status worker background task and aggregated stats endpoint.
"""
from datetime import datetime
from unittest import mock
import pytest
class TestCollectAllStatus:
"""Tests for collect_all_status function."""
@pytest.mark.asyncio
async def test_collects_all_stats(self):
"""Should collect all status types."""
from controller.lib.status_worker import collect_all_status
status = await collect_all_status()
assert "cpu_stats" in status
assert "memory_stats" in status
assert "load_stats" in status
assert "drives_stats" in status
assert "nic_bandwidth_stats" in status
assert "power_stats" in status
assert "last_status" in status
@pytest.mark.asyncio
async def test_last_status_is_iso_timestamp(self):
"""Should include a valid ISO timestamp."""
from controller.lib.status_worker import collect_all_status
status = await collect_all_status()
# Should be parseable as ISO datetime
datetime.fromisoformat(status["last_status"])
@pytest.mark.asyncio
async def test_handles_cpu_failure(self):
"""Should handle failures in CPU stat collector."""
from controller.lib.status_worker import collect_all_status
with mock.patch(
"controller.lib.status_worker.get_cpu_status",
side_effect=Exception("CPU error")
):
status = await collect_all_status()
# CPU should be None but others should work
assert status["cpu_stats"] is None
assert status["memory_stats"] is not None
@pytest.mark.asyncio
async def test_handles_memory_failure(self):
"""Should handle failures in memory stat collector."""
from controller.lib.status_worker import collect_all_status
with mock.patch(
"controller.lib.status_worker.get_memory_status",
side_effect=Exception("Memory error")
):
status = await collect_all_status()
assert status["memory_stats"] is None
assert status["cpu_stats"] is not None
@pytest.mark.asyncio
async def test_drives_stats_is_list_on_failure(self):
"""Should return empty list for drives on failure."""
from controller.lib.status_worker import collect_all_status
with mock.patch(
"controller.lib.status_worker.get_drive_status",
side_effect=Exception("Drive error")
):
status = await collect_all_status()
assert status["drives_stats"] == []
@pytest.mark.asyncio
async def test_nic_stats_is_dict_on_failure(self):
"""Should return empty dict for network on failure."""
from controller.lib.status_worker import collect_all_status
with mock.patch(
"controller.lib.status_worker.get_network_status",
side_effect=Exception("Network error")
):
status = await collect_all_status()
assert status["nic_bandwidth_stats"] == {}
class TestGetAdaptiveSleep:
"""Tests for adaptive sleep calculation."""
def test_returns_base_sleep_when_load_is_low(self):
"""Should return base sleep when load is below CPU count."""
from controller.lib.status_worker import get_adaptive_sleep
with mock.patch("multiprocessing.cpu_count", return_value=4):
load_stats = {"minute_1": "0.5"}
sleep = get_adaptive_sleep(load_stats, base_sleep=5.0)
assert sleep == 5.0
def test_returns_base_sleep_when_load_equals_cpu_count(self):
"""Should return base sleep when load equals CPU count."""
from controller.lib.status_worker import get_adaptive_sleep
with mock.patch("multiprocessing.cpu_count", return_value=4):
load_stats = {"minute_1": "4.0"}
sleep = get_adaptive_sleep(load_stats, base_sleep=5.0)
assert sleep == 5.0
def test_increases_sleep_when_load_exceeds_cpu_count(self):
"""Should increase sleep when load exceeds CPU count."""
from controller.lib.status_worker import get_adaptive_sleep
with mock.patch("multiprocessing.cpu_count", return_value=4):
load_stats = {"minute_1": "8.0"} # 2x CPU count
sleep = get_adaptive_sleep(load_stats, base_sleep=5.0)
# Expected: (5.0 * 8.0) / 4 = 10.0
assert sleep == 10.0
def test_handles_none_load_stats(self):
"""Should return base sleep when load_stats is None."""
from controller.lib.status_worker import get_adaptive_sleep
sleep = get_adaptive_sleep(None, base_sleep=5.0)
assert sleep == 5.0
def test_handles_empty_load_stats(self):
"""Should return base sleep when load_stats is empty dict."""
from controller.lib.status_worker import get_adaptive_sleep
sleep = get_adaptive_sleep({}, base_sleep=5.0)
assert sleep == 5.0
def test_handles_invalid_load_value(self):
"""Should return base sleep when load value is invalid."""
from controller.lib.status_worker import get_adaptive_sleep
load_stats = {"minute_1": "invalid"}
sleep = get_adaptive_sleep(load_stats, base_sleep=5.0)
assert sleep == 5.0
def test_handles_missing_minute_1_key(self):
"""Should return base sleep when minute_1 key is missing."""
from controller.lib.status_worker import get_adaptive_sleep
load_stats = {"minute_5": "2.0"}
sleep = get_adaptive_sleep(load_stats, base_sleep=5.0)
assert sleep == 5.0
class TestAggregatedStatsEndpoint:
"""Tests for the new /api/stats aggregated endpoint."""
def test_aggregated_stats_returns_200(self, test_client):
"""Aggregated stats endpoint should return 200 OK."""
response = test_client.get("/api/stats")
assert response.status_code == 200
def test_aggregated_stats_returns_all_fields(self, test_client):
"""Aggregated stats should include all status types."""
response = test_client.get("/api/stats")
data = response.json()
assert "cpu_stats" in data
assert "memory_stats" in data
assert "load_stats" in data
assert "drives_stats" in data
assert "nic_bandwidth_stats" in data
assert "power_stats" in data
assert "last_status" in data
def test_aggregated_stats_has_valid_timestamp(self, test_client):
"""Should include a timestamp of when data was collected."""
response = test_client.get("/api/stats")
data = response.json()
assert "last_status" in data
# Should be ISO format timestamp
datetime.fromisoformat(data["last_status"])
def test_aggregated_stats_cpu_has_expected_fields(self, test_client):
"""CPU stats should have expected fields."""
response = test_client.get("/api/stats")
data = response.json()
cpu = data["cpu_stats"]
assert cpu is not None
assert "percent" in cpu
assert "cores" in cpu
def test_aggregated_stats_memory_has_expected_fields(self, test_client):
"""Memory stats should have expected fields."""
response = test_client.get("/api/stats")
data = response.json()
memory = data["memory_stats"]
assert memory is not None
assert "total" in memory
assert "used" in memory
assert "free" in memory
def test_aggregated_stats_load_has_expected_fields(self, test_client):
"""Load stats should have expected fields."""
response = test_client.get("/api/stats")
data = response.json()
load = data["load_stats"]
assert load is not None
assert "minute_1" in load
assert "minute_5" in load
assert "minute_15" in load
def test_aggregated_stats_drives_is_list(self, test_client):
"""Drives stats should be a list."""
response = test_client.get("/api/stats")
data = response.json()
assert isinstance(data["drives_stats"], list)
def test_aggregated_stats_network_is_dict(self, test_client):
"""Network stats should be a dict."""
response = test_client.get("/api/stats")
data = response.json()
assert isinstance(data["nic_bandwidth_stats"], dict)
def test_aggregated_stats_trailing_slash(self, test_client):
"""Aggregated stats should work with trailing slash."""
response = test_client.get("/api/stats/")
assert response.status_code == 200
class TestOpenAPIIncludesAggregatedStats:
"""Test that OpenAPI includes the new aggregated endpoint."""
def test_openapi_has_aggregated_stats_path(self, test_client):
"""OpenAPI schema should include /api/stats path."""
response = test_client.get("/openapi.json")
data = response.json()
# Check for either with or without trailing slash
has_path = "/api/stats" in data["paths"] or "/api/stats/" in data["paths"]
assert has_path, f"Expected /api/stats in paths, got: {list(data['paths'].keys())}"

View file

@ -0,0 +1,248 @@
"""
Unit tests for controller.lib.systemd module.
"""
from unittest import mock
import pytest
from controller.lib.systemd import (
get_managed_services,
get_service_config,
get_service_status,
get_all_services_status,
start_service,
stop_service,
restart_service,
enable_service,
disable_service,
get_service_logs,
_run_systemctl,
)
class TestGetManagedServices:
"""Tests for get_managed_services function."""
def test_returns_list(self):
"""Should return a list."""
result = get_managed_services()
assert isinstance(result, list)
def test_returns_services_from_config(self):
"""Should return services from config."""
result = get_managed_services()
# Default config has managed_services
assert len(result) > 0
def test_each_service_has_name(self):
"""Each service should have a name."""
result = get_managed_services()
for service in result:
assert "name" in service
class TestGetServiceConfig:
"""Tests for get_service_config function."""
def test_returns_config_for_known_service(self):
"""Should return config for a known service."""
# wrolpi-api is in default config
result = get_service_config("wrolpi-api")
assert result is not None
assert result["name"] == "wrolpi-api"
def test_returns_none_for_unknown_service(self):
"""Should return None for unknown service."""
result = get_service_config("nonexistent-service")
assert result is None
class TestRunSystemctl:
"""Tests for _run_systemctl function."""
def test_returns_dict(self):
"""Should return a dictionary."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = _run_systemctl("is-active", "test.service")
assert isinstance(result, dict)
def test_success_on_zero_returncode(self):
"""Should return success=True when returncode is 0."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="done", stderr="")
result = _run_systemctl("start", "test.service")
assert result["success"] is True
def test_failure_on_nonzero_returncode(self):
"""Should return success=False when returncode is non-zero."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=1, stdout="", stderr="failed")
result = _run_systemctl("start", "test.service")
assert result["success"] is False
assert result["error"] == "failed"
def test_handles_timeout(self):
"""Should handle subprocess timeout."""
import subprocess
with mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("systemctl", 30)):
result = _run_systemctl("start", "test.service")
assert result["success"] is False
assert "timed out" in result["error"].lower()
def test_handles_file_not_found(self):
"""Should handle systemctl not found."""
with mock.patch("subprocess.run", side_effect=FileNotFoundError()):
result = _run_systemctl("start", "test.service")
assert result["success"] is False
assert "not found" in result["error"].lower()
class TestGetServiceStatus:
"""Tests for get_service_status function."""
def test_returns_error_for_unknown_service(self):
"""Should return error for unknown service."""
result = get_service_status("nonexistent-service")
assert "error" in result
def test_returns_status_dict(self):
"""Should return a status dictionary."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = get_service_status("wrolpi-api")
assert "name" in result
assert "status" in result
@pytest.mark.parametrize("systemd_state,expected_status", [
("active", "running"),
("activating", "running"), # oneshot services during execution
("inactive", "stopped"),
("failed", "failed"),
])
def test_maps_systemd_state_to_status(self, systemd_state, expected_status):
"""Should map systemd states to simple status values."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout=systemd_state, stderr="")
result = get_service_status("wrolpi-api")
assert result["status"] == expected_status
@pytest.mark.parametrize("service_name,expected_https", [
("wrolpi-help", True),
("wrolpi-kiwix", True),
("apache2", True),
("wrolpi-api", False),
])
def test_returns_use_https_field(self, service_name, expected_https):
"""Should return use_https field from service config."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = get_service_status(service_name)
assert result.get("use_https", False) == expected_https
class TestGetAllServicesStatus:
"""Tests for get_all_services_status function."""
def test_returns_list(self):
"""Should return a list."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = get_all_services_status()
assert isinstance(result, list)
def test_returns_status_for_each_visible_service(self):
"""Should return status for each visible managed service."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = get_all_services_status()
managed = get_managed_services()
# All services should be returned when they're all "running" (active)
assert len(result) == len(managed)
def test_filters_show_only_when_running_services_when_stopped(self):
"""Should exclude show_only_when_running services when they're not running."""
with mock.patch("subprocess.run") as mock_run:
# Simulate all services as "inactive" (stopped)
mock_run.return_value = mock.Mock(returncode=0, stdout="inactive", stderr="")
result = get_all_services_status()
managed = get_managed_services()
# Count services without show_only_when_running flag
always_visible = [s for s in managed if not s.get("show_only_when_running")]
assert len(result) == len(always_visible)
def test_includes_show_only_when_running_services_when_running(self):
"""Should include show_only_when_running services when they're running."""
with mock.patch("subprocess.run") as mock_run:
# Simulate all services as "active" (running)
mock_run.return_value = mock.Mock(returncode=0, stdout="active", stderr="")
result = get_all_services_status()
managed = get_managed_services()
# All services should be visible when running
assert len(result) == len(managed)
# Verify wrolpi-upgrade is in the result
service_names = [s["name"] for s in result]
assert "wrolpi-upgrade" in service_names
class TestServiceActions:
"""Tests for service action functions (start, stop, restart, enable, disable)."""
@pytest.mark.parametrize("func", [
start_service,
stop_service,
restart_service,
enable_service,
disable_service,
])
def test_returns_error_for_unknown_service(self, func):
"""Should return error for unknown service."""
result = func("nonexistent-service")
assert result["success"] is False
@pytest.mark.parametrize("func,expected_action", [
(start_service, "start"),
(stop_service, "stop"),
(restart_service, "restart"),
(enable_service, "enable"),
(disable_service, "disable"),
])
def test_calls_correct_systemctl_action(self, func, expected_action):
"""Should call systemctl with correct action."""
with mock.patch("controller.lib.systemd._run_systemctl") as mock_ctl:
mock_ctl.return_value = {"success": True, "output": "", "error": None}
result = func("wrolpi-api")
mock_ctl.assert_called_once()
assert mock_ctl.call_args[0][0] == expected_action
assert result["success"] is True
assert result["action"] == expected_action
class TestGetServiceLogs:
"""Tests for get_service_logs function."""
def test_returns_error_for_unknown_service(self):
"""Should return error for unknown service."""
result = get_service_logs("nonexistent-service")
assert "error" in result
def test_returns_logs(self):
"""Should return logs."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="log line 1\nlog line 2", stderr="")
result = get_service_logs("wrolpi-api", lines=10)
assert "logs" in result
assert result["service"] == "wrolpi-api"
assert result["lines"] == 10
def test_handles_since_parameter(self):
"""Should include since parameter in journalctl command."""
with mock.patch("subprocess.run") as mock_run:
mock_run.return_value = mock.Mock(returncode=0, stdout="logs", stderr="")
result = get_service_logs("wrolpi-api", lines=50, since="1h")
assert result["since"] == "1h"
# Verify journalctl was called with --since
call_args = mock_run.call_args[0][0]
assert "--since" in call_args
assert "1h" in call_args

View file

@ -0,0 +1,83 @@
"""
Unit tests for controller.lib.wrol_mode module.
"""
from unittest import mock
import pytest
from controller.lib.wrol_mode import (
get_wrol_mode_flag_path,
is_wrol_mode,
require_normal_mode,
)
class TestGetWrolModeFlagPath:
"""Tests for get_wrol_mode_flag_path function."""
def test_returns_path(self):
"""Should return a Path object."""
from pathlib import Path
result = get_wrol_mode_flag_path()
assert isinstance(result, Path)
def test_path_ends_with_wrol_mode(self):
"""Path should end with .wrol_mode."""
result = get_wrol_mode_flag_path()
assert result.name == ".wrol_mode"
def test_path_is_in_config_directory(self):
"""Path should be in config directory."""
result = get_wrol_mode_flag_path()
assert result.parent.name == "config"
class TestIsWrolMode:
"""Tests for is_wrol_mode function."""
def test_returns_false_when_file_does_not_exist(self, tmp_path):
"""Should return False when flag file doesn't exist."""
with mock.patch(
"controller.lib.wrol_mode.get_wrol_mode_flag_path",
return_value=tmp_path / ".wrol_mode"
):
assert is_wrol_mode() is False
def test_returns_true_when_file_exists(self, tmp_path):
"""Should return True when flag file exists."""
flag_file = tmp_path / ".wrol_mode"
flag_file.touch()
with mock.patch(
"controller.lib.wrol_mode.get_wrol_mode_flag_path",
return_value=flag_file
):
assert is_wrol_mode() is True
class TestRequireNormalMode:
"""Tests for require_normal_mode function."""
def test_does_not_raise_when_not_in_wrol_mode(self):
"""Should not raise when WROL mode is inactive."""
with mock.patch("controller.lib.wrol_mode.is_wrol_mode", return_value=False):
# Should not raise
require_normal_mode("test operation")
def test_raises_permission_error_when_in_wrol_mode(self):
"""Should raise PermissionError when WROL mode is active."""
with mock.patch("controller.lib.wrol_mode.is_wrol_mode", return_value=True):
with pytest.raises(PermissionError) as exc_info:
require_normal_mode("save configuration")
assert "save configuration" in str(exc_info.value)
assert "WROL Mode" in str(exc_info.value)
def test_error_message_includes_operation_name(self):
"""Error message should include the operation name."""
with mock.patch("controller.lib.wrol_mode.is_wrol_mode", return_value=True):
with pytest.raises(PermissionError) as exc_info:
require_normal_mode("modify settings")
assert "modify settings" in str(exc_info.value)