Spaces:
Sleeping
Sleeping
Merge pull request #5 from Tobkubos/backend-setup
Browse files- TODO.md +0 -2
- backend/.env.example +0 -4
- backend/README.md +1 -20
- backend/app/__init__.py +5 -0
- backend/app/api/routes.py +33 -11
- backend/app/core/config.py +1 -5
- backend/app/core/limiter.py +4 -0
- backend/app/models/schemas.py +2 -2
- backend/requirements.txt +4 -1
- backend/run_tests.py +47 -0
- backend/test_rate_limit.sh +161 -0
- backend/tests/__init__.py +1 -0
- backend/tests/conftest.py +33 -0
- backend/tests/test_analysis.py +348 -0
- index.js +1 -1
TODO.md
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
Bezpieczeństwo (SSRF - Server-Side Request Forgery): Twój backend pobiera pliki z dowolnego przekazanego adresu URL. Złośliwy użytkownik mógłby podać URL wskazujący na wewnętrzne zasoby Twojej sieci (np. http://localhost:8080/admin). Warto zaimplementować w download_file walidację, która pozwala na pobieranie plików wyłącznie z zaufanych domen (np. tylko z *.discordapp.com i *.media.discordapp.net).
|
| 2 |
-
|
|
|
|
|
|
|
|
|
backend/.env.example
CHANGED
|
@@ -14,10 +14,6 @@ PORT=8000
|
|
| 14 |
DOWNLOAD_TIMEOUT=30
|
| 15 |
MAX_FILE_SIZE=104857600
|
| 16 |
|
| 17 |
-
# ML Model Configuration
|
| 18 |
-
DEFAULT_DETECTOR_MODEL=mock
|
| 19 |
-
# Supported models: mock, deepseek, openai, etc.
|
| 20 |
-
|
| 21 |
# Redis Configuration (for future queuing)
|
| 22 |
REDIS_ENABLED=False
|
| 23 |
REDIS_URL=redis://localhost:6379
|
|
|
|
| 14 |
DOWNLOAD_TIMEOUT=30
|
| 15 |
MAX_FILE_SIZE=104857600
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# Redis Configuration (for future queuing)
|
| 18 |
REDIS_ENABLED=False
|
| 19 |
REDIS_URL=redis://localhost:6379
|
backend/README.md
CHANGED
|
@@ -41,25 +41,6 @@ Once the server is running, interactive API documentation is available at:
|
|
| 41 |
- Swagger UI: `http://127.0.0.1:8000/docs`
|
| 42 |
- ReDoc: `http://127.0.0.1:8000/redoc`
|
| 43 |
|
| 44 |
-
## 🔌 API Endpoints
|
| 45 |
-
|
| 46 |
-
### Health Check
|
| 47 |
-
```bash
|
| 48 |
-
GET /
|
| 49 |
-
```
|
| 50 |
-
|
| 51 |
-
Returns service status and available models.
|
| 52 |
-
|
| 53 |
-
**Response:**
|
| 54 |
-
```json
|
| 55 |
-
{
|
| 56 |
-
"status": "ok",
|
| 57 |
-
"service": "Deepfake Detection Service",
|
| 58 |
-
"version": "1.0.0",
|
| 59 |
-
"available_models": ["mock"]
|
| 60 |
-
}
|
| 61 |
-
```
|
| 62 |
-
|
| 63 |
### Analyze File
|
| 64 |
```bash
|
| 65 |
POST /analyze
|
|
@@ -81,7 +62,7 @@ Content-Type: application/json
|
|
| 81 |
"is_deepfake": true,
|
| 82 |
"confidence": 0.847,
|
| 83 |
"analysis_time": 1.234,
|
| 84 |
-
"
|
| 85 |
}
|
| 86 |
```
|
| 87 |
|
|
|
|
| 41 |
- Swagger UI: `http://127.0.0.1:8000/docs`
|
| 42 |
- ReDoc: `http://127.0.0.1:8000/redoc`
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
### Analyze File
|
| 45 |
```bash
|
| 46 |
POST /analyze
|
|
|
|
| 62 |
"is_deepfake": true,
|
| 63 |
"confidence": 0.847,
|
| 64 |
"analysis_time": 1.234,
|
| 65 |
+
"used_model": "mock"
|
| 66 |
}
|
| 67 |
```
|
| 68 |
|
backend/app/__init__.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
from fastapi import FastAPI
|
|
|
|
|
|
|
| 2 |
from app.api.routes import router as api_router
|
| 3 |
from app.core.logging_config import setup_logging
|
|
|
|
| 4 |
|
| 5 |
setup_logging()
|
| 6 |
|
|
@@ -10,4 +13,6 @@ app = FastAPI(
|
|
| 10 |
version="1.0.0",
|
| 11 |
)
|
| 12 |
|
|
|
|
|
|
|
| 13 |
app.include_router(api_router)
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
+
from slowapi import _rate_limit_exceeded_handler
|
| 3 |
+
from slowapi.errors import RateLimitExceeded
|
| 4 |
from app.api.routes import router as api_router
|
| 5 |
from app.core.logging_config import setup_logging
|
| 6 |
+
from app.core.limiter import limiter
|
| 7 |
|
| 8 |
setup_logging()
|
| 9 |
|
|
|
|
| 13 |
version="1.0.0",
|
| 14 |
)
|
| 15 |
|
| 16 |
+
app.state.limiter = limiter
|
| 17 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 18 |
app.include_router(api_router)
|
backend/app/api/routes.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import logging
|
| 2 |
-
from fastapi import APIRouter, HTTPException, status
|
| 3 |
|
| 4 |
from app.models.schemas import (
|
| 5 |
AnalysisRequest,
|
|
@@ -14,6 +14,7 @@ from app.services.text_analyzer import analyze_text
|
|
| 14 |
from app.services.image_analyzer import analyze_image
|
| 15 |
from app.core.config import get_settings
|
| 16 |
from app.utils.exceptions import DeepfakeDetectionError
|
|
|
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
@@ -29,8 +30,28 @@ async def health_check() -> HealthResponse:
|
|
| 29 |
settings = get_settings()
|
| 30 |
logger.info("Health check endpoint accessed")
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
return HealthResponse(
|
| 33 |
-
status=
|
| 34 |
service="Deepfake Detection Service",
|
| 35 |
version=settings.APP_VERSION,
|
| 36 |
available_models=settings.AVAILABLE_MODELS,
|
|
@@ -44,15 +65,17 @@ async def health_check() -> HealthResponse:
|
|
| 44 |
400: {"model": ErrorResponse, "description": "Bad request"},
|
| 45 |
408: {"model": ErrorResponse, "description": "Request timeout"},
|
| 46 |
415: {"model": ErrorResponse, "description": "Unsupported media type"},
|
|
|
|
| 47 |
500: {"model": ErrorResponse, "description": "Internal server error"},
|
| 48 |
},
|
| 49 |
tags=["Analysis"],
|
| 50 |
summary="Analyze content for deepfake detection",
|
| 51 |
)
|
| 52 |
-
|
| 53 |
-
|
|
|
|
| 54 |
content_type = "text"
|
| 55 |
-
elif isinstance(
|
| 56 |
content_type = "image"
|
| 57 |
else:
|
| 58 |
raise HTTPException(
|
|
@@ -70,15 +93,15 @@ async def analyze(request: AnalysisRequest) -> AnalysisResponse:
|
|
| 70 |
|
| 71 |
try:
|
| 72 |
if content_type == "text":
|
| 73 |
-
if len(
|
| 74 |
raise ValueError(f"Text content exceeds maximum length of {settings.MAX_CONTENT_SIZES['text']} characters")
|
| 75 |
-
if len(
|
| 76 |
raise ValueError("Text content must be at least 50 characters")
|
| 77 |
|
| 78 |
-
analysis_result = await analyze_text(
|
| 79 |
|
| 80 |
elif content_type == "image":
|
| 81 |
-
image_bytes = await download_file(str(
|
| 82 |
if not image_bytes:
|
| 83 |
raise ValueError("Failed to download image")
|
| 84 |
if len(image_bytes) > settings.MAX_CONTENT_SIZES["image"]:
|
|
@@ -86,7 +109,6 @@ async def analyze(request: AnalysisRequest) -> AnalysisResponse:
|
|
| 86 |
|
| 87 |
analysis_result = await analyze_image(image_bytes)
|
| 88 |
|
| 89 |
-
# 4. Globalna obsługa błędów
|
| 90 |
except ValueError as e:
|
| 91 |
raise HTTPException(status_code=400, detail=str(e))
|
| 92 |
except DeepfakeDetectionError as e:
|
|
@@ -101,6 +123,6 @@ async def analyze(request: AnalysisRequest) -> AnalysisResponse:
|
|
| 101 |
is_deepfake=analysis_result["is_deepfake"],
|
| 102 |
confidence=analysis_result["confidence"],
|
| 103 |
analysis_time=analysis_result["analysis_time"],
|
| 104 |
-
|
| 105 |
content_type=content_type,
|
| 106 |
)
|
|
|
|
| 1 |
import logging
|
| 2 |
+
from fastapi import APIRouter, HTTPException, Request, status
|
| 3 |
|
| 4 |
from app.models.schemas import (
|
| 5 |
AnalysisRequest,
|
|
|
|
| 14 |
from app.services.image_analyzer import analyze_image
|
| 15 |
from app.core.config import get_settings
|
| 16 |
from app.utils.exceptions import DeepfakeDetectionError
|
| 17 |
+
from app.core.limiter import limiter
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
|
|
|
| 30 |
settings = get_settings()
|
| 31 |
logger.info("Health check endpoint accessed")
|
| 32 |
|
| 33 |
+
handlers = {
|
| 34 |
+
"text": analyze_text,
|
| 35 |
+
"image": analyze_image,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
models_status = {}
|
| 39 |
+
is_healthy = True
|
| 40 |
+
|
| 41 |
+
for content_type in settings.AVAILABLE_MODELS.keys():
|
| 42 |
+
handler = handlers.get(content_type)
|
| 43 |
+
|
| 44 |
+
if handler is not None and callable(handler):
|
| 45 |
+
models_status[content_type] = "ready"
|
| 46 |
+
else:
|
| 47 |
+
models_status[content_type] = "error_not_callable"
|
| 48 |
+
is_healthy = False
|
| 49 |
+
logger.error(f"Krytyczny brak! Handler dla typu '{content_type}' nie jest callable.")
|
| 50 |
+
|
| 51 |
+
overall_status = "ok" if is_healthy else "degraded"
|
| 52 |
+
|
| 53 |
return HealthResponse(
|
| 54 |
+
status=overall_status,
|
| 55 |
service="Deepfake Detection Service",
|
| 56 |
version=settings.APP_VERSION,
|
| 57 |
available_models=settings.AVAILABLE_MODELS,
|
|
|
|
| 65 |
400: {"model": ErrorResponse, "description": "Bad request"},
|
| 66 |
408: {"model": ErrorResponse, "description": "Request timeout"},
|
| 67 |
415: {"model": ErrorResponse, "description": "Unsupported media type"},
|
| 68 |
+
429: {"model": ErrorResponse, "description": "Too many requests"},
|
| 69 |
500: {"model": ErrorResponse, "description": "Internal server error"},
|
| 70 |
},
|
| 71 |
tags=["Analysis"],
|
| 72 |
summary="Analyze content for deepfake detection",
|
| 73 |
)
|
| 74 |
+
@limiter.limit("1/5seconds")
|
| 75 |
+
async def analyze(request: Request, payload: AnalysisRequest) -> AnalysisResponse:
|
| 76 |
+
if isinstance(payload, TextAnalysisRequest):
|
| 77 |
content_type = "text"
|
| 78 |
+
elif isinstance(payload, ImageAnalysisRequest):
|
| 79 |
content_type = "image"
|
| 80 |
else:
|
| 81 |
raise HTTPException(
|
|
|
|
| 93 |
|
| 94 |
try:
|
| 95 |
if content_type == "text":
|
| 96 |
+
if len(payload.text) > settings.MAX_CONTENT_SIZES["text"]:
|
| 97 |
raise ValueError(f"Text content exceeds maximum length of {settings.MAX_CONTENT_SIZES['text']} characters")
|
| 98 |
+
if len(payload.text) < 50:
|
| 99 |
raise ValueError("Text content must be at least 50 characters")
|
| 100 |
|
| 101 |
+
analysis_result = await analyze_text(payload.text)
|
| 102 |
|
| 103 |
elif content_type == "image":
|
| 104 |
+
image_bytes = await download_file(str(payload.image_url))
|
| 105 |
if not image_bytes:
|
| 106 |
raise ValueError("Failed to download image")
|
| 107 |
if len(image_bytes) > settings.MAX_CONTENT_SIZES["image"]:
|
|
|
|
| 109 |
|
| 110 |
analysis_result = await analyze_image(image_bytes)
|
| 111 |
|
|
|
|
| 112 |
except ValueError as e:
|
| 113 |
raise HTTPException(status_code=400, detail=str(e))
|
| 114 |
except DeepfakeDetectionError as e:
|
|
|
|
| 123 |
is_deepfake=analysis_result["is_deepfake"],
|
| 124 |
confidence=analysis_result["confidence"],
|
| 125 |
analysis_time=analysis_result["analysis_time"],
|
| 126 |
+
used_model=model,
|
| 127 |
content_type=content_type,
|
| 128 |
)
|
backend/app/core/config.py
CHANGED
|
@@ -18,11 +18,7 @@ class Settings:
|
|
| 18 |
# File handling
|
| 19 |
DOWNLOAD_TIMEOUT: int = int(os.getenv("DOWNLOAD_TIMEOUT", "30"))
|
| 20 |
MAX_FILE_SIZE: int = int(os.getenv("MAX_FILE_SIZE", str(100 * 1024 * 1024))) # 100 MB
|
| 21 |
-
|
| 22 |
-
# ML Model configuration
|
| 23 |
-
DEFAULT_DETECTOR_MODEL: str = os.getenv("DEFAULT_DETECTOR_MODEL", "mock")
|
| 24 |
-
# Supported models: "mock", "deepseek", "openai", etc. (easy to add more)
|
| 25 |
-
|
| 26 |
# Redis configuration (for future queuing)
|
| 27 |
REDIS_ENABLED: bool = os.getenv("REDIS_ENABLED", "False").lower() == "true"
|
| 28 |
REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379")
|
|
|
|
| 18 |
# File handling
|
| 19 |
DOWNLOAD_TIMEOUT: int = int(os.getenv("DOWNLOAD_TIMEOUT", "30"))
|
| 20 |
MAX_FILE_SIZE: int = int(os.getenv("MAX_FILE_SIZE", str(100 * 1024 * 1024))) # 100 MB
|
| 21 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# Redis configuration (for future queuing)
|
| 23 |
REDIS_ENABLED: bool = os.getenv("REDIS_ENABLED", "False").lower() == "true"
|
| 24 |
REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379")
|
backend/app/core/limiter.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from slowapi import Limiter
|
| 2 |
+
from slowapi.util import get_remote_address
|
| 3 |
+
|
| 4 |
+
limiter = Limiter(key_func=get_remote_address)
|
backend/app/models/schemas.py
CHANGED
|
@@ -66,7 +66,7 @@ class AnalysisResponse(BaseModel):
|
|
| 66 |
is_deepfake: bool = Field(..., description="Whether the content is detected as a deepfake")
|
| 67 |
confidence: float = Field(..., ge=0.0, le=1.0, description="Confidence score between 0.0 and 1.0")
|
| 68 |
analysis_time: float = Field(..., description="Time taken for analysis in seconds")
|
| 69 |
-
|
| 70 |
content_type: str = Field(..., description="Type of content analyzed (text/image/video/file)")
|
| 71 |
|
| 72 |
class Config:
|
|
@@ -75,7 +75,7 @@ class AnalysisResponse(BaseModel):
|
|
| 75 |
"is_deepfake": True,
|
| 76 |
"confidence": 0.847,
|
| 77 |
"analysis_time": 1.234,
|
| 78 |
-
"
|
| 79 |
"content_type": "image"
|
| 80 |
}
|
| 81 |
}
|
|
|
|
| 66 |
is_deepfake: bool = Field(..., description="Whether the content is detected as a deepfake")
|
| 67 |
confidence: float = Field(..., ge=0.0, le=1.0, description="Confidence score between 0.0 and 1.0")
|
| 68 |
analysis_time: float = Field(..., description="Time taken for analysis in seconds")
|
| 69 |
+
used_model: str = Field(..., description="The detector model that was used")
|
| 70 |
content_type: str = Field(..., description="Type of content analyzed (text/image/video/file)")
|
| 71 |
|
| 72 |
class Config:
|
|
|
|
| 75 |
"is_deepfake": True,
|
| 76 |
"confidence": 0.847,
|
| 77 |
"analysis_time": 1.234,
|
| 78 |
+
"used_model": "mock",
|
| 79 |
"content_type": "image"
|
| 80 |
}
|
| 81 |
}
|
backend/requirements.txt
CHANGED
|
@@ -9,4 +9,7 @@ torch==2.3.1
|
|
| 9 |
numpy==1.26.4
|
| 10 |
sentencepiece
|
| 11 |
protobuf
|
| 12 |
-
Pillow
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
numpy==1.26.4
|
| 10 |
sentencepiece
|
| 11 |
protobuf
|
| 12 |
+
Pillow
|
| 13 |
+
slowapi
|
| 14 |
+
pytest==7.4.3
|
| 15 |
+
pytest-asyncio==0.21.1
|
backend/run_tests.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
Simple test runner script for the Deepfake Detection Service.
|
| 4 |
+
Run this file to execute all tests with proper output formatting.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import subprocess
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def run_tests():
|
| 13 |
+
"""Run all tests with pytest."""
|
| 14 |
+
print("=" * 70)
|
| 15 |
+
print("🧪 Deepfake Detection Service - Test Suite")
|
| 16 |
+
print("=" * 70)
|
| 17 |
+
|
| 18 |
+
backend_dir = Path(__file__).parent
|
| 19 |
+
|
| 20 |
+
# Run tests with verbose output
|
| 21 |
+
cmd = [
|
| 22 |
+
sys.executable,
|
| 23 |
+
"-m",
|
| 24 |
+
"pytest",
|
| 25 |
+
"tests/",
|
| 26 |
+
"-v",
|
| 27 |
+
"--tb=short",
|
| 28 |
+
"-ra" # Show summary of all test outcomes
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
print(f"\n📝 Running command: {' '.join(cmd)}\n")
|
| 32 |
+
|
| 33 |
+
result = subprocess.run(cmd, cwd=backend_dir)
|
| 34 |
+
|
| 35 |
+
print("\n" + "=" * 70)
|
| 36 |
+
if result.returncode == 0:
|
| 37 |
+
print("✅ All tests passed!")
|
| 38 |
+
else:
|
| 39 |
+
print("❌ Some tests failed. See output above for details.")
|
| 40 |
+
print("=" * 70)
|
| 41 |
+
|
| 42 |
+
return result.returncode
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
exit_code = run_tests()
|
| 47 |
+
sys.exit(exit_code)
|
backend/test_rate_limit.sh
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Manual Testing Script for Rate Limiting (slowapi)
|
| 4 |
+
# This script demonstrates how to test the rate limiting manually
|
| 5 |
+
# Make sure the backend is running first: python main.py
|
| 6 |
+
|
| 7 |
+
API_URL="http://127.0.0.1:8000"
|
| 8 |
+
ENDPOINT="/analyze"
|
| 9 |
+
|
| 10 |
+
# Sample text for testing
|
| 11 |
+
SAMPLE_TEXT="This is a comprehensive test of the rate limiting functionality to ensure that the API properly restricts requests to one per five second interval."
|
| 12 |
+
|
| 13 |
+
# Colors for output
|
| 14 |
+
RED='\033[0;31m'
|
| 15 |
+
GREEN='\033[0;32m'
|
| 16 |
+
YELLOW='\033[1;33m'
|
| 17 |
+
BLUE='\033[0;34m'
|
| 18 |
+
NC='\033[0m' # No Color
|
| 19 |
+
|
| 20 |
+
echo -e "${BLUE}╔═══════════════════════════════════════════════════════════════════════════╗${NC}"
|
| 21 |
+
echo -e "${BLUE}║ Rate Limiting Test - Slowapi (1 request per 5 seconds) ║${NC}"
|
| 22 |
+
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════════════════════╝${NC}"
|
| 23 |
+
echo ""
|
| 24 |
+
|
| 25 |
+
# Test 1: First request (should succeed)
|
| 26 |
+
echo -e "${YELLOW}[TEST 1]${NC} First request (should succeed - HTTP 200):"
|
| 27 |
+
echo -e "${YELLOW}Command:${NC} curl -X POST $API_URL$ENDPOINT -H \"Content-Type: application/json\" -d '{...}'"
|
| 28 |
+
echo ""
|
| 29 |
+
|
| 30 |
+
RESPONSE1=$(curl -s -w "\n%{http_code}" -X POST "$API_URL$ENDPOINT" \
|
| 31 |
+
-H "Content-Type: application/json" \
|
| 32 |
+
-d "{
|
| 33 |
+
\"content_type\": \"text\",
|
| 34 |
+
\"text\": \"$SAMPLE_TEXT\"
|
| 35 |
+
}")
|
| 36 |
+
|
| 37 |
+
HTTP_CODE1=$(echo "$RESPONSE1" | tail -n 1)
|
| 38 |
+
BODY1=$(echo "$RESPONSE1" | head -n -1)
|
| 39 |
+
|
| 40 |
+
if [ "$HTTP_CODE1" == "200" ]; then
|
| 41 |
+
echo -e "${GREEN}✅ SUCCESS${NC} - HTTP $HTTP_CODE1"
|
| 42 |
+
echo -e "${GREEN}Response:${NC} (truncated) $(echo $BODY1 | head -c 100)..."
|
| 43 |
+
else
|
| 44 |
+
echo -e "${RED}❌ FAILED${NC} - HTTP $HTTP_CODE1"
|
| 45 |
+
echo -e "${RED}Response:${NC} $BODY1"
|
| 46 |
+
fi
|
| 47 |
+
echo ""
|
| 48 |
+
|
| 49 |
+
# Test 2: Immediate second request (should be rate limited)
|
| 50 |
+
echo -e "${YELLOW}[TEST 2]${NC} Immediate second request (should be rate limited - HTTP 429):"
|
| 51 |
+
echo -e "${YELLOW}Command:${NC} curl -X POST $API_URL$ENDPOINT ... (immediately)"
|
| 52 |
+
echo ""
|
| 53 |
+
|
| 54 |
+
RESPONSE2=$(curl -s -w "\n%{http_code}" -X POST "$API_URL$ENDPOINT" \
|
| 55 |
+
-H "Content-Type: application/json" \
|
| 56 |
+
-d "{
|
| 57 |
+
\"content_type\": \"text\",
|
| 58 |
+
\"text\": \"$SAMPLE_TEXT\"
|
| 59 |
+
}")
|
| 60 |
+
|
| 61 |
+
HTTP_CODE2=$(echo "$RESPONSE2" | tail -n 1)
|
| 62 |
+
BODY2=$(echo "$RESPONSE2" | head -n -1)
|
| 63 |
+
|
| 64 |
+
if [ "$HTTP_CODE2" == "429" ]; then
|
| 65 |
+
echo -e "${GREEN}✅ SUCCESS${NC} - HTTP $HTTP_CODE2 (Rate Limited as expected)"
|
| 66 |
+
echo -e "${GREEN}Response:${NC} (truncated) $(echo $BODY2 | head -c 100)..."
|
| 67 |
+
else
|
| 68 |
+
echo -e "${RED}❌ FAILED${NC} - Expected HTTP 429, got HTTP $HTTP_CODE2"
|
| 69 |
+
fi
|
| 70 |
+
echo ""
|
| 71 |
+
|
| 72 |
+
# Test 3: Wait and retry
|
| 73 |
+
echo -e "${YELLOW}[TEST 3]${NC} Wait 5 seconds and retry (should succeed - HTTP 200):"
|
| 74 |
+
echo -e "${YELLOW}Command:${NC} sleep 5 && curl -X POST $API_URL$ENDPOINT ..."
|
| 75 |
+
echo ""
|
| 76 |
+
|
| 77 |
+
echo -e "${BLUE}⏳ Waiting 5 seconds...${NC}"
|
| 78 |
+
for i in {1..5}; do
|
| 79 |
+
echo -ne "\r⏳ Waiting $i/5 seconds..."
|
| 80 |
+
sleep 1
|
| 81 |
+
done
|
| 82 |
+
echo ""
|
| 83 |
+
|
| 84 |
+
RESPONSE3=$(curl -s -w "\n%{http_code}" -X POST "$API_URL$ENDPOINT" \
|
| 85 |
+
-H "Content-Type: application/json" \
|
| 86 |
+
-d "{
|
| 87 |
+
\"content_type\": \"text\",
|
| 88 |
+
\"text\": \"$SAMPLE_TEXT\"
|
| 89 |
+
}")
|
| 90 |
+
|
| 91 |
+
HTTP_CODE3=$(echo "$RESPONSE3" | tail -n 1)
|
| 92 |
+
BODY3=$(echo "$RESPONSE3" | head -n -1)
|
| 93 |
+
|
| 94 |
+
if [ "$HTTP_CODE3" == "200" ]; then
|
| 95 |
+
echo -e "${GREEN}✅ SUCCESS${NC} - HTTP $HTTP_CODE3 (Rate limit recovered)"
|
| 96 |
+
echo -e "${GREEN}Response:${NC} (truncated) $(echo $BODY3 | head -c 100)..."
|
| 97 |
+
else
|
| 98 |
+
echo -e "${RED}❌ FAILED${NC} - Expected HTTP 200, got HTTP $HTTP_CODE3"
|
| 99 |
+
fi
|
| 100 |
+
echo ""
|
| 101 |
+
|
| 102 |
+
# Summary
|
| 103 |
+
echo -e "${BLUE}╔═══════════════════════════════════════════════════════════════════════════╗${NC}"
|
| 104 |
+
echo -e "${BLUE}║ TEST SUMMARY ║${NC}"
|
| 105 |
+
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════════════════════╝${NC}"
|
| 106 |
+
echo ""
|
| 107 |
+
|
| 108 |
+
PASSED=0
|
| 109 |
+
FAILED=0
|
| 110 |
+
|
| 111 |
+
if [ "$HTTP_CODE1" == "200" ]; then
|
| 112 |
+
echo -e "${GREEN}✅${NC} Test 1 (First request): PASSED"
|
| 113 |
+
PASSED=$((PASSED + 1))
|
| 114 |
+
else
|
| 115 |
+
echo -e "${RED}❌${NC} Test 1 (First request): FAILED"
|
| 116 |
+
FAILED=$((FAILED + 1))
|
| 117 |
+
fi
|
| 118 |
+
|
| 119 |
+
if [ "$HTTP_CODE2" == "429" ]; then
|
| 120 |
+
echo -e "${GREEN}✅${NC} Test 2 (Rate limited): PASSED"
|
| 121 |
+
PASSED=$((PASSED + 1))
|
| 122 |
+
else
|
| 123 |
+
echo -e "${RED}❌${NC} Test 2 (Rate limited): FAILED"
|
| 124 |
+
FAILED=$((FAILED + 1))
|
| 125 |
+
fi
|
| 126 |
+
|
| 127 |
+
if [ "$HTTP_CODE3" == "200" ]; then
|
| 128 |
+
echo -e "${GREEN}✅${NC} Test 3 (Recovery): PASSED"
|
| 129 |
+
PASSED=$((PASSED + 1))
|
| 130 |
+
else
|
| 131 |
+
echo -e "${RED}❌${NC} Test 3 (Recovery): FAILED"
|
| 132 |
+
FAILED=$((FAILED + 1))
|
| 133 |
+
fi
|
| 134 |
+
|
| 135 |
+
echo ""
|
| 136 |
+
echo -e "Results: ${GREEN}$PASSED passed${NC}, ${RED}$FAILED failed${NC}"
|
| 137 |
+
echo ""
|
| 138 |
+
|
| 139 |
+
# Additional manual test options
|
| 140 |
+
echo -e "${BLUE}Additional Manual Tests:${NC}"
|
| 141 |
+
echo ""
|
| 142 |
+
echo "1. Test with different IPs (requires proxy or localhost simulation):"
|
| 143 |
+
echo " This would test that rate limiting is per-IP"
|
| 144 |
+
echo ""
|
| 145 |
+
echo "2. Test different rate limit thresholds:"
|
| 146 |
+
echo " Modify @limiter.limit(\"1/5seconds\") in routes.py to test different rates"
|
| 147 |
+
echo ""
|
| 148 |
+
echo "3. Test health endpoint (no rate limit):"
|
| 149 |
+
echo " curl -X GET http://127.0.0.1:8000/"
|
| 150 |
+
echo ""
|
| 151 |
+
|
| 152 |
+
# Health check (no rate limit)
|
| 153 |
+
echo -e "${YELLOW}[BONUS]${NC} Testing health endpoint (should have no rate limit):"
|
| 154 |
+
HEALTH_RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "$API_URL/")
|
| 155 |
+
HEALTH_CODE=$(echo "$HEALTH_RESPONSE" | tail -n 1)
|
| 156 |
+
|
| 157 |
+
if [ "$HEALTH_CODE" == "200" ]; then
|
| 158 |
+
echo -e "${GREEN}✅ Health check: PASSED (HTTP $HEALTH_CODE)${NC}"
|
| 159 |
+
else
|
| 160 |
+
echo -e "${RED}❌ Health check: FAILED (HTTP $HEALTH_CODE)${NC}"
|
| 161 |
+
fi
|
backend/tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Tests package for Deepfake Detection Service."""
|
backend/tests/conftest.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pytest configuration for the Deepfake Detection Service tests.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
# Add the backend directory to the Python path
|
| 9 |
+
backend_dir = Path(__file__).parent.parent
|
| 10 |
+
sys.path.insert(0, str(backend_dir))
|
| 11 |
+
|
| 12 |
+
import pytest
|
| 13 |
+
from fastapi.testclient import TestClient
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def test_client():
|
| 18 |
+
"""Provide a test client for API testing."""
|
| 19 |
+
from app import app
|
| 20 |
+
return TestClient(app)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.fixture
|
| 24 |
+
def sample_texts():
|
| 25 |
+
"""Provide sample text data for testing."""
|
| 26 |
+
return {
|
| 27 |
+
"ai_generated": "This is an AI-generated text that demonstrates the capabilities of modern language models in creating coherent and contextually appropriate content without human intervention.",
|
| 28 |
+
"human_written": "I went to the store yesterday and bought some groceries. The weather was nice, and I enjoyed the walk.",
|
| 29 |
+
"technical": "The implementation of neural networks requires careful consideration of hyperparameters, activation functions, and optimization techniques to achieve optimal performance.",
|
| 30 |
+
"short": "Too short",
|
| 31 |
+
"long": "A" * 5001, # Exceeds 5000 char limit
|
| 32 |
+
"minimum": "A" * 50, # Exactly 50 chars (minimum valid)
|
| 33 |
+
}
|
backend/tests/test_analysis.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Comprehensive tests for the Deepfake Detection Service.
|
| 3 |
+
Tests cover: text analysis, rate limiting, response validation, and Redis integration.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import pytest
|
| 8 |
+
from fastapi.testclient import TestClient
|
| 9 |
+
from unittest.mock import patch, AsyncMock, MagicMock
|
| 10 |
+
|
| 11 |
+
from app import app
|
| 12 |
+
from app.services.text_analyzer import analyze_text
|
| 13 |
+
from app.services.queue import get_queue_service
|
| 14 |
+
from app.models.schemas import TextAnalysisRequest, AnalysisResponse
|
| 15 |
+
from app.core.limiter import limiter
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
client = TestClient(app)
|
| 19 |
+
|
| 20 |
+
@pytest.fixture(autouse=True)
|
| 21 |
+
def reset_rate_limits():
|
| 22 |
+
"""
|
| 23 |
+
Automatyczny fixture, który przed KAŻDYM testem
|
| 24 |
+
czyści pamięć limitera zapytań SlowAPI.
|
| 25 |
+
Dzięki temu testy nie blokują się nawzajem błędem 429.
|
| 26 |
+
"""
|
| 27 |
+
limiter._storage.reset()
|
| 28 |
+
|
| 29 |
+
class TestTextAnalysis:
|
| 30 |
+
"""Test text deepfake analysis functionality."""
|
| 31 |
+
|
| 32 |
+
def test_health_check(self):
|
| 33 |
+
"""Test health check endpoint returns correct status."""
|
| 34 |
+
response = client.get("/")
|
| 35 |
+
assert response.status_code == 200
|
| 36 |
+
data = response.json()
|
| 37 |
+
assert data["status"] in ["ok", "degraded"]
|
| 38 |
+
assert data["service"] == "Deepfake Detection Service"
|
| 39 |
+
assert "available_models" in data
|
| 40 |
+
assert "text" in data["supported_types"]
|
| 41 |
+
assert "image" in data["supported_types"]
|
| 42 |
+
|
| 43 |
+
def test_text_analysis_valid_input(self):
|
| 44 |
+
"""Test text analysis with valid AI-generated text."""
|
| 45 |
+
payload = {
|
| 46 |
+
"content_type": "text",
|
| 47 |
+
"text": "This is an AI-generated text that demonstrates the capabilities of modern language models in creating coherent and contextually appropriate content without human intervention."
|
| 48 |
+
}
|
| 49 |
+
response = client.post("/analyze", json=payload)
|
| 50 |
+
|
| 51 |
+
assert response.status_code == 200
|
| 52 |
+
data = response.json()
|
| 53 |
+
|
| 54 |
+
# Validate response structure
|
| 55 |
+
assert "is_deepfake" in data
|
| 56 |
+
assert isinstance(data["is_deepfake"], bool)
|
| 57 |
+
assert "confidence" in data
|
| 58 |
+
assert 0.0 <= data["confidence"] <= 1.0
|
| 59 |
+
assert "analysis_time" in data
|
| 60 |
+
assert data["analysis_time"] > 0
|
| 61 |
+
assert "used_model" in data
|
| 62 |
+
assert data["content_type"] == "text"
|
| 63 |
+
assert "yaya36095/xlm-roberta-text-detector" in data["used_model"]
|
| 64 |
+
|
| 65 |
+
def test_text_analysis_human_written(self):
|
| 66 |
+
"""Test text analysis with human-written text."""
|
| 67 |
+
payload = {
|
| 68 |
+
"content_type": "text",
|
| 69 |
+
"text": "I went to the store yesterday and bought some groceries. The weather was nice, and I enjoyed the walk. I also met an old friend who I haven't seen in years. We talked about our lives and made plans to meet again soon."
|
| 70 |
+
}
|
| 71 |
+
response = client.post("/analyze", json=payload)
|
| 72 |
+
|
| 73 |
+
assert response.status_code == 200
|
| 74 |
+
data = response.json()
|
| 75 |
+
assert isinstance(data["is_deepfake"], bool)
|
| 76 |
+
assert 0.0 <= data["confidence"] <= 1.0
|
| 77 |
+
|
| 78 |
+
def test_text_analysis_too_short(self):
|
| 79 |
+
"""Test text analysis with text that's too short (< 50 chars)."""
|
| 80 |
+
payload = {
|
| 81 |
+
"content_type": "text",
|
| 82 |
+
"text": "Short text"
|
| 83 |
+
}
|
| 84 |
+
response = client.post("/analyze", json=payload)
|
| 85 |
+
|
| 86 |
+
assert response.status_code == 400
|
| 87 |
+
data = response.json()
|
| 88 |
+
assert "at least 50 characters" in data["detail"]
|
| 89 |
+
|
| 90 |
+
def test_text_analysis_too_long(self):
|
| 91 |
+
"""Test text analysis with text that exceeds max length."""
|
| 92 |
+
payload = {
|
| 93 |
+
"content_type": "text",
|
| 94 |
+
"text": "A" * 5001 # Exceeds 5000 character limit
|
| 95 |
+
}
|
| 96 |
+
response = client.post("/analyze", json=payload)
|
| 97 |
+
|
| 98 |
+
assert response.status_code == 400
|
| 99 |
+
data = response.json()
|
| 100 |
+
assert "exceeds maximum length" in data["detail"]
|
| 101 |
+
|
| 102 |
+
def test_text_analysis_exactly_50_chars(self):
|
| 103 |
+
"""Test text analysis with exactly 50 characters (minimum valid)."""
|
| 104 |
+
text_50_chars = "A" * 50
|
| 105 |
+
payload = {
|
| 106 |
+
"content_type": "text",
|
| 107 |
+
"text": text_50_chars
|
| 108 |
+
}
|
| 109 |
+
response = client.post("/analyze", json=payload)
|
| 110 |
+
|
| 111 |
+
# Should either succeed or fail based on model behavior
|
| 112 |
+
# but not because of length validation
|
| 113 |
+
assert response.status_code in [200, 500] # Success or model error, not validation error
|
| 114 |
+
|
| 115 |
+
def test_text_analysis_empty_text(self):
|
| 116 |
+
"""Test text analysis with empty text."""
|
| 117 |
+
payload = {
|
| 118 |
+
"content_type": "text",
|
| 119 |
+
"text": ""
|
| 120 |
+
}
|
| 121 |
+
response = client.post("/analyze", json=payload)
|
| 122 |
+
|
| 123 |
+
assert response.status_code == 400
|
| 124 |
+
|
| 125 |
+
def test_text_analysis_missing_field(self):
|
| 126 |
+
"""Test text analysis with missing text field."""
|
| 127 |
+
payload = {
|
| 128 |
+
"content_type": "text"
|
| 129 |
+
}
|
| 130 |
+
response = client.post("/analyze", json=payload)
|
| 131 |
+
|
| 132 |
+
assert response.status_code == 422 # Validation error
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class TestRateLimiting:
|
| 136 |
+
"""Test rate limiting (slowapi) functionality."""
|
| 137 |
+
|
| 138 |
+
def test_rate_limit_single_request(self):
|
| 139 |
+
"""Test that a single request is allowed."""
|
| 140 |
+
payload = {
|
| 141 |
+
"content_type": "text",
|
| 142 |
+
"text": "This is a test text with sufficient length to pass validation and be analyzed by the deepfake detector model."
|
| 143 |
+
}
|
| 144 |
+
response = client.post("/analyze", json=payload)
|
| 145 |
+
|
| 146 |
+
assert response.status_code in [200, 500] # Should not be rate limited
|
| 147 |
+
assert response.status_code != 429
|
| 148 |
+
|
| 149 |
+
def test_rate_limit_multiple_rapid_requests(self):
|
| 150 |
+
"""Test that rapid requests are rate limited (1 per 5 seconds)."""
|
| 151 |
+
payload = {
|
| 152 |
+
"content_type": "text",
|
| 153 |
+
"text": "This is a test text with sufficient length to pass validation and be analyzed by the deepfake detector model."
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
# First request should succeed
|
| 157 |
+
response1 = client.post("/analyze", json=payload)
|
| 158 |
+
assert response1.status_code != 429
|
| 159 |
+
|
| 160 |
+
# Immediate second request should be rate limited
|
| 161 |
+
response2 = client.post("/analyze", json=payload)
|
| 162 |
+
assert response2.status_code == 429
|
| 163 |
+
assert "rate limit" in response2.text.lower()
|
| 164 |
+
|
| 165 |
+
def test_rate_limit_recovery_after_delay(self):
|
| 166 |
+
"""Test that rate limit recovers after 5 seconds."""
|
| 167 |
+
payload = {
|
| 168 |
+
"content_type": "text",
|
| 169 |
+
"text": "This is a test text with sufficient length to pass validation and be analyzed by the deepfake detector model."
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
# First request
|
| 173 |
+
response1 = client.post("/analyze", json=payload)
|
| 174 |
+
first_status = response1.status_code
|
| 175 |
+
|
| 176 |
+
# Wait for rate limit to reset (5+ seconds)
|
| 177 |
+
import time
|
| 178 |
+
time.sleep(5.1)
|
| 179 |
+
|
| 180 |
+
# Second request should now be allowed
|
| 181 |
+
response2 = client.post("/analyze", json=payload)
|
| 182 |
+
assert response2.status_code != 429
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class TestResponseValidation:
|
| 186 |
+
"""Test response structure and validation."""
|
| 187 |
+
|
| 188 |
+
def test_response_includes_all_fields(self):
|
| 189 |
+
"""Test that response includes all required fields."""
|
| 190 |
+
payload = {
|
| 191 |
+
"content_type": "text",
|
| 192 |
+
"text": "This is a comprehensive test to ensure the response includes all necessary fields for proper API usage and data handling requirements."
|
| 193 |
+
}
|
| 194 |
+
response = client.post("/analyze", json=payload)
|
| 195 |
+
|
| 196 |
+
if response.status_code == 200:
|
| 197 |
+
data = response.json()
|
| 198 |
+
required_fields = ["is_deepfake", "confidence", "analysis_time", "used_model", "content_type"]
|
| 199 |
+
for field in required_fields:
|
| 200 |
+
assert field in data, f"Missing required field: {field}"
|
| 201 |
+
|
| 202 |
+
def test_response_confidence_range(self):
|
| 203 |
+
"""Test that confidence score is between 0.0 and 1.0."""
|
| 204 |
+
payload = {
|
| 205 |
+
"content_type": "text",
|
| 206 |
+
"text": "This is another test to verify that the confidence score is properly normalized between zero and one for consistent API behavior."
|
| 207 |
+
}
|
| 208 |
+
response = client.post("/analyze", json=payload)
|
| 209 |
+
|
| 210 |
+
if response.status_code == 200:
|
| 211 |
+
data = response.json()
|
| 212 |
+
assert 0.0 <= data["confidence"] <= 1.0
|
| 213 |
+
|
| 214 |
+
def test_response_analysis_time_positive(self):
|
| 215 |
+
"""Test that analysis_time is positive."""
|
| 216 |
+
payload = {
|
| 217 |
+
"content_type": "text",
|
| 218 |
+
"text": "Testing the analysis time tracking to ensure it records valid positive durations for performance monitoring purposes."
|
| 219 |
+
}
|
| 220 |
+
response = client.post("/analyze", json=payload)
|
| 221 |
+
|
| 222 |
+
if response.status_code == 200:
|
| 223 |
+
data = response.json()
|
| 224 |
+
assert data["analysis_time"] > 0
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class TestRedisIntegration:
|
| 228 |
+
"""Test Redis queue integration."""
|
| 229 |
+
|
| 230 |
+
def test_queue_service_initialization(self):
|
| 231 |
+
"""Test that queue service initializes correctly."""
|
| 232 |
+
queue_service = get_queue_service()
|
| 233 |
+
assert queue_service is not None
|
| 234 |
+
|
| 235 |
+
def test_queue_service_singleton(self):
|
| 236 |
+
"""Test that queue service is a singleton."""
|
| 237 |
+
queue_service1 = get_queue_service()
|
| 238 |
+
queue_service2 = get_queue_service()
|
| 239 |
+
assert queue_service1 is queue_service2
|
| 240 |
+
|
| 241 |
+
@pytest.mark.asyncio
|
| 242 |
+
async def test_enqueue_analysis_task(self):
|
| 243 |
+
"""Test enqueuing an analysis task."""
|
| 244 |
+
queue_service = get_queue_service()
|
| 245 |
+
|
| 246 |
+
result = await queue_service.enqueue_analysis(
|
| 247 |
+
file_url="https://example.com/text.txt",
|
| 248 |
+
model="yaya36095/xlm-roberta-text-detector",
|
| 249 |
+
task_id="test_task_001"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
assert result is True
|
| 253 |
+
|
| 254 |
+
@pytest.mark.asyncio
|
| 255 |
+
async def test_get_task_result(self):
|
| 256 |
+
"""Test retrieving task result from queue."""
|
| 257 |
+
queue_service = get_queue_service()
|
| 258 |
+
|
| 259 |
+
# Try to get a non-existent result
|
| 260 |
+
result = await queue_service.get_task_result("non_existent_task")
|
| 261 |
+
|
| 262 |
+
# Should return None for non-existent task
|
| 263 |
+
assert result is None
|
| 264 |
+
|
| 265 |
+
def test_redis_config_available(self):
|
| 266 |
+
"""Test that Redis config is available."""
|
| 267 |
+
from app.core.config import get_settings
|
| 268 |
+
settings = get_settings()
|
| 269 |
+
|
| 270 |
+
assert hasattr(settings, "REDIS_ENABLED")
|
| 271 |
+
assert hasattr(settings, "REDIS_URL")
|
| 272 |
+
assert hasattr(settings, "REDIS_QUEUE_NAME")
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class TestAsyncTextAnalyzer:
|
| 276 |
+
"""Test async text analyzer directly."""
|
| 277 |
+
|
| 278 |
+
@pytest.mark.asyncio
|
| 279 |
+
async def test_analyze_text_valid_input(self):
|
| 280 |
+
"""Test analyze_text function with valid input."""
|
| 281 |
+
text = "This is a comprehensive test of the async text analyzer to ensure it properly processes input and returns valid results."
|
| 282 |
+
|
| 283 |
+
result = await analyze_text(text)
|
| 284 |
+
|
| 285 |
+
assert isinstance(result, dict)
|
| 286 |
+
assert "is_deepfake" in result
|
| 287 |
+
assert "confidence" in result
|
| 288 |
+
assert "analysis_time" in result
|
| 289 |
+
assert isinstance(result["is_deepfake"], bool)
|
| 290 |
+
assert isinstance(result["confidence"], float)
|
| 291 |
+
assert 0.0 <= result["confidence"] <= 1.0
|
| 292 |
+
|
| 293 |
+
@pytest.mark.asyncio
|
| 294 |
+
async def test_analyze_text_multiple_calls(self):
|
| 295 |
+
"""Test that analyze_text can be called multiple times (model caching)."""
|
| 296 |
+
text1 = "First test text that should be analyzed by the model to verify it works correctly on multiple invocations."
|
| 297 |
+
text2 = "Second test text to ensure the model remains loaded in memory for subsequent analysis operations."
|
| 298 |
+
|
| 299 |
+
result1 = await analyze_text(text1)
|
| 300 |
+
result2 = await analyze_text(text2)
|
| 301 |
+
|
| 302 |
+
assert result1 is not None
|
| 303 |
+
assert result2 is not None
|
| 304 |
+
assert "confidence" in result1
|
| 305 |
+
assert "confidence" in result2
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class TestErrorHandling:
|
| 309 |
+
"""Test error handling in endpoints."""
|
| 310 |
+
|
| 311 |
+
def test_unsupported_content_type(self):
|
| 312 |
+
"""Test handling of unsupported content type."""
|
| 313 |
+
payload = {
|
| 314 |
+
"content_type": "unsupported_type",
|
| 315 |
+
"data": "some data"
|
| 316 |
+
}
|
| 317 |
+
response = client.post("/analyze", json=payload)
|
| 318 |
+
|
| 319 |
+
assert response.status_code in [415, 422] # Unsupported media type or validation error
|
| 320 |
+
|
| 321 |
+
def test_malformed_json(self):
|
| 322 |
+
"""Test handling of malformed JSON."""
|
| 323 |
+
response = client.post(
|
| 324 |
+
"/analyze",
|
| 325 |
+
content="not valid json",
|
| 326 |
+
headers={"Content-Type": "application/json"}
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
assert response.status_code == 422
|
| 330 |
+
|
| 331 |
+
def test_invalid_content_type_header(self):
|
| 332 |
+
"""Test handling of invalid Content-Type header."""
|
| 333 |
+
payload = {
|
| 334 |
+
"content_type": "text",
|
| 335 |
+
"text": "Valid test text with sufficient length to be properly analyzed and validated by the system."
|
| 336 |
+
}
|
| 337 |
+
response = client.post(
|
| 338 |
+
"/analyze",
|
| 339 |
+
json=payload,
|
| 340 |
+
headers={"Content-Type": "text/plain"}
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
# Should still work as FastAPI is lenient
|
| 344 |
+
assert response.status_code in [200, 422, 400, 415, 500]
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
if __name__ == "__main__":
|
| 348 |
+
pytest.main([__file__, "-v", "--tb=short"])
|
index.js
CHANGED
|
@@ -284,7 +284,7 @@ async function handleAnalysis(interaction, userContent, targetMessage = null) {
|
|
| 284 |
.addFields(
|
| 285 |
{ name: "Pewność modelu", value: `\`${confidencePercent}%\` \n${progressBar}` },
|
| 286 |
{ name: "Czas przetwarzania", value: `\`${data.analysis_time.toFixed(3)}s\``, inline: true },
|
| 287 |
-
{ name: "Użyty model", value: `\`${data.
|
| 288 |
{ name: "Format danych", value: `\`${data.content_type.toUpperCase()}\``, inline: true }
|
| 289 |
)
|
| 290 |
.setTimestamp()
|
|
|
|
| 284 |
.addFields(
|
| 285 |
{ name: "Pewność modelu", value: `\`${confidencePercent}%\` \n${progressBar}` },
|
| 286 |
{ name: "Czas przetwarzania", value: `\`${data.analysis_time.toFixed(3)}s\``, inline: true },
|
| 287 |
+
{ name: "Użyty model", value: `\`${data.used_model}\``, inline: true },
|
| 288 |
{ name: "Format danych", value: `\`${data.content_type.toUpperCase()}\``, inline: true }
|
| 289 |
)
|
| 290 |
.setTimestamp()
|