Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions permit/api/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
)
from .context import ApiContextLevel, ApiKeyAccessLevel
from .models import (
ElementsUserInviteApprove,
ElementsUserInviteRead,
PaginatedResultUserRead,
RoleAssignmentCreate,
RoleAssignmentRead,
Expand Down Expand Up @@ -58,6 +60,12 @@ def __bulk_operations(self) -> SimpleHttpClient:
f"/v2/facts/{self.config.api_context.project}/{self.config.api_context.environment}/bulk/users"
)

@property
def __user_invites(self) -> SimpleHttpClient:
return self._build_http_client(
f"/v2/facts/{self.config.api_context.project}/{self.config.api_context.environment}/user_invites"
)

@validate_arguments # type: ignore[operator]
async def list(self, page: int = 1, per_page: int = 100) -> PaginatedResultUserRead:
"""
Expand Down Expand Up @@ -374,3 +382,27 @@ async def get_assigned_roles(
model=List[RoleAssignmentRead],
params=params,
)

@validate_arguments # type: ignore[operator]
async def approve(self, user_invite_id: str, approve_data: ElementsUserInviteApprove) -> ElementsUserInviteRead:
"""
Approves a user invite.

Args:
user_invite_id: The ID of the user invite to approve.
approve_data: The approval data for the user invite.

Returns:
the approved user invite.

Raises:
PermitApiError: If the API returns an error HTTP status code.
PermitContextError: If the configured ApiContext does not match the required endpoint context.
"""
await self._ensure_access_level(ApiKeyAccessLevel.ENVIRONMENT_LEVEL_API_KEY)
await self._ensure_context(ApiContextLevel.ENVIRONMENT)
return await self.__user_invites.post(
f"/{user_invite_id}/approve",
model=ElementsUserInviteRead,
json=approve_data,
)
Comment thread
shuvyA marked this conversation as resolved.
Outdated
179 changes: 179 additions & 0 deletions tests/test_user_invite_approve_simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""
Simple tests for user invite approve functionality.
These tests focus on the core implementation without complex API mocking.
"""

import uuid
import pytest
from unittest.mock import Mock, AsyncMock, patch

from permit.api.models import ElementsUserInviteApprove, ElementsUserInviteRead, UserInviteStatus
from permit.api.users import UsersApi


class TestUserInviteApproveSimple:
Comment thread
shuvyA marked this conversation as resolved.
"""Simple test suite for user invite approve functionality."""

def test_approve_method_exists(self):
"""Test that the approve method exists in UsersApi."""
assert hasattr(UsersApi, 'approve')
assert callable(UsersApi.approve)

def test_approve_method_signature(self):
"""Test that the approve method has the correct signature."""
import inspect

method = getattr(UsersApi, 'approve')
signature = inspect.signature(method)

# Check parameter names
params = list(signature.parameters.keys())
assert 'self' in params
assert 'user_invite_id' in params
assert 'approve_data' in params

# Check return type annotation
assert signature.return_annotation.__name__ == 'ElementsUserInviteRead'

def test_approve_data_model_validation(self):
"""Test ElementsUserInviteApprove model validation."""
# Valid data
valid_data = ElementsUserInviteApprove(
email="test@example.com",
key="valid-key-123",
attributes={"role": "admin"}
)
assert valid_data.email == "test@example.com"
assert valid_data.key == "valid-key-123"
assert valid_data.attributes == {"role": "admin"}

def test_approve_data_model_email_validation(self):
"""Test ElementsUserInviteApprove email validation."""
# Test email validation
with pytest.raises(ValueError):
ElementsUserInviteApprove(
email="invalid-email",
key="valid-key-123",
attributes={}
)

def test_approve_data_model_key_validation(self):
"""Test ElementsUserInviteApprove key validation."""
# Test key validation (regex pattern)
with pytest.raises(ValueError):
ElementsUserInviteApprove(
email="test@example.com",
key="invalid key with spaces", # Should fail regex validation
attributes={}
)

def test_approve_data_model_with_complex_attributes(self):
"""Test ElementsUserInviteApprove with complex attributes."""
complex_attributes = {
"department": "Engineering",
"location": "San Francisco",
"role": "Developer",
"level": "Senior",
"permissions": ["read", "write"],
"metadata": {
"hire_date": "2024-01-01",
"manager": "john@example.com"
}
}

approve_data = ElementsUserInviteApprove(
email="test@example.com",
key="test-key-123",
attributes=complex_attributes
)

assert approve_data.attributes == complex_attributes
assert approve_data.attributes["permissions"] == ["read", "write"]
assert approve_data.attributes["metadata"]["hire_date"] == "2024-01-01"

def test_approve_data_model_with_empty_attributes(self):
"""Test ElementsUserInviteApprove with empty attributes."""
approve_data = ElementsUserInviteApprove(
email="test@example.com",
key="test-key-123",
attributes={} # Empty attributes should be allowed
)

assert approve_data.attributes == {}

def test_user_invite_status_enum(self):
"""Test UserInviteStatus enum values."""
assert UserInviteStatus.pending == 'pending'
assert UserInviteStatus.approved == 'approved'

def test_elements_user_invite_read_model(self):
"""Test ElementsUserInviteRead model creation."""
invite_data = ElementsUserInviteRead(
id=uuid.uuid4(),
organization_id=uuid.uuid4(),
project_id=uuid.uuid4(),
environment_id=uuid.uuid4(),
key="test-invite-key-123",
status=UserInviteStatus.approved,
email="test@example.com",
first_name="John",
last_name="Doe",
role_id=uuid.uuid4(),
tenant_id=uuid.uuid4(),
created_at="2024-01-01T00:00:00Z",
updated_at="2024-01-01T01:00:00Z"
)

assert invite_data.status == UserInviteStatus.approved
assert invite_data.email == "test@example.com"
assert invite_data.key == "test-invite-key-123"


def test_approve_parameter_types(self):
"""Test that the approve method parameters have correct types."""
import inspect
from typing import get_type_hints

method = getattr(UsersApi, 'approve')
type_hints = get_type_hints(method)

# Check parameter types
assert type_hints.get('user_invite_id') == str
assert type_hints.get('approve_data').__name__ == 'ElementsUserInviteApprove'
assert type_hints.get('return').__name__ == 'ElementsUserInviteRead'

def test_user_invite_models_exist(self):
"""Test that all required models are available."""
# Test that we can import all necessary models
from permit.api.models import (
ElementsUserInviteApprove,
ElementsUserInviteRead,
UserInviteStatus
)

assert ElementsUserInviteApprove is not None
assert ElementsUserInviteRead is not None
assert UserInviteStatus is not None

def test_approve_data_serialization(self):
"""Test that ElementsUserInviteApprove data can be serialized."""
approve_data = ElementsUserInviteApprove(
email="test@example.com",
key="test-key-123",
attributes={"role": "admin", "department": "Engineering"}
)

# Test dict() method
data_dict = approve_data.dict()
assert data_dict['email'] == "test@example.com"
assert data_dict['key'] == "test-key-123"
assert data_dict['attributes']['role'] == "admin"
assert data_dict['attributes']['department'] == "Engineering"

# Test JSON serialization
import json
json_str = approve_data.json()
parsed_data = json.loads(json_str)
assert parsed_data['email'] == "test@example.com"
assert parsed_data['key'] == "test-key-123"

Loading