import asyncio from types import SimpleNamespace from unittest.mock import AsyncMock import pytest from fastapi import HTTPException from app.auth import dependencies from app.core.security import create_access_token, create_refresh_token from tests.conftest import make_user def test_get_db_returns_app_state_db(): request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(db="db-instance"))) result = asyncio.run(dependencies.get_db(request)) assert result == "db-instance" def test_get_db_raises_when_database_missing(): request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace())) with pytest.raises(HTTPException) as exc_info: asyncio.run(dependencies.get_db(request)) assert exc_info.value.status_code == 503 assert exc_info.value.detail == "Database not initialized" def test_get_current_user_accepts_valid_access_token(): repo = SimpleNamespace(get_user_by_username=AsyncMock(return_value=make_user())) result = asyncio.run( dependencies.get_current_user( token=create_access_token("tester"), user_repo=repo, ) ) assert result.username == "tester" repo.get_user_by_username.assert_awaited_once_with("tester") def test_get_current_user_rejects_refresh_token(): repo = SimpleNamespace(get_user_by_username=AsyncMock()) with pytest.raises(HTTPException) as exc_info: asyncio.run( dependencies.get_current_user( token=create_refresh_token("tester"), user_repo=repo, ) ) assert exc_info.value.status_code == 401 assert exc_info.value.detail == "Invalid token type. Access token required." repo.get_user_by_username.assert_not_awaited() def test_get_current_user_rejects_missing_user(): repo = SimpleNamespace(get_user_by_username=AsyncMock(return_value=None)) with pytest.raises(HTTPException) as exc_info: asyncio.run( dependencies.get_current_user( token=create_access_token("ghost"), user_repo=repo, ) ) assert exc_info.value.status_code == 401 assert exc_info.value.detail == "Could not validate credentials" def test_get_current_active_user_rejects_inactive_user(): with pytest.raises(HTTPException) as exc_info: asyncio.run( dependencies.get_current_active_user( current_user=make_user(is_active=False), ) ) assert exc_info.value.status_code == 403 assert exc_info.value.detail == "Inactive user" def test_get_current_superuser_rejects_non_superuser(): with pytest.raises(HTTPException) as exc_info: asyncio.run( dependencies.get_current_superuser( current_user=make_user(is_superuser=False), ) ) assert exc_info.value.status_code == 403 assert exc_info.value.detail == "Not enough privileges. Superuser access required."