format: ruff format
This commit is contained in:
parent
f786780a20
commit
1b643c8355
8 changed files with 259 additions and 181 deletions
|
|
@ -46,7 +46,9 @@ def get_cognify_router() -> APIRouter:
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@router.post("", response_model=dict)
|
@router.post("", response_model=dict)
|
||||||
async def cognify(payload: CognifyPayloadDTO, user: User = Depends(get_conditional_authenticated_user)):
|
async def cognify(
|
||||||
|
payload: CognifyPayloadDTO, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Transform datasets into structured knowledge graphs through cognitive processing.
|
Transform datasets into structured knowledge graphs through cognitive processing.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -114,7 +114,8 @@ def get_datasets_router() -> APIRouter:
|
||||||
|
|
||||||
@router.post("", response_model=DatasetDTO)
|
@router.post("", response_model=DatasetDTO)
|
||||||
async def create_new_dataset(
|
async def create_new_dataset(
|
||||||
dataset_data: DatasetCreationPayload, user: User = Depends(get_conditional_authenticated_user)
|
dataset_data: DatasetCreationPayload,
|
||||||
|
user: User = Depends(get_conditional_authenticated_user),
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Create a new dataset or return existing dataset with the same name.
|
Create a new dataset or return existing dataset with the same name.
|
||||||
|
|
@ -175,7 +176,9 @@ def get_datasets_router() -> APIRouter:
|
||||||
@router.delete(
|
@router.delete(
|
||||||
"/{dataset_id}", response_model=None, responses={404: {"model": ErrorResponseDTO}}
|
"/{dataset_id}", response_model=None, responses={404: {"model": ErrorResponseDTO}}
|
||||||
)
|
)
|
||||||
async def delete_dataset(dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)):
|
async def delete_dataset(
|
||||||
|
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Delete a dataset by its ID.
|
Delete a dataset by its ID.
|
||||||
|
|
||||||
|
|
@ -263,7 +266,9 @@ def get_datasets_router() -> APIRouter:
|
||||||
await delete_data(data)
|
await delete_data(data)
|
||||||
|
|
||||||
@router.get("/{dataset_id}/graph", response_model=GraphDTO)
|
@router.get("/{dataset_id}/graph", response_model=GraphDTO)
|
||||||
async def get_dataset_graph(dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)):
|
async def get_dataset_graph(
|
||||||
|
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Get the knowledge graph visualization for a dataset.
|
Get the knowledge graph visualization for a dataset.
|
||||||
|
|
||||||
|
|
@ -293,7 +298,9 @@ def get_datasets_router() -> APIRouter:
|
||||||
response_model=list[DataDTO],
|
response_model=list[DataDTO],
|
||||||
responses={404: {"model": ErrorResponseDTO}},
|
responses={404: {"model": ErrorResponseDTO}},
|
||||||
)
|
)
|
||||||
async def get_dataset_data(dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)):
|
async def get_dataset_data(
|
||||||
|
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Get all data items in a dataset.
|
Get all data items in a dataset.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -183,7 +183,9 @@ def get_permissions_router() -> APIRouter:
|
||||||
return JSONResponse(status_code=200, content={"message": "User added to tenant"})
|
return JSONResponse(status_code=200, content={"message": "User added to tenant"})
|
||||||
|
|
||||||
@permissions_router.post("/tenants")
|
@permissions_router.post("/tenants")
|
||||||
async def create_tenant(tenant_name: str, user: User = Depends(get_conditional_authenticated_user)):
|
async def create_tenant(
|
||||||
|
tenant_name: str, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Create a new tenant.
|
Create a new tenant.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,9 @@ def get_search_router() -> APIRouter:
|
||||||
return JSONResponse(status_code=500, content={"error": str(error)})
|
return JSONResponse(status_code=500, content={"error": str(error)})
|
||||||
|
|
||||||
@router.post("", response_model=list)
|
@router.post("", response_model=list)
|
||||||
async def search(payload: SearchPayloadDTO, user: User = Depends(get_conditional_authenticated_user)):
|
async def search(
|
||||||
|
payload: SearchPayloadDTO, user: User = Depends(get_conditional_authenticated_user)
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Search for nodes in the graph database.
|
Search for nodes in the graph database.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,4 +4,7 @@ from .delete_user import delete_user
|
||||||
from .get_default_user import get_default_user
|
from .get_default_user import get_default_user
|
||||||
from .get_user_by_email import get_user_by_email
|
from .get_user_by_email import get_user_by_email
|
||||||
from .create_default_user import create_default_user
|
from .create_default_user import create_default_user
|
||||||
from .get_conditional_authenticated_user import get_conditional_authenticated_user, REQUIRE_AUTHENTICATION
|
from .get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,13 @@ else:
|
||||||
# When REQUIRE_AUTHENTICATION=false (default), make authentication optional
|
# When REQUIRE_AUTHENTICATION=false (default), make authentication optional
|
||||||
_auth_dependency = fastapi_users.current_user(
|
_auth_dependency = fastapi_users.current_user(
|
||||||
optional=True, # Returns None instead of raising HTTPException(401)
|
optional=True, # Returns None instead of raising HTTPException(401)
|
||||||
active=True # Still require users to be active when authenticated
|
active=True, # Still require users to be active when authenticated
|
||||||
)
|
)
|
||||||
|
|
||||||
async def get_conditional_authenticated_user(user: Optional[User] = Depends(_auth_dependency)) -> User:
|
|
||||||
|
async def get_conditional_authenticated_user(
|
||||||
|
user: Optional[User] = Depends(_auth_dependency),
|
||||||
|
) -> User:
|
||||||
"""
|
"""
|
||||||
Get authenticated user with environment-controlled behavior:
|
Get authenticated user with environment-controlled behavior:
|
||||||
- If REQUIRE_AUTHENTICATION=true: Enforces authentication (raises 401 if not authenticated)
|
- If REQUIRE_AUTHENTICATION=true: Enforces authentication (raises 401 if not authenticated)
|
||||||
|
|
@ -34,9 +37,6 @@ async def get_conditional_authenticated_user(user: Optional[User] = Depends(_aut
|
||||||
user = await get_default_user()
|
user = await get_default_user()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Convert any get_default_user failure into a proper HTTP 500 error
|
# Convert any get_default_user failure into a proper HTTP 500 error
|
||||||
raise HTTPException(
|
raise HTTPException(status_code=500, detail=f"Failed to create default user: {str(e)}")
|
||||||
status_code=500,
|
|
||||||
detail=f"Failed to create default user: {str(e)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
return user
|
return user
|
||||||
|
|
|
||||||
|
|
@ -21,23 +21,21 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
def mock_default_user(self):
|
def mock_default_user(self):
|
||||||
"""Mock default user for testing."""
|
"""Mock default user for testing."""
|
||||||
return SimpleNamespace(
|
return SimpleNamespace(
|
||||||
id=uuid4(),
|
id=uuid4(), email="default@example.com", is_active=True, tenant_id=uuid4()
|
||||||
email="default@example.com",
|
|
||||||
is_active=True,
|
|
||||||
tenant_id=uuid4()
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_authenticated_user(self):
|
def mock_authenticated_user(self):
|
||||||
"""Mock authenticated user for testing."""
|
"""Mock authenticated user for testing."""
|
||||||
from cognee.modules.users.models import User
|
from cognee.modules.users.models import User
|
||||||
|
|
||||||
return User(
|
return User(
|
||||||
id=uuid4(),
|
id=uuid4(),
|
||||||
email="auth@example.com",
|
email="auth@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True,
|
is_verified=True,
|
||||||
tenant_id=uuid4()
|
tenant_id=uuid4(),
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_health_endpoint_no_auth_required(self, client):
|
def test_health_endpoint_no_auth_required(self, client):
|
||||||
|
|
@ -71,8 +69,10 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
@patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"})
|
@patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"})
|
||||||
def test_add_endpoint_with_conditional_auth(self, client, mock_default_user):
|
def test_add_endpoint_with_conditional_auth(self, client, mock_default_user):
|
||||||
"""Test add endpoint works with conditional authentication."""
|
"""Test add endpoint works with conditional authentication."""
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
with patch('cognee.api.v1.add.add') as mock_cognee_add:
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
|
with patch("cognee.api.v1.add.add") as mock_cognee_add:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
mock_cognee_add.return_value = MagicMock(
|
mock_cognee_add.return_value = MagicMock(
|
||||||
model_dump=lambda: {"status": "success", "pipeline_run_id": str(uuid4())}
|
model_dump=lambda: {"status": "success", "pipeline_run_id": str(uuid4())}
|
||||||
|
|
@ -95,8 +95,12 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
# Since REQUIRE_AUTHENTICATION defaults to "false", we expect endpoints to work without auth
|
# Since REQUIRE_AUTHENTICATION defaults to "false", we expect endpoints to work without auth
|
||||||
# This tests the actual integration behavior
|
# This tests the actual integration behavior
|
||||||
|
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com", is_active=True, tenant_id=uuid4())
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
|
mock_default_user = SimpleNamespace(
|
||||||
|
id=uuid4(), email="default@example.com", is_active=True, tenant_id=uuid4()
|
||||||
|
)
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
files = {"data": ("test.txt", b"test content", "text/plain")}
|
files = {"data": ("test.txt", b"test content", "text/plain")}
|
||||||
|
|
@ -112,8 +116,10 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
|
|
||||||
def test_authenticated_request_uses_user(self, client, mock_authenticated_user):
|
def test_authenticated_request_uses_user(self, client, mock_authenticated_user):
|
||||||
"""Test that authenticated requests use the authenticated user, not default user."""
|
"""Test that authenticated requests use the authenticated user, not default user."""
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
with patch('cognee.api.v1.add.add') as mock_cognee_add:
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
|
with patch("cognee.api.v1.add.add") as mock_cognee_add:
|
||||||
# Mock successful authentication - this would normally be handled by FastAPI Users
|
# Mock successful authentication - this would normally be handled by FastAPI Users
|
||||||
# but we're testing the conditional logic
|
# but we're testing the conditional logic
|
||||||
mock_cognee_add.return_value = MagicMock(
|
mock_cognee_add.return_value = MagicMock(
|
||||||
|
|
@ -121,7 +127,9 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
)
|
)
|
||||||
|
|
||||||
# Simulate authenticated request by directly testing the conditional function
|
# Simulate authenticated request by directly testing the conditional function
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
async def test_logic():
|
async def test_logic():
|
||||||
# When user is provided (authenticated), should not call get_default_user
|
# When user is provided (authenticated), should not call get_default_user
|
||||||
|
|
@ -131,6 +139,7 @@ class TestConditionalAuthenticationEndpoints:
|
||||||
|
|
||||||
# Run the async test
|
# Run the async test
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
asyncio.run(test_logic())
|
asyncio.run(test_logic())
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -141,13 +150,18 @@ class TestConditionalAuthenticationBehavior:
|
||||||
def client(self):
|
def client(self):
|
||||||
return TestClient(app)
|
return TestClient(app)
|
||||||
|
|
||||||
@pytest.mark.parametrize("endpoint,method", [
|
@pytest.mark.parametrize(
|
||||||
("/api/v1/search", "GET"),
|
"endpoint,method",
|
||||||
("/api/v1/datasets", "GET"),
|
[
|
||||||
])
|
("/api/v1/search", "GET"),
|
||||||
|
("/api/v1/datasets", "GET"),
|
||||||
|
],
|
||||||
|
)
|
||||||
def test_get_endpoints_work_without_auth(self, client, endpoint, method, mock_default_user):
|
def test_get_endpoints_work_without_auth(self, client, endpoint, method, mock_default_user):
|
||||||
"""Test that GET endpoints work without authentication (with current environment)."""
|
"""Test that GET endpoints work without authentication (with current environment)."""
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
if method == "GET":
|
if method == "GET":
|
||||||
|
|
@ -170,9 +184,13 @@ class TestConditionalAuthenticationBehavior:
|
||||||
|
|
||||||
def test_settings_endpoint_integration(self, client, mock_default_user):
|
def test_settings_endpoint_integration(self, client, mock_default_user):
|
||||||
"""Test that settings endpoint integration works with conditional authentication."""
|
"""Test that settings endpoint integration works with conditional authentication."""
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
with patch('cognee.modules.settings.get_settings.get_llm_config') as mock_llm_config:
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
with patch('cognee.modules.settings.get_settings.get_vectordb_config') as mock_vector_config:
|
) as mock_get_default:
|
||||||
|
with patch("cognee.modules.settings.get_settings.get_llm_config") as mock_llm_config:
|
||||||
|
with patch(
|
||||||
|
"cognee.modules.settings.get_settings.get_vectordb_config"
|
||||||
|
) as mock_vector_config:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
# Mock configurations to avoid validation errors
|
# Mock configurations to avoid validation errors
|
||||||
|
|
@ -181,13 +199,13 @@ class TestConditionalAuthenticationBehavior:
|
||||||
llm_model="gpt-4o",
|
llm_model="gpt-4o",
|
||||||
llm_endpoint=None,
|
llm_endpoint=None,
|
||||||
llm_api_version=None,
|
llm_api_version=None,
|
||||||
llm_api_key="test_key_1234567890"
|
llm_api_key="test_key_1234567890",
|
||||||
)
|
)
|
||||||
|
|
||||||
mock_vector_config.return_value = SimpleNamespace(
|
mock_vector_config.return_value = SimpleNamespace(
|
||||||
vector_db_provider="lancedb",
|
vector_db_provider="lancedb",
|
||||||
vector_db_url="localhost:5432", # Must be string, not None
|
vector_db_url="localhost:5432", # Must be string, not None
|
||||||
vector_db_key="test_vector_key"
|
vector_db_key="test_vector_key",
|
||||||
)
|
)
|
||||||
|
|
||||||
response = client.get("/api/v1/settings")
|
response = client.get("/api/v1/settings")
|
||||||
|
|
@ -208,7 +226,9 @@ class TestConditionalAuthenticationErrorHandling:
|
||||||
|
|
||||||
def test_get_default_user_fails(self, client):
|
def test_get_default_user_fails(self, client):
|
||||||
"""Test behavior when get_default_user fails (with current environment)."""
|
"""Test behavior when get_default_user fails (with current environment)."""
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.side_effect = Exception("Database connection failed")
|
mock_get_default.side_effect = Exception("Database connection failed")
|
||||||
|
|
||||||
# The error should propagate - either as a 500 error or as an exception
|
# The error should propagate - either as a 500 error or as an exception
|
||||||
|
|
@ -232,7 +252,9 @@ class TestConditionalAuthenticationErrorHandling:
|
||||||
def test_current_environment_configuration(self):
|
def test_current_environment_configuration(self):
|
||||||
"""Test that current environment configuration is working properly."""
|
"""Test that current environment configuration is working properly."""
|
||||||
# This tests the actual module state without trying to change it
|
# This tests the actual module state without trying to change it
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
# Should be a boolean value (the parsing logic works)
|
# Should be a boolean value (the parsing logic works)
|
||||||
assert isinstance(REQUIRE_AUTHENTICATION, bool)
|
assert isinstance(REQUIRE_AUTHENTICATION, bool)
|
||||||
|
|
@ -246,21 +268,20 @@ class TestConditionalAuthenticationErrorHandling:
|
||||||
def mock_default_user():
|
def mock_default_user():
|
||||||
"""Mock default user for testing."""
|
"""Mock default user for testing."""
|
||||||
return SimpleNamespace(
|
return SimpleNamespace(
|
||||||
id=uuid4(),
|
id=uuid4(), email="default@example.com", is_active=True, tenant_id=uuid4()
|
||||||
email="default@example.com",
|
|
||||||
is_active=True,
|
|
||||||
tenant_id=uuid4()
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def mock_authenticated_user():
|
def mock_authenticated_user():
|
||||||
"""Mock authenticated user for testing."""
|
"""Mock authenticated user for testing."""
|
||||||
from cognee.modules.users.models import User
|
from cognee.modules.users.models import User
|
||||||
|
|
||||||
return User(
|
return User(
|
||||||
id=uuid4(),
|
id=uuid4(),
|
||||||
email="auth@example.com",
|
email="auth@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True,
|
is_verified=True,
|
||||||
tenant_id=uuid4()
|
tenant_id=uuid4(),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ from types import SimpleNamespace
|
||||||
|
|
||||||
from cognee.modules.users.models import User
|
from cognee.modules.users.models import User
|
||||||
|
|
||||||
|
|
||||||
class TestConditionalAuthentication:
|
class TestConditionalAuthentication:
|
||||||
"""Test cases for conditional authentication functionality."""
|
"""Test cases for conditional authentication functionality."""
|
||||||
|
|
||||||
|
|
@ -16,15 +17,16 @@ class TestConditionalAuthentication:
|
||||||
async def test_require_authentication_false_no_token_returns_default_user(self):
|
async def test_require_authentication_false_no_token_returns_default_user(self):
|
||||||
"""Test that when REQUIRE_AUTHENTICATION=false and no token, returns default user."""
|
"""Test that when REQUIRE_AUTHENTICATION=false and no token, returns default user."""
|
||||||
# Mock the default user
|
# Mock the default user
|
||||||
mock_default_user = SimpleNamespace(
|
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com", is_active=True)
|
||||||
id=uuid4(),
|
|
||||||
email="default@example.com",
|
|
||||||
is_active=True
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
# Test with None user (no authentication)
|
# Test with None user (no authentication)
|
||||||
|
|
@ -41,12 +43,17 @@ class TestConditionalAuthentication:
|
||||||
email="user@example.com",
|
email="user@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True
|
is_verified=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
# Test with authenticated user
|
# Test with authenticated user
|
||||||
result = await get_conditional_authenticated_user(user=mock_authenticated_user)
|
result = await get_conditional_authenticated_user(user=mock_authenticated_user)
|
||||||
|
|
||||||
|
|
@ -61,11 +68,14 @@ class TestConditionalAuthentication:
|
||||||
email="user@example.com",
|
email="user@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True
|
is_verified=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
result = await get_conditional_authenticated_user(user=mock_authenticated_user)
|
result = await get_conditional_authenticated_user(user=mock_authenticated_user)
|
||||||
|
|
||||||
assert result == mock_authenticated_user
|
assert result == mock_authenticated_user
|
||||||
|
|
@ -78,12 +88,15 @@ class TestConditionalAuthentication:
|
||||||
|
|
||||||
# Since REQUIRE_AUTHENTICATION is currently false (set at import time),
|
# Since REQUIRE_AUTHENTICATION is currently false (set at import time),
|
||||||
# we expect it to return the default user, not None
|
# we expect it to return the default user, not None
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
result = await get_conditional_authenticated_user(user=None)
|
result = await get_conditional_authenticated_user(user=None)
|
||||||
|
|
||||||
# The current implementation will return default user because REQUIRE_AUTHENTICATION is false
|
# The current implementation will return default user because REQUIRE_AUTHENTICATION is false
|
||||||
assert result is not None # Should get default user
|
assert result is not None # Should get default user
|
||||||
assert hasattr(result, 'id')
|
assert hasattr(result, "id")
|
||||||
|
|
||||||
|
|
||||||
class TestConditionalAuthenticationIntegration:
|
class TestConditionalAuthenticationIntegration:
|
||||||
|
|
@ -109,7 +122,7 @@ class TestConditionalAuthenticationIntegration:
|
||||||
"""Test that the conditional authentication function can be imported and used."""
|
"""Test that the conditional authentication function can be imported and used."""
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
get_conditional_authenticated_user,
|
get_conditional_authenticated_user,
|
||||||
REQUIRE_AUTHENTICATION
|
REQUIRE_AUTHENTICATION,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Should be callable
|
# Should be callable
|
||||||
|
|
@ -129,36 +142,45 @@ class TestConditionalAuthenticationEnvironmentVariables:
|
||||||
"""Test that REQUIRE_AUTHENTICATION defaults to false when imported with no env var."""
|
"""Test that REQUIRE_AUTHENTICATION defaults to false when imported with no env var."""
|
||||||
with patch.dict(os.environ, {}, clear=True):
|
with patch.dict(os.environ, {}, clear=True):
|
||||||
# Remove module from cache to force fresh import
|
# Remove module from cache to force fresh import
|
||||||
module_name = 'cognee.modules.users.methods.get_conditional_authenticated_user'
|
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user"
|
||||||
if module_name in sys.modules:
|
if module_name in sys.modules:
|
||||||
del sys.modules[module_name]
|
del sys.modules[module_name]
|
||||||
|
|
||||||
# Import after patching environment - module will see empty environment
|
# Import after patching environment - module will see empty environment
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
assert REQUIRE_AUTHENTICATION == False
|
assert REQUIRE_AUTHENTICATION == False
|
||||||
|
|
||||||
def test_require_authentication_true(self):
|
def test_require_authentication_true(self):
|
||||||
"""Test that REQUIRE_AUTHENTICATION=true is parsed correctly when imported."""
|
"""Test that REQUIRE_AUTHENTICATION=true is parsed correctly when imported."""
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
|
||||||
# Remove module from cache to force fresh import
|
# Remove module from cache to force fresh import
|
||||||
module_name = 'cognee.modules.users.methods.get_conditional_authenticated_user'
|
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user"
|
||||||
if module_name in sys.modules:
|
if module_name in sys.modules:
|
||||||
del sys.modules[module_name]
|
del sys.modules[module_name]
|
||||||
|
|
||||||
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=true
|
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=true
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
assert REQUIRE_AUTHENTICATION == True
|
assert REQUIRE_AUTHENTICATION == True
|
||||||
|
|
||||||
def test_require_authentication_false_explicit(self):
|
def test_require_authentication_false_explicit(self):
|
||||||
"""Test that REQUIRE_AUTHENTICATION=false is parsed correctly when imported."""
|
"""Test that REQUIRE_AUTHENTICATION=false is parsed correctly when imported."""
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
# Remove module from cache to force fresh import
|
# Remove module from cache to force fresh import
|
||||||
module_name = 'cognee.modules.users.methods.get_conditional_authenticated_user'
|
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user"
|
||||||
if module_name in sys.modules:
|
if module_name in sys.modules:
|
||||||
del sys.modules[module_name]
|
del sys.modules[module_name]
|
||||||
|
|
||||||
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=false
|
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=false
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
assert REQUIRE_AUTHENTICATION == False
|
assert REQUIRE_AUTHENTICATION == False
|
||||||
|
|
||||||
def test_require_authentication_case_insensitive(self):
|
def test_require_authentication_case_insensitive(self):
|
||||||
|
|
@ -168,18 +190,23 @@ class TestConditionalAuthenticationEnvironmentVariables:
|
||||||
for case in test_cases:
|
for case in test_cases:
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": case}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": case}):
|
||||||
# Remove module from cache to force fresh import
|
# Remove module from cache to force fresh import
|
||||||
module_name = 'cognee.modules.users.methods.get_conditional_authenticated_user'
|
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user"
|
||||||
if module_name in sys.modules:
|
if module_name in sys.modules:
|
||||||
del sys.modules[module_name]
|
del sys.modules[module_name]
|
||||||
|
|
||||||
# Import after patching environment
|
# Import after patching environment
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
expected = case.lower() == "true"
|
expected = case.lower() == "true"
|
||||||
assert REQUIRE_AUTHENTICATION == expected, f"Failed for case: {case}"
|
assert REQUIRE_AUTHENTICATION == expected, f"Failed for case: {case}"
|
||||||
|
|
||||||
def test_current_require_authentication_value(self):
|
def test_current_require_authentication_value(self):
|
||||||
"""Test that the current REQUIRE_AUTHENTICATION module value is as expected."""
|
"""Test that the current REQUIRE_AUTHENTICATION module value is as expected."""
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import REQUIRE_AUTHENTICATION
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
REQUIRE_AUTHENTICATION,
|
||||||
|
)
|
||||||
|
|
||||||
# The module-level variable should currently be False (set at import time)
|
# The module-level variable should currently be False (set at import time)
|
||||||
assert isinstance(REQUIRE_AUTHENTICATION, bool)
|
assert isinstance(REQUIRE_AUTHENTICATION, bool)
|
||||||
|
|
@ -192,9 +219,14 @@ class TestConditionalAuthenticationEdgeCases:
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_get_default_user_raises_exception(self):
|
async def test_get_default_user_raises_exception(self):
|
||||||
"""Test behavior when get_default_user raises an exception."""
|
"""Test behavior when get_default_user raises an exception."""
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.side_effect = Exception("Database error")
|
mock_get_default.side_effect = Exception("Database error")
|
||||||
|
|
||||||
# This should propagate the exception
|
# This should propagate the exception
|
||||||
|
|
@ -204,23 +236,24 @@ class TestConditionalAuthenticationEdgeCases:
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_type_consistency(self):
|
async def test_user_type_consistency(self):
|
||||||
"""Test that the function always returns the same type."""
|
"""Test that the function always returns the same type."""
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
mock_user = User(
|
mock_user = User(
|
||||||
id=uuid4(),
|
id=uuid4(),
|
||||||
email="test@example.com",
|
email="test@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True
|
is_verified=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
mock_default_user = SimpleNamespace(
|
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com", is_active=True)
|
||||||
id=uuid4(),
|
|
||||||
email="default@example.com",
|
|
||||||
is_active=True
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
# Test with user
|
# Test with user
|
||||||
|
|
@ -232,10 +265,10 @@ class TestConditionalAuthenticationEdgeCases:
|
||||||
assert result2 == mock_default_user
|
assert result2 == mock_default_user
|
||||||
|
|
||||||
# Both should have user-like interface
|
# Both should have user-like interface
|
||||||
assert hasattr(result1, 'id')
|
assert hasattr(result1, "id")
|
||||||
assert hasattr(result1, 'email')
|
assert hasattr(result1, "email")
|
||||||
assert hasattr(result2, 'id')
|
assert hasattr(result2, "id")
|
||||||
assert hasattr(result2, 'email')
|
assert hasattr(result2, "email")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|
@ -254,9 +287,14 @@ class TestAuthenticationScenarios:
|
||||||
which should trigger fallback to default user.
|
which should trigger fallback to default user.
|
||||||
"""
|
"""
|
||||||
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com")
|
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com")
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
|
)
|
||||||
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
with patch('cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user') as mock_get_default:
|
with patch(
|
||||||
|
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user"
|
||||||
|
) as mock_get_default:
|
||||||
mock_get_default.return_value = mock_default_user
|
mock_get_default.return_value = mock_default_user
|
||||||
|
|
||||||
# All the above scenarios result in user=None being passed to our function
|
# All the above scenarios result in user=None being passed to our function
|
||||||
|
|
@ -271,10 +309,13 @@ class TestAuthenticationScenarios:
|
||||||
email="active@example.com",
|
email="active@example.com",
|
||||||
hashed_password="hashed",
|
hashed_password="hashed",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
is_verified=True
|
is_verified=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
from cognee.modules.users.methods.get_conditional_authenticated_user import (
|
||||||
|
get_conditional_authenticated_user,
|
||||||
)
|
)
|
||||||
|
|
||||||
from cognee.modules.users.methods.get_conditional_authenticated_user import get_conditional_authenticated_user
|
|
||||||
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
|
||||||
result = await get_conditional_authenticated_user(user=mock_user)
|
result = await get_conditional_authenticated_user(user=mock_user)
|
||||||
assert result == mock_user
|
assert result == mock_user
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue