92 lines
2.6 KiB
Python
92 lines
2.6 KiB
Python
# tests/fixtures/auth_fixtures.py
|
|
import uuid
|
|
|
|
import pytest
|
|
|
|
from middleware.auth import AuthManager
|
|
from models.database_models import User
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def auth_manager():
|
|
"""Create auth manager instance (session scope since it's stateless)"""
|
|
return AuthManager()
|
|
|
|
|
|
@pytest.fixture
|
|
def test_user(db, auth_manager):
|
|
"""Create a test user with unique username"""
|
|
unique_id = str(uuid.uuid4())[:8] # Short unique identifier
|
|
hashed_password = auth_manager.hash_password("testpass123")
|
|
user = User(
|
|
email=f"test_{unique_id}@example.com",
|
|
username=f"testuser_{unique_id}",
|
|
hashed_password=hashed_password,
|
|
role="user",
|
|
is_active=True,
|
|
)
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
@pytest.fixture
|
|
def test_admin(db, auth_manager):
|
|
"""Create a test admin user with unique username"""
|
|
unique_id = str(uuid.uuid4())[:8] # Short unique identifier
|
|
hashed_password = auth_manager.hash_password("adminpass123")
|
|
admin = User(
|
|
email=f"admin_{unique_id}@example.com",
|
|
username=f"admin_{unique_id}",
|
|
hashed_password=hashed_password,
|
|
role="admin",
|
|
is_active=True,
|
|
)
|
|
db.add(admin)
|
|
db.commit()
|
|
db.refresh(admin)
|
|
return admin
|
|
|
|
|
|
@pytest.fixture
|
|
def other_user(db, auth_manager):
|
|
"""Create a different user for testing access controls"""
|
|
unique_id = str(uuid.uuid4())[:8]
|
|
hashed_password = auth_manager.hash_password("otherpass123")
|
|
user = User(
|
|
email=f"other_{unique_id}@example.com",
|
|
username=f"otheruser_{unique_id}",
|
|
hashed_password=hashed_password,
|
|
role="user",
|
|
is_active=True,
|
|
)
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
@pytest.fixture
|
|
def auth_headers(client, test_user):
|
|
"""Get authentication headers for test user"""
|
|
response = client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": test_user.username, "password": "testpass123"},
|
|
)
|
|
assert response.status_code == 200, f"Login failed: {response.text}"
|
|
token = response.json()["access_token"]
|
|
return {"Authorization": f"Bearer {token}"}
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_headers(client, test_admin):
|
|
"""Get authentication headers for admin user"""
|
|
response = client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": test_admin.username, "password": "adminpass123"},
|
|
)
|
|
assert response.status_code == 200, f"Admin login failed: {response.text}"
|
|
token = response.json()["access_token"]
|
|
return {"Authorization": f"Bearer {token}"}
|