Files
sdb-back/tests/test_auth_routes.py
JSC 171dbb9b63 Refactor code for improved readability and consistency
- Cleaned up whitespace and formatting across multiple files for better readability.
2025-07-02 10:37:48 +02:00

95 lines
3.2 KiB
Python

"""Tests for authentication routes with Flask-JWT-Extended."""
from unittest.mock import Mock, patch
import pytest
from app import create_app
@pytest.fixture
def client():
"""Create a test client for the Flask application."""
app = create_app()
app.config["TESTING"] = True
app.config["JWT_COOKIE_SECURE"] = False # Allow cookies in testing
with app.test_client() as client:
yield client
class TestAuthRoutesJWTExtended:
"""Test cases for authentication routes with Flask-JWT-Extended."""
@patch("app.routes.auth.auth_service.get_login_url")
def test_login_route(self, mock_get_login_url: Mock, client) -> None:
"""Test the login route."""
mock_get_login_url.return_value = (
"https://accounts.google.com/oauth/authorize?..."
)
response = client.get("/api/auth/login")
assert response.status_code == 200
data = response.get_json()
assert "login_url" in data
assert (
data["login_url"]
== "https://accounts.google.com/oauth/authorize?..."
)
@patch("app.routes.auth.auth_service.handle_callback")
def test_callback_route_success(
self, mock_handle_callback: Mock, client
) -> None:
"""Test successful callback route."""
mock_response = Mock()
mock_response.get_json.return_value = {
"message": "Login successful",
"user": {
"id": "123",
"email": "test@example.com",
"name": "Test User",
},
}
mock_handle_callback.return_value = mock_response
response = client.get("/api/auth/callback?code=test_code")
mock_handle_callback.assert_called_once()
@patch("app.routes.auth.auth_service.handle_callback")
def test_callback_route_error(
self, mock_handle_callback: Mock, client
) -> None:
"""Test callback route with error."""
mock_handle_callback.side_effect = Exception("OAuth error")
response = client.get("/api/auth/callback?code=test_code")
assert response.status_code == 400
data = response.get_json()
assert data["error"] == "OAuth error"
@patch("app.routes.auth.auth_service.logout")
def test_logout_route(self, mock_logout: Mock, client) -> None:
"""Test logout route."""
mock_response = Mock()
mock_response.get_json.return_value = {
"message": "Logged out successfully"
}
mock_logout.return_value = mock_response
response = client.get("/api/auth/logout")
mock_logout.assert_called_once()
def test_me_route_not_authenticated(self, client) -> None:
"""Test /me route when not authenticated."""
response = client.get("/api/auth/me")
assert response.status_code == 401
data = response.get_json()
assert "msg" in data # Flask-JWT-Extended error format
def test_refresh_route_not_authenticated(self, client) -> None:
"""Test /refresh route when not authenticated."""
response = client.post("/api/auth/refresh")
assert response.status_code == 401
data = response.get_json()
assert "msg" in data # Flask-JWT-Extended error format