CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pytest-django

A Django plugin for pytest that provides Django-specific testing fixtures, marks, and assertions.

Pending
Overview
Eval results
Files

settings-management.mddocs/

Settings Management

Django settings configuration and temporary modification fixtures. The settings fixture allows temporary modification of Django settings that are automatically restored after test completion.

Capabilities

Settings Wrapper

Fixture providing temporary Django settings modification with automatic restoration.

def settings() -> SettingsWrapper:
    """
    Django settings wrapper for temporary modification.
    
    Provides a wrapper around Django settings that allows temporary
    modification of settings values. Changes are automatically reverted
    after test completion. Supports both attribute access and context
    manager usage.
    
    Returns:
        SettingsWrapper: Settings wrapper with modification capabilities
    """

class SettingsWrapper:
    """Django settings wrapper with context manager support."""
    
    def __setattr__(self, name: str, value: Any) -> None:
        """
        Set a Django setting temporarily.
        
        Args:
            name: Setting name (e.g., 'DEBUG', 'SECRET_KEY')
            value: Setting value
        """
    
    def __getattr__(self, name: str) -> Any:
        """
        Get a Django setting value.
        
        Args:
            name: Setting name
            
        Returns:
            Any: Setting value
        """
    
    def __enter__(self) -> SettingsWrapper:
        """Context manager entry."""
    
    def __exit__(self, exc_type, exc_value, traceback) -> None:
        """Context manager exit with automatic restoration."""

Usage examples:

# Direct attribute modification
def test_with_debug_enabled(settings):
    settings.DEBUG = True
    settings.SECRET_KEY = "test-secret-key"
    settings.ALLOWED_HOSTS = ["testserver", "localhost"]
    
    # Test code that depends on these settings
    assert settings.DEBUG is True
    # Settings automatically restored after test

# Context manager usage
def test_with_context_manager(settings):
    original_debug = settings.DEBUG
    
    with settings:
        settings.DEBUG = False
        settings.USE_I18N = False
        # Test code with modified settings
        assert settings.DEBUG is False
    
    # Settings restored to original values
    assert settings.DEBUG == original_debug

# Testing cache configuration
def test_cache_settings(settings):
    settings.CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test-cache',
        }
    }
    # Test cache-dependent functionality

# Testing database configuration
def test_custom_database(settings):
    settings.DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
        }
    }
    # Test with custom database settings

# Testing middleware modification
def test_custom_middleware(settings):
    settings.MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'myapp.middleware.CustomMiddleware',
    ]
    # Test with custom middleware stack

# Testing email configuration
def test_email_settings(settings):
    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
    settings.DEFAULT_FROM_EMAIL = 'test@example.com'
    # Test email functionality

Settings Types

from typing import Any, Dict, List, Optional, Union
from types import ModuleType

# Common Django setting types
DatabaseConfig = Dict[str, Union[str, Dict[str, Any]]]
CacheConfig = Dict[str, Dict[str, Any]]
MiddlewareList = List[str]
AppsList = List[str]
EmailBackend = str

# Settings wrapper implementation
class SettingsWrapper:
    """Wrapper for Django settings with temporary modification support."""
    
    # Common Django settings with type hints
    DEBUG: bool
    SECRET_KEY: str
    ALLOWED_HOSTS: List[str]
    INSTALLED_APPS: List[str]
    MIDDLEWARE: List[str]
    ROOT_URLCONF: str
    DATABASES: Dict[str, DatabaseConfig]
    CACHES: Dict[str, CacheConfig]
    USE_I18N: bool
    USE_L10N: bool
    USE_TZ: bool
    TIME_ZONE: str
    LANGUAGE_CODE: str
    STATIC_URL: str
    MEDIA_URL: str
    STATIC_ROOT: Optional[str]
    MEDIA_ROOT: Optional[str]
    EMAIL_BACKEND: str
    DEFAULT_FROM_EMAIL: str
    LOGGING: Dict[str, Any]
    
    # Authentication settings
    AUTH_USER_MODEL: str
    LOGIN_URL: str
    LOGIN_REDIRECT_URL: str
    LOGOUT_REDIRECT_URL: str
    
    # Session settings
    SESSION_ENGINE: str
    SESSION_COOKIE_AGE: int
    SESSION_COOKIE_NAME: str
    
    # Security settings
    CSRF_COOKIE_SECURE: bool
    SESSION_COOKIE_SECURE: bool
    SECURE_SSL_REDIRECT: bool
    
    def __setitem__(self, key: str, value: Any) -> None: ...
    def __getitem__(self, key: str) -> Any: ...
    def __delattr__(self, name: str) -> None: ...
    def __contains__(self, key: str) -> bool: ...

Install with Tessl CLI

npx tessl i tessl/pypi-pytest-django

docs

client-testing.md

database-testing.md

django-assertions.md

django-utilities.md

email-testing.md

index.md

live-server-testing.md

pytest-marks.md

query-testing.md

settings-management.md

transaction-callbacks.md

user-management.md

tile.json