File size: 7,872 Bytes
6bed18e | 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 | #!/usr/bin/env python3
"""
Quickstart validation script for the Todo API backend
This script validates that all core functionality works as expected
"""
import subprocess
import sys
import time
import requests
import json
from datetime import datetime, timedelta
from jose import jwt
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__)))
from src.core.config import settings
def validate_project_structure():
"""Validate that all required project files and directories exist"""
print("π Validating project structure...")
required_files = [
"src/main.py",
"src/models/task.py",
"src/services/task_service.py",
"src/api/v1/tasks.py",
"src/auth/security.py",
"src/auth/deps.py",
"src/core/config.py",
"src/core/database.py",
"requirements.txt"
]
missing_files = []
for file in required_files:
full_path = f"./{file}"
try:
with open(full_path, 'r'):
pass
except FileNotFoundError:
missing_files.append(full_path)
if missing_files:
print(f"β Missing required files: {missing_files}")
return False
print("β
All required files exist")
return True
def validate_dependencies():
"""Validate that all required dependencies are available"""
print("π Validating dependencies...")
try:
import fastapi
import sqlmodel
import jose
import pydantic
print("β
All required dependencies are available")
return True
except ImportError as e:
print(f"β Missing dependency: {e}")
return False
def validate_config():
"""Validate that configuration is properly set up"""
print("π Validating configuration...")
try:
# Check that settings object has required attributes
assert hasattr(settings, 'DATABASE_URL'), "DATABASE_URL not configured"
assert hasattr(settings, 'SECRET_KEY'), "SECRET_KEY not configured"
assert hasattr(settings, 'JWT_ALGORITHM'), "JWT_ALGORITHM not configured"
assert hasattr(settings, 'JWT_EXPIRATION_DELTA'), "JWT_EXPIRATION_DELTA not configured"
print("β
Configuration is properly set up")
return True
except AssertionError as e:
print(f"β Configuration error: {e}")
return False
def validate_token_functionality():
"""Validate JWT token creation and verification functionality"""
print("π Validating token functionality...")
try:
# Create a test token
test_data = {"user_id": "test_user_123", "role": "user"}
from src.auth.security import create_access_token, verify_token
token = create_access_token(data=test_data)
assert token is not None, "Token creation failed"
assert isinstance(token, str), "Token should be a string"
assert len(token) > 0, "Token should not be empty"
# Verify the token
payload = verify_token(token)
assert payload is not None, "Token verification failed"
assert payload["user_id"] == "test_user_123", "User ID mismatch in payload"
assert payload["role"] == "user", "Role mismatch in payload"
assert "exp" in payload, "Expiration not in payload"
print("β
Token functionality works correctly")
return True
except Exception as e:
print(f"β Token functionality error: {e}")
return False
def validate_models():
"""Validate that the data models are properly defined"""
print("π Validating data models...")
try:
from src.models.task import Task, TaskCreate, TaskUpdate, TaskResponse
# Test creating a task model instance
task_create = TaskCreate(
title="Test task",
description="Test description",
user_id="test_user_123"
)
assert task_create.title == "Test task"
assert task_create.user_id == "test_user_123"
print("β
Data models are properly defined")
return True
except Exception as e:
print(f"β Data model error: {e}")
return False
def validate_services():
"""Validate that the service layer is properly implemented"""
print("π Validating service layer...")
try:
from src.services.task_service import TaskService
# Just check that the service class exists and has required methods
assert hasattr(TaskService, 'create_task'), "create_task method missing"
assert hasattr(TaskService, 'get_tasks_by_user_id'), "get_tasks_by_user_id method missing"
assert hasattr(TaskService, 'update_task'), "update_task method missing"
assert hasattr(TaskService, 'delete_task'), "delete_task method missing"
assert hasattr(TaskService, 'toggle_task_completion'), "toggle_task_completion method missing"
print("β
Service layer is properly implemented")
return True
except Exception as e:
print(f"β Service layer error: {e}")
return False
def validate_api_endpoints():
"""Validate that API endpoints are properly defined"""
print("π Validating API endpoints...")
try:
from src.api.v1.tasks import router
# Check that the router is properly defined
assert router is not None, "API router not defined"
print("β
API endpoints are properly defined")
return True
except Exception as e:
print(f"β API endpoint error: {e}")
return False
def validate_logging():
"""Validate that logging functionality works"""
print("π Validating logging functionality...")
try:
from src.core.logging import log_operation, log_error, log_authentication_event, log_authorization_decision, log_token_validation_result
# Test logging functions
log_operation("QUICKSTART_TEST_OPERATION", user_id="test_user")
log_authentication_event("QUICKSTART_TEST", user_id="test_user")
log_authorization_decision("read", "test_user", "task_123", True)
log_token_validation_result("QUICKSTART_VALID", user_id="test_user")
print("β
Logging functionality works")
return True
except Exception as e:
print(f"β Logging error: {e}")
return False
def run_complete_validation():
"""Run all validation checks"""
print("π Starting quickstart validation for Todo API Backend...\n")
all_checks = [
("Project Structure", validate_project_structure),
("Dependencies", validate_dependencies),
("Configuration", validate_config),
("Token Functionality", validate_token_functionality),
("Data Models", validate_models),
("Service Layer", validate_services),
("API Endpoints", validate_api_endpoints),
("Logging", validate_logging)
]
results = []
for check_name, check_func in all_checks:
print(f"\nπ {check_name} check:")
result = check_func()
results.append((check_name, result))
print(f"\nπ Validation Summary:")
total_checks = len(results)
passed_checks = sum(1 for _, result in results if result)
failed_checks = total_checks - passed_checks
for check_name, result in results:
status = "β
PASS" if result else "β FAIL"
print(f" {status}: {check_name}")
print(f"\nπ Total: {total_checks}, Passed: {passed_checks}, Failed: {failed_checks}")
if failed_checks == 0:
print("\nπ All validation checks passed! The Todo API backend is ready for use.")
return True
else:
print(f"\nβ οΈ {failed_checks} validation checks failed. Please review the issues above.")
return False
if __name__ == "__main__":
success = run_complete_validation()
sys.exit(0 if success else 1) |