AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
test(platform/admin): increase patch coverage for export endpoint and cache token tracking
Zamil Majdy2f67249d5f4e
diff --git a/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes_test.pyindex 224a754487..8cfc0e47b5 100644--- a/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/platform_cost_routes_test.py@@ -1,3 +1,4 @@+from datetime import datetime, timezonefrom unittest.mock import AsyncMockimport fastapi@@ -6,7 +7,7 @@ import pytestimport pytest_mockfrom autogpt_libs.auth.jwt_utils import get_jwt_payload-from backend.data.platform_cost import PlatformCostDashboard+from backend.data.platform_cost import CostLogRow, PlatformCostDashboardfrom .platform_cost_routes import router as platform_cost_router@@ -190,3 +191,101 @@ def test_get_dashboard_repeated_requests(assert r2.status_code == 200assert r1.json()["total_cost_microdollars"] == 42assert r2.json()["total_cost_microdollars"] == 42+++def _make_cost_log_row() -> CostLogRow:+ return CostLogRow(+ id="log-1",+ created_at=datetime(2026, 1, 1, tzinfo=timezone.utc),+ user_id="user-1",+ email="u***@example.com",+ graph_exec_id="graph-1",+ node_exec_id="node-1",+ block_name="LlmCallBlock",+ provider="anthropic",+ tracking_type="token",+ cost_microdollars=500,+ input_tokens=100,+ output_tokens=50,+ cache_read_tokens=10,+ cache_creation_tokens=5,+ duration=1.5,+ model="claude-3-5-sonnet-20241022",+ )+++def test_export_logs_success(+ mocker: pytest_mock.MockerFixture,+) -> None:+ row = _make_cost_log_row()+ mocker.patch(+ "backend.api.features.admin.platform_cost_routes.get_platform_cost_logs_for_export",+ AsyncMock(return_value=([row], False)),+ )++ response = client.get("/platform-costs/logs/export")+ assert response.status_code == 200+ data = response.json()+ assert data["total_rows"] == 1+ assert data["truncated"] is False+ assert len(data["logs"]) == 1+ assert data["logs"][0]["cache_read_tokens"] == 10+ assert data["logs"][0]["cache_creation_tokens"] == 5+++def test_export_logs_truncated(+ mocker: pytest_mock.MockerFixture,+) -> None:+ rows = [_make_cost_log_row() for _ in range(3)]+ mocker.patch(+ "backend.api.features.admin.platform_cost_routes.get_platform_cost_logs_for_export",+ AsyncMock(return_value=(rows, True)),+ )++ response = client.get("/platform-costs/logs/export")+ assert response.status_code == 200+ data = response.json()+ assert data["total_rows"] == 3+ assert data["truncated"] is True+++def test_export_logs_with_filters(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_export = AsyncMock(return_value=([], False))+ mocker.patch(+ "backend.api.features.admin.platform_cost_routes.get_platform_cost_logs_for_export",+ mock_export,+ )++ response = client.get(+ "/platform-costs/logs/export",+ params={+ "provider": "anthropic",+ "model": "claude-3-5-sonnet-20241022",+ "block_name": "LlmCallBlock",+ "tracking_type": "token",+ },+ )+ assert response.status_code == 200+ mock_export.assert_called_once()+ call_kwargs = mock_export.call_args.kwargs+ assert call_kwargs["provider"] == "anthropic"+ assert call_kwargs["model"] == "claude-3-5-sonnet-20241022"+ assert call_kwargs["block_name"] == "LlmCallBlock"+ assert call_kwargs["tracking_type"] == "token"+++def test_export_logs_requires_admin() -> None:+ import fastapi+ from fastapi import HTTPException++ def reject_jwt(request: fastapi.Request):+ raise HTTPException(status_code=401, detail="Not authenticated")++ app.dependency_overrides[get_jwt_payload] = reject_jwt+ try:+ response = client.get("/platform-costs/logs/export")+ assert response.status_code == 401+ finally:+ app.dependency_overrides.clear()diff --git a/autogpt_platform/backend/backend/data/platform_cost_test.py b/autogpt_platform/backend/backend/data/platform_cost_test.pyindex 169934377b..7c5b75e78a 100644--- a/autogpt_platform/backend/backend/data/platform_cost_test.py+++ b/autogpt_platform/backend/backend/data/platform_cost_test.py@@ -14,6 +14,7 @@ from .platform_cost import (_mask_email,get_platform_cost_dashboard,get_platform_cost_logs,+ get_platform_cost_logs_for_export,log_platform_cost,log_platform_cost_safe,)@@ -94,6 +95,51 @@ class TestBuildWhere:sql, _ = _build_where(start, end, None, None)assert " AND " in sql+ def test_model_only(self):+ sql, params = _build_where(None, None, None, None, model="gpt-4")+ assert '"model" = $1' in sql+ assert params == ["gpt-4"]++ def test_block_name_only(self):+ sql, params = _build_where(None, None, None, None, block_name="LLMBlock")+ assert 'LOWER("blockName") = LOWER($1)' in sql+ assert params == ["LLMBlock"]++ def test_tracking_type_only(self):+ sql, params = _build_where(None, None, None, None, tracking_type="tokens")+ assert '"trackingType" = $1' in sql+ assert params == ["tokens"]++ def test_all_new_filters_combined(self):+ sql, params = _build_where(+ None,+ None,+ None,+ None,+ model="gpt-4",+ block_name="LLM",+ tracking_type="tokens",+ )+ assert len(params) == 3+ assert params[0] == "gpt-4"+ assert params[1] == "LLM"+ assert params[2] == "tokens"++ def test_new_filters_with_alias(self):+ sql, params = _build_where(+ None,+ None,+ None,+ None,+ table_alias="p",+ model="gpt-4",+ block_name="MyBlock",+ tracking_type="cost_usd",+ )+ assert 'p."model" = $1' in sql+ assert 'LOWER(p."blockName") = LOWER($2)' in sql+ assert 'p."trackingType" = $3' in sql+def _make_entry(**overrides: object) -> PlatformCostEntry:return PlatformCostEntry.model_validate(@@ -288,3 +334,78 @@ class TestGetPlatformCostLogs:with patch("backend.data.platform_cost.query_raw_with_schema", new=mock_query):logs, total = await get_platform_cost_logs()assert total == 0+++def _make_log_row(i: int = 0) -> dict:+ return {+ "id": f"log-{i}",+ "created_at": datetime(2026, 3, 1, tzinfo=timezone.utc),+ "user_id": "u1",+ "email": None,+ "graph_exec_id": None,+ "node_exec_id": None,+ "block_name": "TestBlock",+ "provider": "openai",+ "tracking_type": "tokens",+ "cost_microdollars": 1000,+ "input_tokens": 10,+ "output_tokens": 5,+ "duration": 0.5,+ "model": "gpt-4",+ "cache_read_tokens": None,+ "cache_creation_tokens": None,+ }+++class TestGetPlatformCostLogsForExport:+ @pytest.mark.asyncio+ async def test_returns_logs_not_truncated(self):+ rows = [_make_log_row(0)]+ mock_query = AsyncMock(return_value=rows)+ with patch("backend.data.platform_cost.query_raw_with_schema", new=mock_query):+ logs, truncated = await get_platform_cost_logs_for_export()+ assert len(logs) == 1+ assert truncated is False+ assert logs[0].id == "log-0"++ @pytest.mark.asyncio+ async def test_returns_empty_not_truncated(self):+ mock_query = AsyncMock(return_value=[])+ with patch("backend.data.platform_cost.query_raw_with_schema", new=mock_query):+ logs, truncated = await get_platform_cost_logs_for_export()+ assert logs == []+ assert truncated is False++ @pytest.mark.asyncio+ async def test_truncates_at_export_max_rows(self):+ rows = [_make_log_row(i) for i in range(3)]+ mock_query = AsyncMock(return_value=rows)+ with patch(+ "backend.data.platform_cost.query_raw_with_schema", new=mock_query+ ), patch("backend.data.platform_cost.EXPORT_MAX_ROWS", 2):+ logs, truncated = await get_platform_cost_logs_for_export()+ assert len(logs) == 2+ assert truncated is True++ @pytest.mark.asyncio+ async def test_passes_model_block_tracking_filters(self):+ mock_query = AsyncMock(return_value=[])+ with patch("backend.data.platform_cost.query_raw_with_schema", new=mock_query):+ await get_platform_cost_logs_for_export(+ model="gpt-4", block_name="LLMBlock", tracking_type="tokens"+ )+ call_args = mock_query.call_args[0]+ assert "gpt-4" in call_args+ assert "LLMBlock" in call_args+ assert "tokens" in call_args++ @pytest.mark.asyncio+ async def test_maps_cache_tokens(self):+ row = _make_log_row(0)+ row["cache_read_tokens"] = 50+ row["cache_creation_tokens"] = 25+ mock_query = AsyncMock(return_value=[row])+ with patch("backend.data.platform_cost.query_raw_with_schema", new=mock_query):+ logs, _ = await get_platform_cost_logs_for_export()+ assert logs[0].cache_read_tokens == 50+ assert logs[0].cache_creation_tokens == 25