Add environment configuration and email settings
- Created a new .env.example file for environment variable configuration including Django settings, email configurations, and common SMTP provider examples. - Updated .vscode/settings.json to include additional words for spell checking. - Enhanced config/settings.py to load environment variables using python-dotenv, added data directory management, and configured email settings. - Updated config/urls.py to include debug toolbar URLs conditionally based on testing. - Added pytest configuration in conftest.py for Django testing. - Created core application with custom User model, admin registration, and migrations. - Implemented tests for User model and admin functionalities. - Updated pyproject.toml to include new dependencies for debugging and environment management. - Updated uv.lock to reflect new package versions and dependencies.
This commit is contained in:
parent
11c3db9817
commit
96a159f691
16 changed files with 697 additions and 57 deletions
0
core/__init__.py
Normal file
0
core/__init__.py
Normal file
9
core/admin.py
Normal file
9
core/admin.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.admin import UserAdmin
|
||||
|
||||
from core.models import User
|
||||
|
||||
# Register your custom User model with the admin
|
||||
admin.site.register(User, UserAdmin)
|
||||
17
core/apps.py
Normal file
17
core/apps.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class CoreConfig(AppConfig):
|
||||
"""Configuration class for the 'core' Django application.
|
||||
|
||||
Attributes:
|
||||
default_auto_field (str): Specifies the type of auto-created primary key field to use for models in this app.
|
||||
name (str): The full Python path to the application.
|
||||
verbose_name (str): A human-readable name for the application.
|
||||
"""
|
||||
|
||||
default_auto_field: str = "django.db.models.BigAutoField"
|
||||
name = "core"
|
||||
verbose_name: str = "Core Application"
|
||||
44
core/migrations/0001_initial.py
Normal file
44
core/migrations/0001_initial.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# Generated by Django 5.2.4 on 2025-07-08 00:33
|
||||
|
||||
import django.contrib.auth.models
|
||||
import django.contrib.auth.validators
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='User',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('password', models.CharField(max_length=128, verbose_name='password')),
|
||||
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
|
||||
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
|
||||
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
|
||||
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
|
||||
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
|
||||
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
|
||||
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
|
||||
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
|
||||
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
|
||||
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
|
||||
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'User',
|
||||
'verbose_name_plural': 'Users',
|
||||
'db_table': 'auth_user',
|
||||
},
|
||||
managers=[
|
||||
('objects', django.contrib.auth.models.UserManager()),
|
||||
],
|
||||
),
|
||||
]
|
||||
0
core/migrations/__init__.py
Normal file
0
core/migrations/__init__.py
Normal file
21
core/models.py
Normal file
21
core/models.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
|
||||
class User(AbstractUser):
|
||||
"""Custom User model extending Django's AbstractUser.
|
||||
|
||||
This allows for future customization of the User model
|
||||
while maintaining all the default Django User functionality.
|
||||
"""
|
||||
|
||||
# Add any custom fields here in the future
|
||||
# For example:
|
||||
# bio = models.TextField(max_length=500, blank=True)
|
||||
# avatar = models.ImageField(upload_to='avatars/', blank=True, null=True)
|
||||
|
||||
class Meta:
|
||||
db_table = "auth_user" # Keep the same table name as Django's default User
|
||||
verbose_name = "User"
|
||||
verbose_name_plural = "Users"
|
||||
0
core/tests/__init__.py
Normal file
0
core/tests/__init__.py
Normal file
86
core/tests/test_admin.py
Normal file
86
core/tests/test_admin.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.admin import UserAdmin
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.db.models.base import Model
|
||||
from django.test import RequestFactory
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.contrib.admin import ModelAdmin
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.db.models.base import Model
|
||||
|
||||
User: type[AbstractUser] = get_user_model()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUserAdmin:
|
||||
"""Test cases for User admin configuration."""
|
||||
|
||||
def setup_method(self) -> None:
|
||||
"""Set up test data for each test method."""
|
||||
self.factory = RequestFactory()
|
||||
self.superuser: AbstractUser = User.objects.create_superuser(
|
||||
username="admin",
|
||||
email="admin@example.com",
|
||||
password="test_admin_password_123",
|
||||
)
|
||||
|
||||
def test_user_model_registered_in_admin(self) -> None:
|
||||
"""Test that User model is registered in Django admin."""
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
assert User in registry
|
||||
|
||||
def test_user_admin_class(self) -> None:
|
||||
"""Test that User is registered with UserAdmin."""
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
admin_class: admin.ModelAdmin[Any] = registry[User]
|
||||
assert isinstance(admin_class, UserAdmin)
|
||||
|
||||
def test_user_admin_can_create_user(self) -> None:
|
||||
"""Test that admin can create users through the interface."""
|
||||
# Test that the admin form can handle user creation
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
user_admin: admin.ModelAdmin[Any] = registry[User]
|
||||
|
||||
# Check that the admin has the expected methods
|
||||
assert hasattr(user_admin, "get_form")
|
||||
assert hasattr(user_admin, "save_model")
|
||||
|
||||
def test_user_admin_list_display(self) -> None:
|
||||
"""Test admin list display configuration."""
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
user_admin: admin.ModelAdmin[Any] = registry[User]
|
||||
|
||||
# UserAdmin should have default list_display
|
||||
expected_fields: tuple[str, ...] = (
|
||||
"username",
|
||||
"email",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"is_staff",
|
||||
)
|
||||
assert user_admin.list_display == expected_fields
|
||||
|
||||
def test_user_admin_search_fields(self) -> None:
|
||||
"""Test admin search fields configuration."""
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
user_admin: admin.ModelAdmin[Any] = registry[User]
|
||||
|
||||
# UserAdmin should have default search fields
|
||||
expected_search_fields: tuple[str, ...] = ("username", "first_name", "last_name", "email")
|
||||
assert user_admin.search_fields == expected_search_fields
|
||||
|
||||
def test_user_admin_fieldsets(self) -> None:
|
||||
"""Test admin fieldsets configuration."""
|
||||
registry: dict[type[Model], ModelAdmin[Any]] = admin.site._registry # noqa: SLF001
|
||||
user_admin: admin.ModelAdmin[Any] = registry[User]
|
||||
|
||||
# UserAdmin should have fieldsets defined
|
||||
assert hasattr(user_admin, "fieldsets")
|
||||
assert user_admin.fieldsets is not None
|
||||
178
core/tests/test_models.py
Normal file
178
core/tests/test_models.py
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.contrib.auth.models import AbstractUser
|
||||
|
||||
User: type[AbstractUser] = get_user_model()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUserModel:
|
||||
"""Test cases for the custom User model."""
|
||||
|
||||
def test_create_user(self) -> None:
|
||||
"""Test creating a regular user."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
assert user.username == "testuser"
|
||||
assert user.email == "test@example.com"
|
||||
assert user.check_password("testpass123")
|
||||
assert not user.is_staff
|
||||
assert not user.is_superuser
|
||||
assert user.is_active
|
||||
|
||||
def test_create_superuser(self) -> None:
|
||||
"""Test creating a superuser."""
|
||||
superuser: AbstractUser = User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123")
|
||||
|
||||
assert superuser.username == "admin"
|
||||
assert superuser.email == "admin@example.com"
|
||||
assert superuser.check_password("adminpass123")
|
||||
assert superuser.is_staff
|
||||
assert superuser.is_superuser
|
||||
assert superuser.is_active
|
||||
|
||||
def test_user_str_representation(self) -> None:
|
||||
"""Test the string representation of the user."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com")
|
||||
|
||||
assert str(user) == "testuser"
|
||||
|
||||
def test_user_email_field(self) -> None:
|
||||
"""Test that email field works correctly."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
assert user.email == "test@example.com"
|
||||
|
||||
# Test email update
|
||||
user.email = "newemail@example.com"
|
||||
user.save()
|
||||
user.refresh_from_db()
|
||||
|
||||
assert user.email == "newemail@example.com"
|
||||
|
||||
def test_user_unique_username(self) -> None:
|
||||
"""Test that username must be unique."""
|
||||
User.objects.create_user(username="testuser", email="test1@example.com", password="testpass123")
|
||||
|
||||
# Attempting to create another user with the same username should raise an error
|
||||
with pytest.raises(IntegrityError):
|
||||
User.objects.create_user(username="testuser", email="test2@example.com", password="testpass123")
|
||||
|
||||
def test_user_password_hashing(self) -> None:
|
||||
"""Test that passwords are properly hashed."""
|
||||
password = "testpass123"
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password=password)
|
||||
|
||||
# Password should be hashed, not stored in plain text
|
||||
assert user.password != password
|
||||
assert user.check_password(password)
|
||||
assert not user.check_password("wrongpassword")
|
||||
|
||||
def test_user_without_email(self) -> None:
|
||||
"""Test creating a user without email."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", password="testpass123")
|
||||
|
||||
assert user.username == "testuser"
|
||||
assert not user.email
|
||||
assert user.check_password("testpass123")
|
||||
|
||||
def test_user_model_meta_options(self) -> None:
|
||||
"""Test the model meta options."""
|
||||
assert User._meta.db_table == "auth_user" # noqa: SLF001
|
||||
assert User._meta.verbose_name == "User" # noqa: SLF001
|
||||
assert User._meta.verbose_name_plural == "Users" # noqa: SLF001
|
||||
|
||||
def test_user_manager_methods(self) -> None:
|
||||
"""Test User manager methods."""
|
||||
# Test create_user method
|
||||
user: AbstractUser = User.objects.create_user(username="regularuser", email="regular@example.com", password="pass123")
|
||||
assert not user.is_staff
|
||||
assert not user.is_superuser
|
||||
|
||||
# Test create_superuser method
|
||||
superuser: AbstractUser = User.objects.create_superuser(username="superuser", email="super@example.com", password="superpass123")
|
||||
assert superuser.is_staff
|
||||
assert superuser.is_superuser
|
||||
|
||||
def test_user_permissions(self) -> None:
|
||||
"""Test user permissions and groups."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
# Initially user should have no permissions
|
||||
assert not user.user_permissions.exists()
|
||||
assert not user.groups.exists()
|
||||
|
||||
# Test has_perm method (should be False for regular user)
|
||||
assert not user.has_perm("auth.add_user")
|
||||
|
||||
def test_user_active_status(self) -> None:
|
||||
"""Test user active status functionality."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
# User should be active by default
|
||||
assert user.is_active
|
||||
|
||||
# Test deactivating user
|
||||
user.is_active = False
|
||||
user.save()
|
||||
user.refresh_from_db()
|
||||
|
||||
assert not user.is_active
|
||||
|
||||
def test_user_date_joined(self) -> None:
|
||||
"""Test that date_joined is automatically set."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
assert user.date_joined is not None
|
||||
|
||||
def test_user_last_login_initially_none(self) -> None:
|
||||
"""Test that last_login is initially None."""
|
||||
user: AbstractUser = User.objects.create_user(username="testuser", email="test@example.com", password="testpass123")
|
||||
|
||||
assert user.last_login is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestUserModelEdgeCases:
|
||||
"""Test edge cases and error conditions for the User model."""
|
||||
|
||||
def test_create_user_without_username(self) -> None:
|
||||
"""Test that creating a user without username raises an error."""
|
||||
with pytest.raises(ValueError, match="The given username must be set"):
|
||||
User.objects.create_user(username="", email="test@example.com", password="testpass123")
|
||||
|
||||
def test_create_superuser_without_is_staff(self) -> None:
|
||||
"""Test that create_superuser enforces is_staff=True."""
|
||||
with pytest.raises(ValueError, match=r"Superuser must have is_staff=True."):
|
||||
User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123", is_staff=False)
|
||||
|
||||
def test_create_superuser_without_is_superuser(self) -> None:
|
||||
"""Test that create_superuser enforces is_superuser=True."""
|
||||
with pytest.raises(ValueError, match=r"Superuser must have is_superuser=True."):
|
||||
User.objects.create_superuser(username="admin", email="admin@example.com", password="adminpass123", is_superuser=False)
|
||||
|
||||
def test_user_with_very_long_username(self) -> None:
|
||||
"""Test username length validation."""
|
||||
# Django's default max_length for username is 150
|
||||
long_username: str = "a" * 151
|
||||
|
||||
user = User(username=long_username, email="test@example.com")
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
user.full_clean()
|
||||
|
||||
def test_user_with_invalid_email_format(self) -> None:
|
||||
"""Test email format validation."""
|
||||
user = User(username="testuser", email="invalid-email-format")
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
user.full_clean()
|
||||
Loading…
Add table
Add a link
Reference in a new issue