test_log_storage.py 8.03 KB
"""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