test_log_storage.py
8.03 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
215
216
"""F-11 原始日志存储服务测试"""
import json
import os
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import patch
import pytest
from httpx import AsyncClient
from app.services import log_storage_service
class TestLogStorageService:
"""原始日志存储服务单元测试"""
@pytest.fixture(autouse=True)
def setup_temp_dir(self):
"""每个测试使用临时目录"""
with tempfile.TemporaryDirectory() as tmpdir:
with patch.object(log_storage_service.settings, "LOG_STORAGE_PATH", tmpdir):
yield
def test_write_and_read_raw_log(self):
"""测试写入和读取原始日志"""
request_id = "test-req-001"
request_body = {"model": "gpt-4", "messages": [{"role": "user", "content": "hello"}]}
response_body = {"content": "Hi there!", "tokens": 10}
file_path = log_storage_service.write_raw_log(
request_id=request_id,
request_body=request_body,
response_body=response_body,
)
assert file_path is not None
assert os.path.exists(file_path)
# 验证文件内容
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
assert data["request_id"] == request_id
assert data["request"] == request_body
assert data["response"] == response_body
assert "timestamp" in data
def test_write_with_metadata(self):
"""测试写入带元数据的日志"""
request_id = "test-req-002"
metadata = {"duration_ms": 1500, "status": "success"}
file_path = log_storage_service.write_raw_log(
request_id=request_id,
request_body={"test": True},
metadata=metadata,
)
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
assert data["metadata"] == metadata
def test_read_nonexistent_log(self):
"""测试读取不存在的日志返回 None"""
result = log_storage_service.read_raw_log("nonexistent-id")
assert result is None
def test_write_invalid_path_raises_error(self):
"""测试写入无法访问的路径抛出异常"""
from unittest.mock import mock_open
with patch("builtins.open", mock_open()) as mock_f:
mock_f.side_effect = PermissionError("Permission denied")
with pytest.raises(IOError):
log_storage_service.write_raw_log(
request_id="test",
request_body={},
)
def test_archive_no_expired_logs(self):
"""测试无过期日志时归档返回 0"""
count = log_storage_service.archive_expired_logs(retention_days=365)
assert count == 0
def test_archive_with_expired_logs(self):
"""测试有过期日志时归档"""
base_dir = Path(log_storage_service.settings.LOG_STORAGE_PATH)
calls_dir = base_dir / "calls"
# 创建过期日志目录(30 天前)
old_date = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
old_dir = calls_dir / old_date
old_dir.mkdir(parents=True, exist_ok=True)
(old_dir / "test.json").write_text('{"test": true}', encoding="utf-8")
# 创建新日志目录(今天)
new_date = datetime.now().strftime("%Y-%m-%d")
new_dir = calls_dir / new_date
new_dir.mkdir(parents=True, exist_ok=True)
(new_dir / "test2.json").write_text('{"test": true}', encoding="utf-8")
# 归档(保留 7 天 → 30 天前的应被归档)
count = log_storage_service.archive_expired_logs(retention_days=7)
assert count == 1
# 验证过期目录已移走到 archive
archive_dir = base_dir / "archive" / old_date
assert archive_dir.exists()
assert (archive_dir / "test.json").exists()
# 验证新目录仍在原处
assert new_dir.exists()
def test_get_log_stats(self):
"""测试获取日志存储统计"""
base_dir = Path(log_storage_service.settings.LOG_STORAGE_PATH)
calls_dir = base_dir / "calls"
# 创建一些测试日志
today = datetime.now().strftime("%Y-%m-%d")
today_dir = calls_dir / today
today_dir.mkdir(parents=True, exist_ok=True)
(today_dir / "a.json").write_text('{"a": 1}', encoding="utf-8")
(today_dir / "b.json").write_text('{"b": 2}', encoding="utf-8")
stats = log_storage_service.get_log_stats()
assert stats["active_date_dirs"] == 1
assert stats["active_file_count"] == 2
assert stats["total_size_bytes"] > 0
def test_concurrent_date_dirs(self):
"""测试多个日期目录下的日志文件"""
base_dir = Path(log_storage_service.settings.LOG_STORAGE_PATH)
calls_dir = base_dir / "calls"
for day_offset in range(5):
date_str = (datetime.now() - timedelta(days=day_offset)).strftime("%Y-%m-%d")
d = calls_dir / date_str
d.mkdir(parents=True, exist_ok=True)
(d / f"log-{day_offset}.json").write_text(f'{{"day": {day_offset}}}')
(d / f"log-{day_offset}-extra.json").write_text(f'{{"day": {day_offset}}}')
stats = log_storage_service.get_log_stats()
assert stats["active_date_dirs"] == 5
assert stats["active_file_count"] == 10
class TestLogStorageAPI:
"""原始日志存储 API 集成测试"""
@pytest.fixture(autouse=True)
def setup_temp_dir(self):
"""每个测试使用临时目录"""
with tempfile.TemporaryDirectory() as tmpdir:
with patch.object(log_storage_service.settings, "LOG_STORAGE_PATH", tmpdir):
yield
@pytest.mark.asyncio
async def test_write_log_file(self, client: AsyncClient):
"""测试写入日志文件 API"""
resp = await client.post("/api/v1/internal/logs/write-file", json={
"request_id": "api-test-001",
"request_body": {"model": "gpt-4", "messages": []},
"response_body": {"content": "test"},
})
assert resp.status_code == 200
result = resp.json()
assert "file_path" in result
assert result["message"] == "原始日志写入成功"
@pytest.mark.asyncio
async def test_write_log_file_missing_fields(self, client: AsyncClient):
"""测试缺少必填字段返回 422"""
resp = await client.post("/api/v1/internal/logs/write-file", json={
"request_id": "test",
})
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_read_log_file(self, client: AsyncClient):
"""测试读取日志文件 API"""
# 先写入一个日志
log_storage_service.write_raw_log(
request_id="read-test-001",
request_body={"msg": "hello"},
response_body={"msg": "world"},
)
resp = await client.get("/api/v1/internal/logs/read/read-test-001")
assert resp.status_code == 200
data = resp.json()
assert data["request_id"] == "read-test-001"
assert data["request"] == {"msg": "hello"}
@pytest.mark.asyncio
async def test_read_nonexistent_log_file(self, client: AsyncClient):
"""测试读取不存在的日志返回 404"""
resp = await client.get("/api/v1/internal/logs/read/nonexistent-id")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_archive_logs(self, client: AsyncClient):
"""测试归档日志 API"""
resp = await client.post("/api/v1/internal/logs/archive", json={
"retention_days": 365,
})
assert resp.status_code == 200
result = resp.json()
assert "archived_count" in result
@pytest.mark.asyncio
async def test_get_log_stats(self, client: AsyncClient):
"""测试获取日志统计 API"""
resp = await client.get("/api/v1/internal/logs/stats")
assert resp.status_code == 200
data = resp.json()
assert "log_path" in data
assert "retention_days" in data