"""Integration: Busiest Containers bars average each container's samples per time bucket in one query (#5214). Two samples share a bucket and must merge (lesson #5262). Requires STEWARD_DATABASE_URL.""" from __future__ import annotations import asyncio import os import uuid from datetime import datetime, timedelta, timezone import pytest pytestmark = pytest.mark.integration @pytest.fixture def app(): if not os.environ.get("STEWARD_DATABASE_URL"): pytest.skip("needs Postgres") from steward.app import create_app return create_app(testing=False) def test_recent_usage_averages_each_containers_bucket(app): from plugins.docker.models import DockerMetric from plugins.docker.service import bar_slots, recent_usage from steward.models.hosts import Host tag = uuid.uuid4().hex[:8] hid = str(uuid.uuid4()) slots, width = bar_slots(datetime.now(timezone.utc), 6) at = slots[-2] # a whole bucket, in the past def m(name, secs, cpu, mem): return DockerMetric(host_id=hid, container_name=name, scraped_at=at + timedelta(seconds=secs), cpu_pct=cpu, mem_pct=0.0, mem_usage_bytes=mem) async def go(): async with app.db_sessionmaker() as s: async with s.begin(): s.add(Host(id=hid, name=f"dock-{tag}", address="10.9.9.4")) async with s.begin(): s.add_all([m(f"a-{tag}", 10, 100.0, 1000), m(f"a-{tag}", 70, 300.0, 3000), m(f"b-{tag}", 10, 50.0, 500)]) async with s.begin(): return await recent_usage(s, {(hid, f"a-{tag}")}, slots[0], width) got = asyncio.run(go()) assert got == {(hid, f"a-{tag}"): {at: (200.0, 2000.0)}}