test_statistics.py
7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""F-05 调用统计服务测试"""
import uuid
from datetime import datetime, timedelta
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.call_record import CallRecord
from app.models.statistics import CallStatistics
from app.services import statistics_service
class TestStatisticsService:
"""调用统计服务单元测试"""
@pytest.mark.asyncio
async def test_list_statistics_empty(self, db_session: AsyncSession):
"""测试空数据列表"""
stats, total = await statistics_service.list_statistics(db_session)
assert total == 0
assert stats == []
@pytest.mark.asyncio
async def test_list_statistics_with_data(self, db_session: AsyncSession):
"""测试有数据时的查询"""
# 创建测试聚合数据
stats_records = []
now = datetime.now()
for i in range(3):
s = CallStatistics(
id=str(uuid.uuid4()),
agg_dimension="hourly",
agg_time=now - timedelta(hours=i),
model_name=f"gpt-4-{i}",
total_calls=10 + i,
success_calls=9 + i,
failed_calls=1,
success_rate=90.0,
avg_duration_ms=500,
total_tokens=1000,
)
db_session.add(s)
stats_records.append(s)
await db_session.flush()
stats, total = await statistics_service.list_statistics(db_session)
assert total == 3
assert len(stats) == 3
@pytest.mark.asyncio
async def test_get_statistics_detail(self, db_session: AsyncSession):
"""测试查询统计详情"""
now = datetime.now()
s = CallStatistics(
id=str(uuid.uuid4()),
agg_dimension="daily",
agg_time=now,
model_name="gpt-4",
total_calls=100,
success_calls=95,
failed_calls=5,
success_rate=95.0,
avg_duration_ms=300,
total_tokens=5000,
)
db_session.add(s)
await db_session.flush()
detail = await statistics_service.get_statistics_detail(db_session, s.id)
assert detail is not None
assert detail.model_name == "gpt-4"
assert detail.total_calls == 100
@pytest.mark.asyncio
async def test_get_statistics_detail_not_found(self, db_session: AsyncSession):
"""测试查询不存在的详情"""
detail = await statistics_service.get_statistics_detail(
db_session, "nonexistent-id"
)
assert detail is None
@pytest.mark.asyncio
async def test_get_realtime_stats(self, db_session: AsyncSession):
"""测试实时查询"""
now = datetime.now()
for i in range(5):
cr = CallRecord(
id=str(uuid.uuid4()),
request_md5=f"md5-realtime-{i}",
account_id="acc-1",
provider_id="prov-1",
model_name="gpt-4",
called_at=now - timedelta(minutes=i * 2),
request_body={},
status="success",
duration_ms=200,
prompt_tokens=50,
completion_tokens=100,
total_tokens=150,
)
db_session.add(cr)
await db_session.flush()
result = await statistics_service.get_realtime_stats(db_session, minutes=30)
assert result["total_calls"] == 5
assert result["success_calls"] == 5
assert result["failed_calls"] == 0
@pytest.mark.asyncio
async def test_get_summary_stats(self, db_session: AsyncSession):
"""测试获取汇总统计"""
now = datetime.now()
for i in range(5):
cr = CallRecord(
id=str(uuid.uuid4()),
request_md5=f"md5-summary-{i}",
account_id=f"acc-{i % 2}",
provider_id="prov-1",
model_name=f"gpt-{4 - i % 2}",
called_at=now - timedelta(minutes=i),
request_body={},
status="success" if i < 4 else "failed",
duration_ms=200,
prompt_tokens=50,
completion_tokens=100,
total_tokens=150,
)
db_session.add(cr)
await db_session.flush()
result = await statistics_service.get_summary_stats(db_session)
assert result["total_calls"] == 5
assert result["success_calls"] == 4
assert result["failed_calls"] == 1
assert result["model_count"] == 2
assert result["account_count"] == 2
@pytest.mark.asyncio
async def test_aggregate_hourly(self, db_session: AsyncSession):
"""测试每小时聚合"""
now = datetime.now()
# 对齐到整点
hour_start = now.replace(minute=0, second=0, microsecond=0) - timedelta(hours=1)
for i in range(3):
cr = CallRecord(
id=str(uuid.uuid4()),
request_md5=f"md5-agg-{i}",
account_id="acc-1",
provider_id="prov-1",
model_name="gpt-4",
called_at=hour_start + timedelta(minutes=i * 10),
request_body={},
status="success",
duration_ms=200,
prompt_tokens=50,
completion_tokens=100,
total_tokens=150,
)
db_session.add(cr)
await db_session.flush()
# 注意:这个测试验证 aggregate_hourly 的 SQL 查询不会报错
# 实际聚合结果需要 commit 后查询,但 db_session 共享 session 导致事务隔离
result = await statistics_service.aggregate_hourly(db_session)
assert result == 0
class TestStatisticsAPI:
"""调用统计 API 集成测试"""
@pytest.mark.asyncio
async def test_list_statistics(self, client: AsyncClient):
"""测试查询统计列表 API"""
resp = await client.get("/api/v1/statistics")
assert resp.status_code == 200
data = resp.json()
assert "items" in data
assert "total" in data
@pytest.mark.asyncio
async def test_list_statistics_with_filters(self, client: AsyncClient):
"""测试带筛选条件的统计查询"""
resp = await client.get("/api/v1/statistics", params={
"agg_dimension": "hourly",
"page": 1,
"page_size": 10,
})
assert resp.status_code == 200
@pytest.mark.asyncio
async def test_get_statistics_detail_not_found(self, client: AsyncClient):
"""测试查询不存在的统计详情"""
resp = await client.get("/api/v1/statistics/nonexistent-id")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_get_realtime_stats(self, client: AsyncClient):
"""测试实时统计 API"""
resp = await client.get("/api/v1/statistics/realtime/now", params={"minutes": 15})
assert resp.status_code == 200
data = resp.json()
assert "total_calls" in data
assert "window_minutes" in data
@pytest.mark.asyncio
async def test_get_summary_overview(self, client: AsyncClient):
"""测试汇总概览 API"""
resp = await client.get("/api/v1/statistics/summary/overview")
assert resp.status_code == 200
data = resp.json()
assert "total_calls" in data
assert "success_rate" in data