geo/backend/tests/test_api/test_citations.py

96 lines
2.9 KiB
Python

import uuid
from datetime import datetime
from unittest.mock import AsyncMock, patch
import pytest
@pytest.fixture
def mock_citation_record():
"""Return a mock citation record."""
record = AsyncMock()
record.id = uuid.UUID("32345678-1234-1234-1234-123456789abc")
record.query_id = uuid.UUID("22345678-1234-1234-1234-123456789abc")
record.platform = "wenxin"
record.cited = True
record.citation_position = 1
record.citation_text = "Test citation text"
record.competitor_brands = []
record.match_type = "exact"
record.data_source = "ai_response"
record.ai_response_text = "AI response text"
record.queried_at = datetime.now()
return record
@pytest.mark.asyncio
async def test_get_citations(
async_client, override_get_current_user, auth_headers, mock_citation_record
):
with patch(
"app.api.citations.get_citations",
return_value=([mock_citation_record], 1),
):
response = await async_client.get(
"/api/v1/citations/",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert len(data["items"]) == 1
assert data["items"][0]["platform"] == "wenxin"
assert data["items"][0]["cited"] is True
@pytest.mark.asyncio
async def test_get_citation_stats(
async_client, override_get_current_user, auth_headers
):
stats = {
"total_queries": 10,
"total_citations": 7,
"citation_rate": 0.7,
"avg_position": 2.5,
"by_platform": {
"wenxin": {
"queries": 5,
"citations": 4,
"rate": 0.8,
"avg_position": 2.0,
}
},
"trend": [{"date": "2024-01-01", "citations": 3}],
}
with patch("app.api.citations.get_citation_stats", return_value=stats):
response = await async_client.get(
"/api/v1/citations/stats",
headers=auth_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total_queries"] == 10
assert data["total_citations"] == 7
assert data["citation_rate"] == 0.7
assert "wenxin" in data["by_platform"]
@pytest.mark.asyncio
async def test_export_csv(
async_client, override_get_current_user, auth_headers
):
csv_content = "日期,平台,是否引用,引用位置,引用文本,竞争品牌\n2024-01-01,wenxin,是,1,test,\n"
with patch(
"app.api.reports.export_citations_csv",
return_value=csv_content,
):
response = await async_client.get(
"/api/v1/reports/export/csv?query_id=22345678-1234-1234-1234-123456789abc",
headers=auth_headers,
)
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/csv")
assert "attachment" in response.headers["content-disposition"]
body = response.text
assert "wenxin" in body