Spaces:
Sleeping
Sleeping
| """ | |
| Tests for Authentication System | |
| """ | |
| import pytest | |
| from fastapi.testclient import TestClient | |
| from app.main import app | |
| from app.models import Base, engine, User, SessionLocal | |
| from app.core.security import get_password_hash | |
| # Reset DB for tests | |
| def setup_db(): | |
| Base.metadata.create_all(bind=engine) | |
| yield | |
| # Base.metadata.drop_all(bind=engine) # Optional cleanup | |
| class TestAuth: | |
| def client(self): | |
| return TestClient(app) | |
| def test_user(self): | |
| """Create a test user directly in DB""" | |
| db = SessionLocal() | |
| email = "test@example.com" | |
| # Check if exists | |
| user = db.query(User).filter(User.email == email).first() | |
| if not user: | |
| user = User( | |
| email=email, | |
| hashed_password=get_password_hash("password123"), | |
| full_name="Test User" | |
| ) | |
| db.add(user) | |
| db.commit() | |
| db.refresh(user) | |
| db.close() | |
| return user | |
| def test_register_user(self, client): | |
| """Test user registration endpoint""" | |
| response = client.post( | |
| "/api/v1/auth/register", | |
| json={ | |
| "email": "newuser@example.com", | |
| "password": "securepassword", | |
| "full_name": "New User" | |
| } | |
| ) | |
| if response.status_code == 400: | |
| # Might already exist from previous run | |
| assert response.json()["detail"] == "Email already registered" | |
| else: | |
| assert response.status_code == 200 | |
| data = response.json() | |
| assert data["email"] == "newuser@example.com" | |
| assert "id" in data | |
| def test_login_success(self, client, test_user): | |
| """Test login with correct credentials""" | |
| response = client.post( | |
| "/api/v1/auth/login", | |
| data={ | |
| "username": "test@example.com", | |
| "password": "password123" | |
| } | |
| ) | |
| assert response.status_code == 200 | |
| data = response.json() | |
| assert "access_token" in data | |
| assert data["token_type"] == "bearer" | |
| def test_login_failure(self, client): | |
| """Test login with wrong password""" | |
| response = client.post( | |
| "/api/v1/auth/login", | |
| data={ | |
| "username": "test@example.com", | |
| "password": "wrongpassword" | |
| } | |
| ) | |
| assert response.status_code == 401 | |
| def test_create_api_key(self, client, test_user): | |
| """Test creating an API key (requires auth)""" | |
| # First login | |
| login_res = client.post( | |
| "/api/v1/auth/login", | |
| data={"username": "test@example.com", "password": "password123"} | |
| ) | |
| token = login_res.json()["access_token"] | |
| # Create key | |
| response = client.post( | |
| "/api/v1/auth/api-keys", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| json={"name": "Test Key"} | |
| ) | |
| assert response.status_code == 200 | |
| data = response.json() | |
| assert data["name"] == "Test Key" | |
| assert data["key"].startswith("vf_") | |