61 lines
1.7 KiB
Python
61 lines
1.7 KiB
Python
|
|
"""Fleet metric aggregation and API shape."""
|
||
|
|
|
||
|
|
from datetime import datetime, timedelta, timezone
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from server.utils.fleet_metrics import aggregate_fleet_metrics
|
||
|
|
|
||
|
|
|
||
|
|
def test_aggregate_fleet_metrics_averages():
|
||
|
|
rows = [
|
||
|
|
{
|
||
|
|
"is_online": "True",
|
||
|
|
"system_info": '{"cpu_usage": 10, "mem_usage": 20, "disk_usage": 30}',
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"is_online": "True",
|
||
|
|
"system_info": '{"cpu_usage": 30, "mem_usage": 40, "disk_usage": 50}',
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"is_online": "False",
|
||
|
|
"system_info": '{"cpu_usage": 100, "mem_usage": 100, "disk_usage": 100}',
|
||
|
|
},
|
||
|
|
]
|
||
|
|
agg = aggregate_fleet_metrics(rows)
|
||
|
|
assert agg.online_count == 2
|
||
|
|
assert agg.sample_count == 3
|
||
|
|
assert agg.cpu_avg == 47 # round((10+30+100)/3)
|
||
|
|
assert agg.mem_avg == 53
|
||
|
|
assert agg.disk_avg == 60
|
||
|
|
|
||
|
|
|
||
|
|
def test_aggregate_empty():
|
||
|
|
agg = aggregate_fleet_metrics([])
|
||
|
|
assert agg.online_count == 0
|
||
|
|
assert agg.cpu_avg is None
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.asyncio
|
||
|
|
async def test_fleet_metrics_api(db_session, test_admin):
|
||
|
|
from server.api.servers import fleet_metrics
|
||
|
|
from server.infrastructure.database.fleet_metric_repo import FleetMetricRepositoryImpl
|
||
|
|
|
||
|
|
repo = FleetMetricRepositoryImpl(db_session)
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
await repo.insert_sample(
|
||
|
|
recorded_at=now,
|
||
|
|
online_count=100,
|
||
|
|
sample_count=90,
|
||
|
|
cpu_avg=12,
|
||
|
|
mem_avg=45,
|
||
|
|
disk_avg=60,
|
||
|
|
)
|
||
|
|
await db_session.commit()
|
||
|
|
|
||
|
|
body = await fleet_metrics(hours=24, admin=test_admin["admin"], db=db_session)
|
||
|
|
assert body["hours"] == 24
|
||
|
|
assert body["interval_minutes"] == 10
|
||
|
|
assert len(body["points"]) >= 1
|
||
|
|
assert body["points"][-1]["cpu_avg"] == 12
|