Buckets:

download
raw
30.8 kB
"""
Comprehensive tests for api/models/user.py
Target: 90-100% coverage
Tests cover:
- UserRole enum
- User model initialization
- User methods (find_one, save, update_last_login, to_response)
- Edge cases and validation
"""
import asyncio
import sys
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from api.models.user import User, UserRole
# ============================================================================
# UserRole Enum Tests
# ============================================================================
class TestUserRole:
"""Test suite for UserRole enumeration"""
def test_user_role_values(self):
"""Test UserRole enum has correct values"""
assert UserRole.USER.value == 1
assert UserRole.ADMIN.value == 2
assert UserRole.SUPERADMIN.value == 3
def test_user_role_names(self):
"""Test UserRole enum has correct names"""
assert UserRole.USER.name == "USER"
assert UserRole.ADMIN.name == "ADMIN"
assert UserRole.SUPERADMIN.name == "SUPERADMIN"
def test_user_role_comparison(self):
"""Test UserRole enum comparison"""
assert UserRole.USER.value < UserRole.ADMIN.value
assert UserRole.ADMIN.value < UserRole.SUPERADMIN.value
assert UserRole.USER.value < UserRole.SUPERADMIN.value
def test_user_role_equality(self):
"""Test UserRole enum equality"""
assert UserRole.USER == UserRole.USER
assert UserRole.ADMIN == UserRole.ADMIN
assert UserRole.SUPERADMIN == UserRole.SUPERADMIN
assert UserRole.USER != UserRole.ADMIN
def test_user_role_iteration(self):
"""Test UserRole enum can be iterated"""
roles = list(UserRole)
assert len(roles) == 3
assert UserRole.USER in roles
assert UserRole.ADMIN in roles
assert UserRole.SUPERADMIN in roles
def test_user_role_access_by_name(self):
"""Test accessing UserRole by name"""
assert UserRole["USER"] == UserRole.USER
assert UserRole["ADMIN"] == UserRole.ADMIN
assert UserRole["SUPERADMIN"] == UserRole.SUPERADMIN
def test_user_role_access_by_value(self):
"""Test accessing UserRole by value"""
assert UserRole(1) == UserRole.USER
assert UserRole(2) == UserRole.ADMIN
assert UserRole(3) == UserRole.SUPERADMIN
# ============================================================================
# User Model Initialization Tests
# ============================================================================
class TestUserInitialization:
"""Test suite for User model initialization"""
def test_user_creation_required_fields(self):
"""Test user creation with required fields only"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="hashedpassword123",
)
assert user.username == "testuser"
assert user.email == "test@example.com"
assert user.hashed_password == "hashedpassword123"
assert user.id == "stub-id"
assert user.role == UserRole.USER
assert user.is_active is True
assert user.full_name is None
assert user.last_login is None
assert isinstance(user.created_at, datetime)
def test_user_creation_all_fields(self):
"""Test user creation with all fields"""
user = User(
username="adminuser",
email="admin@example.com",
hashed_password="securehash456",
full_name="Admin User",
role=UserRole.ADMIN,
is_active=True,
)
assert user.username == "adminuser"
assert user.email == "admin@example.com"
assert user.hashed_password == "securehash456"
assert user.full_name == "Admin User"
assert user.role == UserRole.ADMIN
assert user.is_active is True
assert user.id == "stub-id"
assert isinstance(user.created_at, datetime)
def test_user_creation_superadmin(self):
"""Test user creation with SUPERADMIN role"""
user = User(
username="superadmin",
email="super@example.com",
hashed_password="supersecure",
role=UserRole.SUPERADMIN,
)
assert user.role == UserRole.SUPERADMIN
assert user.role.value == 3
def test_user_creation_inactive(self):
"""Test user creation with is_active=False"""
user = User(
username="inactiveuser",
email="inactive@example.com",
hashed_password="hashedpass",
is_active=False,
)
assert user.is_active is False
def test_user_creation_empty_full_name(self):
"""Test user creation with empty full_name"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="hashedpass",
full_name="",
)
assert user.full_name == ""
def test_user_creation_with_whitespace(self):
"""Test user creation with whitespace in strings"""
user = User(
username=" testuser ",
email=" test@example.com ",
hashed_password="hashedpass",
full_name=" Test User ",
)
assert user.username == " testuser "
assert user.email == " test@example.com "
assert user.full_name == " Test User "
def test_user_creation_special_characters(self):
"""Test user creation with special characters"""
user = User(
username="user_123-test",
email="user+test@example.com",
hashed_password="hash$%^&*()",
full_name="User Name (Test)",
)
assert user.username == "user_123-test"
assert user.email == "user+test@example.com"
assert user.hashed_password == "hash$%^&*()"
def test_user_creation_unicode(self):
"""Test user creation with unicode characters"""
user = User(
username="用户测试",
email="测试@例子.测试",
hashed_password="hashedpass",
full_name="测试用户",
)
assert user.username == "用户测试"
assert user.email == "测试@例子.测试"
assert user.full_name == "测试用户"
def test_user_creation_long_strings(self):
"""Test user creation with long strings"""
long_string = "a" * 1000
user = User(
username=long_string,
email=f"{long_string}@example.com",
hashed_password=long_string,
full_name=long_string,
)
assert user.username == long_string
assert user.email == f"{long_string}@example.com"
assert user.hashed_password == long_string
assert user.full_name == long_string
def test_user_creation_created_at_timestamp(self):
"""Test that created_at is set to current time"""
before = datetime.now(timezone.utc)
user = User(
username="testuser",
email="test@example.com",
hashed_password="hashedpass",
)
after = datetime.now(timezone.utc)
assert before <= user.created_at <= after
def test_user_creation_unique_instances(self):
"""Test that each user instance is independent"""
user1 = User(
username="user1",
email="user1@example.com",
hashed_password="pass1",
)
user2 = User(
username="user2",
email="user2@example.com",
hashed_password="pass2",
)
assert user1.username != user2.username
assert user1.email != user2.email
assert user1.created_at != user2.created_at or True # Could be same millisecond
# ============================================================================
# User Model Methods Tests
# ============================================================================
class TestUserMethods:
"""Test suite for User model methods"""
@pytest.fixture
def sample_user(self):
"""Create a sample user for testing"""
return User(
username="testuser",
email="test@example.com",
hashed_password="hashedpass123",
full_name="Test User",
role=UserRole.USER,
is_active=True,
)
# -------------------------------------------------------------------------
# find_one tests
# -------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_find_one_returns_none(self):
"""Test find_one returns None (stub behavior)"""
result = await User.find_one(username="testuser")
assert result is None
@pytest.mark.asyncio
async def test_find_one_with_various_kwargs(self):
"""Test find_one with various keyword arguments"""
result = await User.find_one(email="test@example.com")
assert result is None
result = await User.find_one(id="some-id")
assert result is None
result = await User.find_one(username="test", email="test@test.com")
assert result is None
@pytest.mark.asyncio
async def test_find_one_class_method(self):
"""Test find_one is a class method - accessible without instance"""
# Verify find_one can be called on class without instance
assert hasattr(User, "find_one")
# Verify it's callable without creating an instance
result = await User.find_one(username="test")
assert result is None
# -------------------------------------------------------------------------
# save tests
# -------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_save_method(self, sample_user):
"""Test save method runs without error"""
# Should not raise any exception
await sample_user.save()
@pytest.mark.asyncio
async def test_save_does_not_modify_user(self, sample_user):
"""Test save does not modify user attributes"""
original_username = sample_user.username
original_email = sample_user.email
await sample_user.save()
assert sample_user.username == original_username
assert sample_user.email == original_email
# -------------------------------------------------------------------------
# update_last_login tests
# -------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_update_last_login_sets_timestamp(self, sample_user):
"""Test update_last_login sets last_login to current time"""
assert sample_user.last_login is None
before = datetime.now(timezone.utc)
await sample_user.update_last_login()
after = datetime.now(timezone.utc)
assert sample_user.last_login is not None
assert before <= sample_user.last_login <= after
@pytest.mark.asyncio
async def test_update_last_login_overwrites_existing(self, sample_user):
"""Test update_last_login overwrites existing timestamp"""
# Set initial last_login
old_time = datetime(2020, 1, 1, 12, 0, 0)
sample_user.last_login = old_time
await sample_user.update_last_login()
assert sample_user.last_login != old_time
assert sample_user.last_login > old_time
@pytest.mark.asyncio
async def test_update_last_login_multiple_calls(self, sample_user):
"""Test update_last_login can be called multiple times"""
await sample_user.update_last_login()
first_login = sample_user.last_login
await asyncio.sleep(0.01) # Small delay to ensure different timestamp
await sample_user.update_last_login()
second_login = sample_user.last_login
assert second_login >= first_login
# -------------------------------------------------------------------------
# to_response tests
# -------------------------------------------------------------------------
def test_to_response_basic(self, sample_user):
"""Test to_response returns correct dict structure"""
response = sample_user.to_response()
assert isinstance(response, dict)
assert response["id"] == str(sample_user.id)
assert response["username"] == sample_user.username
assert response["email"] == sample_user.email
assert response["full_name"] == sample_user.full_name
assert response["role"] == sample_user.role.name
assert response["is_active"] == sample_user.is_active
assert response["created_at"] == sample_user.created_at
def test_to_response_excludes_password(self, sample_user):
"""Test to_response excludes hashed_password"""
response = sample_user.to_response()
assert "hashed_password" not in response
assert "password" not in response
def test_to_response_excludes_last_login(self, sample_user):
"""Test to_response excludes last_login"""
response = sample_user.to_response()
assert "last_login" not in response
def test_to_response_id_is_string(self, sample_user):
"""Test to_response converts id to string"""
response = sample_user.to_response()
assert isinstance(response["id"], str)
assert response["id"] == "stub-id"
def test_to_response_role_is_string_name(self, sample_user):
"""Test to_response converts role to string name"""
response = sample_user.to_response()
assert isinstance(response["role"], str)
assert response["role"] == "USER"
def test_to_response_with_none_full_name(self):
"""Test to_response when full_name is None"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="hashedpass",
full_name=None,
)
response = user.to_response()
assert response["full_name"] is None
def test_to_response_inactive_user(self):
"""Test to_response for inactive user"""
user = User(
username="inactiveuser",
email="inactive@example.com",
hashed_password="hashedpass",
is_active=False,
)
response = user.to_response()
assert response["is_active"] is False
def test_to_response_different_roles(self):
"""Test to_response for different user roles"""
admin_user = User(
username="admin",
email="admin@example.com",
hashed_password="pass",
role=UserRole.ADMIN,
)
superadmin_user = User(
username="superadmin",
email="super@example.com",
hashed_password="pass",
role=UserRole.SUPERADMIN,
)
assert admin_user.to_response()["role"] == "ADMIN"
assert superadmin_user.to_response()["role"] == "SUPERADMIN"
def test_to_response_returns_copy(self, sample_user):
"""Test to_response returns a copy, not reference"""
response1 = sample_user.to_response()
response2 = sample_user.to_response()
assert response1 is not response2
assert response1 == response2
# Modifying response1 should not affect response2
response1["username"] = "modified"
assert response2["username"] == sample_user.username
# ============================================================================
# Edge Cases and Error Handling Tests
# ============================================================================
class TestUserEdgeCases:
"""Test suite for edge cases and error handling"""
def test_user_with_empty_username(self):
"""Test user with empty username"""
user = User(
username="",
email="test@example.com",
hashed_password="hashedpass",
)
assert user.username == ""
def test_user_with_empty_email(self):
"""Test user with empty email"""
user = User(
username="testuser",
email="",
hashed_password="hashedpass",
)
assert user.email == ""
def test_user_with_empty_password(self):
"""Test user with empty password hash"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="",
)
assert user.hashed_password == ""
def test_user_with_none_role_not_allowed(self):
"""Test that None role is handled (if allowed)"""
# This tests what happens if None is passed for role
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
role=None, # type: ignore
)
assert user.role is None
def test_user_with_invalid_role_type(self):
"""Test user with invalid role type"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
role="invalid_role", # type: ignore
)
assert user.role == "invalid_role"
def test_user_attribute_modification(self):
"""Test user attributes can be modified after creation"""
user = User(
username="original",
email="original@example.com",
hashed_password="originalpass",
)
user.username = "modified"
user.email = "modified@example.com"
user.hashed_password = "modifiedpass"
user.is_active = False
user.full_name = "Modified Name"
assert user.username == "modified"
assert user.email == "modified@example.com"
assert user.hashed_password == "modifiedpass"
assert user.is_active is False
assert user.full_name == "Modified Name"
def test_user_to_response_after_modification(self):
"""Test to_response reflects attribute modifications"""
user = User(
username="original",
email="original@example.com",
hashed_password="pass",
)
response_before = user.to_response()
assert response_before["username"] == "original"
user.username = "modified"
response_after = user.to_response()
assert response_after["username"] == "modified"
# ============================================================================
# Async Concurrency Tests
# ============================================================================
class TestUserAsyncConcurrency:
"""Test suite for async behavior"""
@pytest.mark.asyncio
async def test_multiple_find_one_calls(self):
"""Test multiple concurrent find_one calls"""
results = await asyncio.gather(
User.find_one(username="user1"),
User.find_one(username="user2"),
User.find_one(email="test@example.com"),
)
assert all(r is None for r in results)
@pytest.mark.asyncio
async def test_multiple_save_calls(self):
"""Test multiple concurrent save calls on same user"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
)
# Multiple saves should not conflict
await asyncio.gather(
user.save(),
user.save(),
user.save(),
)
@pytest.mark.asyncio
async def test_concurrent_update_last_login(self):
"""Test concurrent update_last_login calls"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
)
# Multiple updates should complete without error
await asyncio.gather(
user.update_last_login(),
user.update_last_login(),
user.update_last_login(),
)
assert user.last_login is not None
# ============================================================================
# Integration-style Tests
# ============================================================================
class TestUserIntegration:
"""Integration-style tests for User model"""
@pytest.mark.asyncio
async def test_user_lifecycle(self):
"""Test complete user lifecycle"""
# Create user
user = User(
username="lifecycleuser",
email="lifecycle@example.com",
hashed_password="initialhash",
full_name="Lifecycle User",
role=UserRole.USER,
)
# Verify initial state
assert user.id == "stub-id"
assert user.last_login is None
# Save user
await user.save()
# Simulate first login
await user.update_last_login()
assert user.last_login is not None
first_login = user.last_login
# Get response representation
response = user.to_response()
assert response["username"] == "lifecycleuser"
assert response["role"] == "USER"
# Simulate subsequent login
await asyncio.sleep(0.01)
await user.update_last_login()
assert user.last_login >= first_login
# Try to find user (will return None in stub)
found = await User.find_one(username="lifecycleuser")
assert found is None
def test_multiple_users_response_consistency(self):
"""Test that multiple users have consistent response format"""
users = [
User(
username=f"user{i}",
email=f"user{i}@example.com",
hashed_password=f"pass{i}",
role=role,
)
for i, role in enumerate([UserRole.USER, UserRole.ADMIN, UserRole.SUPERADMIN])
]
responses = [u.to_response() for u in users]
# All responses should have same keys
expected_keys = {
"id",
"username",
"email",
"full_name",
"role",
"is_active",
"created_at",
}
for response in responses:
assert set(response.keys()) == expected_keys
# Verify role names are correct
assert responses[0]["role"] == "USER"
assert responses[1]["role"] == "ADMIN"
assert responses[2]["role"] == "SUPERADMIN"
# ============================================================================
# Performance and Stress Tests
# ============================================================================
class TestUserPerformance:
"""Performance-related tests"""
def test_user_creation_performance(self):
"""Test creating many users"""
users = []
for i in range(100):
user = User(
username=f"user{i}",
email=f"user{i}@example.com",
hashed_password=f"password{i}",
)
users.append(user)
assert len(users) == 100
assert all(u.username.startswith("user") for u in users)
def test_to_response_performance(self):
"""Test to_response on many users"""
user = User(
username="perfuser",
email="perf@example.com",
hashed_password="pass",
full_name="Performance User",
role=UserRole.ADMIN,
)
responses = [user.to_response() for _ in range(1000)]
assert len(responses) == 1000
assert all(r["username"] == "perfuser" for r in responses)
@pytest.mark.asyncio
async def test_find_one_performance(self):
"""Test find_one performance with many calls"""
tasks = [User.find_one(username=f"user{i}") for i in range(100)]
results = await asyncio.gather(*tasks)
assert all(r is None for r in results)
# ============================================================================
# Mock and Patch Tests
# ============================================================================
class TestUserMocking:
"""Tests using mocks and patches"""
@pytest.mark.asyncio
async def test_find_one_with_mocked_return(self):
"""Test find_one with mocked return value"""
mock_user = User(
username="mocked",
email="mocked@example.com",
hashed_password="mockedpass",
)
with patch.object(User, "find_one", new_callable=AsyncMock, return_value=mock_user):
result = await User.find_one(username="test")
assert result is not None
assert result.username == "mocked"
@pytest.mark.asyncio
async def test_save_with_mocked_behavior(self):
"""Test save with mocked behavior"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
)
with patch.object(user, "save", new_callable=AsyncMock) as mock_save:
await user.save()
mock_save.assert_called_once()
@pytest.mark.asyncio
async def test_update_last_login_with_mocked_datetime(self):
"""Test update_last_login with mocked datetime"""
user = User(
username="testuser",
email="test@example.com",
hashed_password="pass",
)
mock_time = datetime(2023, 6, 15, 12, 0, 0)
with patch("api.models.user.datetime") as mock_datetime:
mock_datetime.utcnow.return_value = mock_time
await user.update_last_login()
assert user.last_login == mock_time
# ============================================================================
# Type Safety and Contract Tests
# ============================================================================
class TestUserTypeSafety:
"""Tests for type safety and contracts"""
def test_user_id_type(self):
"""Test that id is always a string"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
assert isinstance(user.id, str)
def test_user_datetime_types(self):
"""Test datetime field types"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
assert isinstance(user.created_at, datetime)
assert user.last_login is None
# After update_last_login
asyncio.run(user.update_last_login())
assert isinstance(user.last_login, datetime)
def test_user_role_type(self):
"""Test role is UserRole enum"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
assert isinstance(user.role, UserRole)
def test_user_is_active_type(self):
"""Test is_active is boolean"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
assert isinstance(user.is_active, bool)
def test_to_response_returns_dict(self):
"""Test to_response returns dict"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
response = user.to_response()
assert isinstance(response, dict)
def test_to_response_value_types(self):
"""Test types of values in to_response"""
user = User(
username="test",
email="test@test.com",
hashed_password="pass",
)
response = user.to_response()
assert isinstance(response["id"], str)
assert isinstance(response["username"], str)
assert isinstance(response["email"], str)
assert isinstance(response["full_name"], type(None))
assert isinstance(response["role"], str)
assert isinstance(response["is_active"], bool)
assert isinstance(response["created_at"], datetime)
# ============================================================================
# Documentation and Docstring Tests
# ============================================================================
class TestUserDocumentation:
"""Tests for documentation and docstrings"""
def test_module_docstring(self):
"""Test module has docstring"""
import api.models.user as user_module
assert user_module.__doc__ is not None
assert "User model" in user_module.__doc__
def test_user_class_docstring(self):
"""Test User class has docstring"""
assert User.__doc__ is not None
assert "User" in User.__doc__
def test_user_role_docstring(self):
"""Test UserRole enum has docstring"""
assert UserRole.__doc__ is not None
def test_user_init_docstring(self):
"""Test User.__init__ has docstring"""
assert User.__init__.__doc__ is not None
def test_find_one_docstring(self):
"""Test find_one has docstring"""
assert User.find_one.__doc__ is not None
def test_save_docstring(self):
"""Test save has docstring"""
assert User.save.__doc__ is not None
def test_update_last_login_docstring(self):
"""Test update_last_login has docstring"""
assert User.update_last_login.__doc__ is not None
def test_to_response_docstring(self):
"""Test to_response has docstring"""
assert User.to_response.__doc__ is not None
# ============================================================================
# Module Import Tests
# ============================================================================
class TestModuleImports:
"""Tests for module imports"""
def test_import_user(self):
"""Test User can be imported"""
from api.models.user import User
assert User is not None
def test_import_user_role(self):
"""Test UserRole can be imported"""
from api.models.user import UserRole
assert UserRole is not None
def test_import_all(self):
"""Test all exports can be imported"""
from api.models.user import User, UserRole
assert User is not None
assert UserRole is not None
def test_module_attributes(self):
"""Test module has expected attributes"""
import api.models.user as user_module
assert hasattr(user_module, "User")
assert hasattr(user_module, "UserRole")
if __name__ == "__main__":
pytest.main([__file__, "-v"])

Xet Storage Details

Size:
30.8 kB
·
Xet hash:
c8980e8a3a44fcb534abe8b7cdb943f7f51103998e9dc3faec9fdae83eda1e56

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.