File size: 19,600 Bytes
59bd45e | 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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | """Tests for main FastAPI application.
Requirements: 10.4 - Startup configuration validation
Requirements: 8.1, 8.2, 8.3 - API endpoint implementation
"""
import os
import pytest
from unittest.mock import patch, AsyncMock, MagicMock
from io import BytesIO
class TestApplicationStartup:
"""Test application startup and configuration validation.
Requirement 10.4: Application should refuse to start if required config is missing.
"""
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_app_starts_with_valid_config(self, tmp_path):
"""Test that application starts successfully with valid configuration."""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
# Import app after setting environment
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
assert response.json()["status"] == "running"
@patch.dict(os.environ, {}, clear=True)
def test_app_refuses_to_start_without_api_key(self):
"""Test that application refuses to start without API key.
Requirement 10.4: Missing required config should cause startup failure.
"""
# Reset the config module
import app.config
app.config._config = None
# Import fresh app module
import importlib
import app.main
importlib.reload(app.main)
from fastapi.testclient import TestClient
with pytest.raises(RuntimeError, match="Configuration error"):
with TestClient(app.main.app) as client:
# Trigger lifespan startup
pass
class TestHealthEndpoint:
"""Test health check endpoint."""
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_health_check_success(self, tmp_path):
"""Test health check returns healthy status."""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
response = client.get("/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "healthy"
assert "data_dir" in data
assert "max_audio_size" in data
class TestRootEndpoint:
"""Test root endpoint."""
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_root_endpoint(self, tmp_path):
"""Test root endpoint returns service information."""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
data = response.json()
assert data["service"] == "Voice Text Processor"
assert data["status"] == "running"
assert "version" in data
class TestProcessEndpoint:
"""Test /api/process endpoint.
Requirements: 8.1, 8.2, 8.3 - API endpoint, business logic, error handling
"""
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_process_endpoint_exists(self, tmp_path):
"""Test that POST /api/process endpoint exists.
Requirement 8.1: System should provide POST /api/process interface.
"""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Test with empty request (should fail validation but endpoint exists)
response = client.post("/api/process")
# Should return 400 (validation error), not 404 (not found)
assert response.status_code == 400
assert "error" in response.json()
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.SemanticParserService")
def test_process_text_input(self, mock_parser_class, tmp_path):
"""Test processing text input (application/json format).
Requirement 8.3: System should accept application/json format.
"""
# Reset config
import app.config
app.config._config = None
# Mock semantic parser
from app.models import ParsedData
mock_parser = MagicMock()
mock_parser.parse = AsyncMock(return_value=ParsedData(
mood=None,
inspirations=[],
todos=[]
))
mock_parser.close = AsyncMock()
mock_parser_class.return_value = mock_parser
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Use data parameter for form data
response = client.post(
"/api/process",
data={"text": "今天心情很好"}
)
assert response.status_code == 200
data = response.json()
assert "record_id" in data
assert "timestamp" in data
assert "mood" in data
assert "inspirations" in data
assert "todos" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.ASRService")
@patch("app.main.SemanticParserService")
def test_process_audio_input(self, mock_parser_class, mock_asr_class, tmp_path):
"""Test processing audio input (multipart/form-data format).
Requirement 8.2: System should accept multipart/form-data format.
"""
# Reset config
import app.config
app.config._config = None
# Mock ASR service
mock_asr = MagicMock()
mock_asr.transcribe = AsyncMock(return_value="转写后的文本")
mock_asr.close = AsyncMock()
mock_asr_class.return_value = mock_asr
# Mock semantic parser
from app.models import ParsedData
mock_parser = MagicMock()
mock_parser.parse = AsyncMock(return_value=ParsedData(
mood=None,
inspirations=[],
todos=[]
))
mock_parser.close = AsyncMock()
mock_parser_class.return_value = mock_parser
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Create fake audio file
audio_data = b"fake audio content"
files = {"audio": ("test.mp3", BytesIO(audio_data), "audio/mpeg")}
response = client.post("/api/process", files=files)
assert response.status_code == 200
data = response.json()
assert "record_id" in data
assert "timestamp" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_validation_error_empty_input(self, tmp_path):
"""Test validation error for empty input.
Requirement 8.3: System should return HTTP 400 for validation errors.
"""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
response = client.post("/api/process")
assert response.status_code == 400
data = response.json()
assert "error" in data
assert "timestamp" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_validation_error_unsupported_audio_format(self, tmp_path):
"""Test validation error for unsupported audio format.
Requirement 1.1: System should reject unsupported audio formats.
"""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Create fake audio file with unsupported format
audio_data = b"fake audio content"
files = {"audio": ("test.ogg", BytesIO(audio_data), "audio/ogg")}
response = client.post("/api/process", files=files)
assert response.status_code == 400
data = response.json()
assert "error" in data
assert "不支持的音频格式" in data["error"]
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
def test_validation_error_file_too_large(self, tmp_path):
"""Test validation error for file size exceeding limit.
Requirement 1.4: System should reject files larger than max size.
"""
# Reset config
import app.config
app.config._config = None
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log"),
"MAX_AUDIO_SIZE": "100" # Set very small limit
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Create audio file larger than limit
audio_data = b"x" * 200 # 200 bytes > 100 bytes limit
files = {"audio": ("test.mp3", BytesIO(audio_data), "audio/mpeg")}
response = client.post("/api/process", files=files)
assert response.status_code == 400
data = response.json()
assert "error" in data
assert "音频文件过大" in data["error"]
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.ASRService")
def test_asr_service_error(self, mock_asr_class, tmp_path):
"""Test ASR service error handling.
Requirement 8.3: System should return HTTP 500 for ASR service errors.
"""
# Reset config
import app.config
app.config._config = None
# Mock ASR service to raise error
from app.asr_service import ASRServiceError
mock_asr = MagicMock()
mock_asr.transcribe = AsyncMock(side_effect=ASRServiceError("API调用失败"))
mock_asr.close = AsyncMock()
mock_asr_class.return_value = mock_asr
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
audio_data = b"fake audio content"
files = {"audio": ("test.mp3", BytesIO(audio_data), "audio/mpeg")}
response = client.post("/api/process", files=files)
assert response.status_code == 500
data = response.json()
assert "error" in data
assert "语音识别服务不可用" in data["error"]
assert "timestamp" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.SemanticParserService")
def test_semantic_parser_error(self, mock_parser_class, tmp_path):
"""Test semantic parser error handling.
Requirement 8.3: System should return HTTP 500 for semantic parser errors.
"""
# Reset config
import app.config
app.config._config = None
# Mock semantic parser to raise error
from app.semantic_parser import SemanticParserError
mock_parser = MagicMock()
mock_parser.parse = AsyncMock(side_effect=SemanticParserError("API调用失败"))
mock_parser.close = AsyncMock()
mock_parser_class.return_value = mock_parser
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Use data parameter for form data
response = client.post(
"/api/process",
data={"text": "今天心情很好"}
)
assert response.status_code == 500
data = response.json()
assert "error" in data
assert "语义解析服务不可用" in data["error"]
assert "timestamp" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.SemanticParserService")
@patch("app.main.StorageService")
def test_storage_error(self, mock_storage_class, mock_parser_class, tmp_path):
"""Test storage error handling.
Requirement 8.3: System should return HTTP 500 for storage errors.
"""
# Reset config
import app.config
app.config._config = None
# Mock semantic parser
from app.models import ParsedData
mock_parser = MagicMock()
mock_parser.parse = AsyncMock(return_value=ParsedData(
mood=None,
inspirations=[],
todos=[]
))
mock_parser.close = AsyncMock()
mock_parser_class.return_value = mock_parser
# Mock storage service to raise error
from app.storage import StorageError
mock_storage = MagicMock()
mock_storage.save_record = MagicMock(side_effect=StorageError("磁盘空间不足"))
mock_storage_class.return_value = mock_storage
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Use data parameter for form data
response = client.post(
"/api/process",
data={"text": "今天心情很好"}
)
assert response.status_code == 500
data = response.json()
assert "error" in data
assert "数据存储失败" in data["error"]
assert "timestamp" in data
@patch.dict(os.environ, {"ZHIPU_API_KEY": "test_key_1234567890"}, clear=True)
@patch("app.main.SemanticParserService")
def test_success_response_format(self, mock_parser_class, tmp_path):
"""Test success response format.
Requirement 8.4, 8.6: Success response should include all required fields.
"""
# Reset config
import app.config
app.config._config = None
# Mock semantic parser with full data
from app.models import MoodData, InspirationData, TodoData, ParsedData
mock_parser = MagicMock()
mock_parser.parse = AsyncMock(return_value=ParsedData(
mood=MoodData(type="开心", intensity=8, keywords=["愉快"]),
inspirations=[InspirationData(core_idea="新想法", tags=["创新"], category="工作")],
todos=[TodoData(task="完成报告", time="明天", location="办公室")]
))
mock_parser.close = AsyncMock()
mock_parser_class.return_value = mock_parser
with patch.dict(os.environ, {
"DATA_DIR": str(tmp_path / "data"),
"LOG_FILE": str(tmp_path / "logs" / "app.log")
}, clear=False):
from fastapi.testclient import TestClient
from app.main import app
with TestClient(app) as client:
# Use data parameter for form data
response = client.post(
"/api/process",
data={"text": "今天心情很好,有个新想法,明天要完成报告"}
)
assert response.status_code == 200
data = response.json()
# Check all required fields
assert "record_id" in data
assert "timestamp" in data
assert "mood" in data
assert "inspirations" in data
assert "todos" in data
# Check mood data
assert data["mood"]["type"] == "开心"
assert data["mood"]["intensity"] == 8
# Check inspirations
assert len(data["inspirations"]) == 1
assert data["inspirations"][0]["core_idea"] == "新想法"
# Check todos
assert len(data["todos"]) == 1
assert data["todos"][0]["task"] == "完成报告"
|