Skip to main content

Django Concurrent Test

PyPI version License Build Status Python versions Django versions

A production-ready Django package for safe and configurable concurrent testing with isolated databases, timing analytics, and concurrency simulation middleware.

🚀 Features

  • 🔒 Secure Database Templating: Zero-config parallel testing with isolated database instances
  • ⚡ Concurrent Test Execution: ThreadPoolExecutor-based parallel execution across isolated worker databases
  • 📊 Timing Analytics: Comprehensive test timing analysis and benchmarking
  • 🛡️ Concurrency Safety: Middleware for detecting race conditions and state mutations
  • 🔧 Runtime Configuration: Dynamic worker scaling and timeout management
  • 📈 Performance Monitoring: Connection pooling, resource monitoring, and metrics
  • 🎯 DRF Integration: Optional Django REST Framework compatibility
  • 📋 JUnit XML Output: CI/CD friendly test reporting
  • 🔍 Telemetry-Free: No data collection or external dependencies

📦 Installation

pip install django-concurrent-test

That pulls in Django, pytest and psutil, and nothing else. No database driver is installed: this package works through Django's connection abstraction and never imports psycopg2 or MySQLdb, so your project keeps using whichever driver it already has.

If you want one installed alongside it:

pip install django-concurrent-test[postgres]   # psycopg2-binary (wheel)
pip install django-concurrent-test[mysql]      # mysqlclient (needs MySQL C headers)

SQLite needs nothing extra.

🏃‍♂️ Quick Start

Basic Usage

# settings.py
TEST_RUNNER = 'django_concurrent_test.runner.ConcurrentTestRunner'

CONCURRENT_TEST = {
    'ENABLED': True,
    'WORKERS': 4,  # auto-detected if not set
}

Then run your tests normally:

python manage.py test

To enable via environment variable instead of settings:

DJANGO_ENABLE_CONCURRENT=True python manage.py test

Pytest Usage

# Run tests with concurrent execution
pytest --concurrent

# Specify number of workers
pytest --concurrent --workers 4

# Set timeouts
pytest --concurrent --timeout 300 --test-timeout 60 --worker-timeout 120

# Export timing data
pytest --concurrent --export-timings results.json

# Import previous timings and export to CSV
pytest --concurrent --import-timings results.json --export-timings-csv results.csv

# Import timings from a CSV instead of JSON
pytest --concurrent --import-timings-csv results.csv

🔧 Configuration

Environment Variables

# Enable concurrent testing
export DJANGO_ENABLE_CONCURRENT=True

# Configure workers (auto-detected if not set)
export DJANGO_TEST_WORKERS=4

# Set timeouts
export DJANGO_TEST_TIMEOUT=300
export DJANGO_TEST_BENCHMARK=True

# Override the production database guard (see Security Features)
export DJANGO_TEST_ALLOW_PRODUCTION_DB=True

Every variable the package reads, with its default:

Variable Default Purpose
DJANGO_ENABLE_CONCURRENT unset Enables concurrent execution. Accepts True, 1 or yes. Without this (or CONCURRENT_TEST['ENABLED']) tests run sequentially.
DJANGO_TEST_WORKERS auto-detected Worker count. Takes precedence over CONCURRENT_TEST['WORKERS'].
DJANGO_TEST_TIMEOUT 300 Base timeout in seconds; the other two timeouts derive from it.
DJANGO_TEST_TIMEOUT_PER_TEST 30 Per-test budget. See Timeout Management.
DJANGO_TEST_TIMEOUT_PER_WORKER DJANGO_TEST_TIMEOUT Per-worker budget, used for the "approaching timeout" warning.
DJANGO_TEST_TIMEOUT_GLOBAL 2 x DJANGO_TEST_TIMEOUT Hard bound on the whole concurrent run.
DJANGO_TEST_BENCHMARK False Writes the benchmark report. Set to True.
DJANGO_TEST_MAX_RETRIES 3 Retries per worker for retryable failures.
DJANGO_TEST_RETRY_DELAY 1.0 Seconds before the first retry; grows per attempt.
DJANGO_TEST_DYNAMIC_SCALING False Picks the worker count from CPU and memory. Set to True.
DJANGO_TEST_MIN_WORKERS 2 Floor for dynamic scaling.
DJANGO_TEST_MAX_WORKERS 16 Ceiling for dynamic scaling.
DJANGO_TEST_MAX_OPERATIONS 1000 Queries a worker connection serves before it is recycled.
DJANGO_TEST_HEALTH_CHECK_INTERVAL 60 Seconds between worker connection health checks.
DJANGO_TEST_ALLOW_PRODUCTION_DB False Overrides the production database guard.
DJANGO_TEST_TELEMETRY False Must stay off; setting it is refused. This package collects nothing.

DJANGO_DEBUG, DJANGO_SECRET_KEY and DATABASE_URL appear in the package's environment table but are not read on any code path, so setting them changes nothing here.

Django Settings

# settings.py
CONCURRENT_TEST = {
    'ENABLED': True,
    'WORKERS': 4,       # Auto-detected if not set
    'TIMEOUT': 300,     # Base timeout in seconds
    'TEST_TIMEOUT': 60, # Per-test budget
    'BENCHMARK': True,
}

These five keys are the whole of what this setting supports. The per-worker and global timeouts are environment-only (DJANGO_TEST_TIMEOUT_PER_WORKER, DJANGO_TEST_TIMEOUT_GLOBAL), and timing export is a pytest flag (--export-timings), not a setting.

🛡️ Concurrency Safety

Using assert_concurrent_safety

Test your functions for concurrent execution safety:

from django_concurrent_test.middleware import assert_concurrent_safety

def test_user_creation():
    """Test that user creation is safe for concurrent execution."""
    
    def create_user():
        from django.contrib.auth.models import User
        return User.objects.create_user(
            username=f'user_{time.time()}',
            email='test@example.com'
        )
    
    # This will run the function concurrently and check for race conditions
    assert_concurrent_safety(create_user, max_workers=4, iterations=10)

Using simulate_concurrent_requests

Simulate concurrent request scenarios:

from django_concurrent_test.middleware import simulate_concurrent_requests
from django.test import RequestFactory

def test_api_endpoint_concurrency():
    """Test API endpoint under concurrent load."""
    
    factory = RequestFactory()
    
    def make_request():
        request = factory.get('/api/users/')
        response = your_view_function(request)
        return response.status_code
    
    # Simulate 10 concurrent requests
    results = simulate_concurrent_requests(make_request, num_requests=10)
    
    # Check results
    successful = [r for r in results if r['status'] == 'success']
    assert len(successful) == 10

🔌 Middleware Integration

Auto-Registration

The middleware can be auto-registered during pytest sessions:

# conftest.py
import pytest
from django_concurrent_test.middleware import auto_register_middleware

@pytest.fixture(scope='session', autouse=True)
def setup_concurrent_middleware():
    """Auto-register concurrent testing middleware."""
    added_middleware = auto_register_middleware()
    if added_middleware:
        print(f"Auto-registered middleware: {added_middleware}")

Manual Configuration

Add middleware to your Django settings:

# settings.py
MIDDLEWARE = [
    # ... existing middleware
    'django_concurrent_test.middleware.ConcurrentSafetyMiddleware',
    'django_concurrent_test.middleware.StateMutationMiddleware',
    'django_concurrent_test.middleware.ConcurrencySimulationMiddleware',
]

Runtime Configuration

Configure middleware behavior at runtime:

from django_concurrent_test.middleware import (
    set_test_override, 
    concurrent_test_context
)

# Adjust middleware behavior
set_test_override('delay_range', (0.2, 0.8))
set_test_override('probability', 0.5)

# Use context manager for temporary changes
with concurrent_test_context():
    # All middleware uses testing configuration
    run_tests()

🍰 DRF Integration

Testing DRF Viewsets

from django_concurrent_test.middleware import assert_concurrent_safety
from rest_framework.test import APITestCase
from rest_framework import status

class UserViewSetTest(APITestCase):
    def test_concurrent_user_creation(self):
        """Test concurrent user creation via DRF."""
        
        def create_user_via_api():
            data = {
                'username': f'user_{time.time()}',
                'email': 'test@example.com',
                'password': 'testpass123'
            }
            response = self.client.post('/api/users/', data)
            return response.status_code
        
        # Test concurrent API calls
        assert_concurrent_safety(create_user_via_api, max_workers=4, iterations=5)

Testing DRF Serializers

from django_concurrent_test.middleware import assert_concurrent_safety
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'email']

def test_serializer_concurrency():
    """Test serializer validation under concurrent load."""
    
    def validate_user_data():
        data = {
            'username': f'user_{time.time()}',
            'email': 'test@example.com'
        }
        serializer = UserSerializer(data=data)
        return serializer.is_valid()
    
    assert_concurrent_safety(validate_user_data, max_workers=4, iterations=10)

📊 Timing Analytics

Export and Import Timing Data

from django_concurrent_test.timing_utils import (
    load_timings, 
    save_timings, 
    filter_timings,
    export_timings_to_csv
)

# Load timing data
timings = load_timings('test_timings.json')

# Filter slow tests
slow_tests = filter_timings(timings, min_duration=5.0)

# Export to CSV
export_timings_to_csv(slow_tests, 'slow_tests.csv')

# Analyze timing data
for test_name, timing_data in slow_tests.items():
    print(f"{test_name}: {timing_data['duration']:.2f}s")

Benchmark Analysis

from django_concurrent_test.timing_utils import get_slowest_tests, get_fastest_tests

# Get performance insights
slowest = get_slowest_tests(timings, count=5)
fastest = get_fastest_tests(timings, count=5)

print("Slowest tests:")
for test_name, duration in slowest:
    print(f"  {test_name}: {duration:.2f}s")

print("Fastest tests:")
for test_name, duration in fastest:
    print(f"  {test_name}: {duration:.2f}s")

🔒 Security Features

Environment Validation

from django_concurrent_test.security import validate_environment, get_safe_worker_count

# Validate worker count and timeout settings
validate_environment()

# Query the auto-detected safe worker count
worker_count = get_safe_worker_count()
print(f"Safe worker count: {worker_count}")

Production Database Guard

Concurrent testing clones databases and drops them again, so the runner refuses to start if it looks aimed at a real one. Before any database is created it checks every alias in DATABASES and raises SecurityException if a name looks production-like. The check runs on every entry point: the test runner (concurrent or not) and pytest --concurrent.

Names are matched whole words, splitting on anything that is not a letter or digit — which includes path separators, so each component of a SQLite path is inspected on its own. A name is production-like when any word is exactly prod, production, live or staging:

Name Refused?
prod_main, myapp_prod, billing_prod_db yes
production, myapp_live, staging_main yes
/var/lib/myapp/prod_main.sqlite3 yes
delivery, olive_oil, product_catalog no — live/prod are not whole words here
test_main, myapp_test, ci_test, myapp_testing no — exempt

Any name with a word starting test is exempt, and that exemption is checked first, so prod_test counts as a test database. latest and contest do not exempt a name — they merely contain "test".

Two names are checked per alias, in this order:

  • TEST['NAME'] — the database Django actually creates and destroys, so this is the one that matters most.
  • NAME — your real database. Django never touches it during tests, but a production-like value here means the run is misaimed.

Aliases configured with TEST['MIRROR'] are skipped, since Django neither creates nor destroys a mirrored database.

from django_concurrent_test.security import (
    is_production_database,
    validate_database_configuration,
)

is_production_database('myapp_prod')   # True
is_production_database('myapp_test')   # False
is_production_database('delivery')     # False

# Raises SecurityException if any alias looks production-like
validate_database_configuration()

The heuristic can still be wrong about your naming, so it can be overridden. The bypass is logged every time:

export DJANGO_TEST_ALLOW_PRODUCTION_DB=True

Resource Monitoring

from django_concurrent_test.security import check_system_resources

# Check system resources
resources = check_system_resources()
print(f"Available memory: {resources['memory_available_gb']:.1f}GB")
print(f"CPU cores: {resources['cpu_count']}")
print(f"Safe worker count: {resources['safe_worker_count']}")

🧪 Advanced Testing

Custom Test Runner

from django_concurrent_test.runner import ConcurrentTestRunner

class CustomConcurrentRunner(ConcurrentTestRunner):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.custom_metrics = {}
    
    def run_tests(self, test_labels, **kwargs):
        # Custom pre-test setup
        self.setup_custom_environment()
        
        # Run tests with concurrent execution
        failures = super().run_tests(test_labels, **kwargs)
        
        # Custom post-test cleanup
        self.cleanup_custom_environment()
        
        return failures

Database Isolation

The runner automatically verifies worker database isolation before starting. Each worker gets its own cloned database via a dct_worker_N Django connection alias, so tests in different workers never share database state.

To check if a database is ready before connecting:

from django_concurrent_test.db import wait_for_database_ready

ready = wait_for_database_ready('test_db', timeout=30)
assert ready, "Database not ready within timeout"

📈 Performance Monitoring

Connection Pool Statistics

from django_concurrent_test.db import get_connection_pool_stats

# Get connection pool metrics
stats = get_connection_pool_stats()
print(f"Active connections: {stats.get('active', 0)}")
print(f"Pooled connections: {stats.get('pooled', 0)}")
print(f"Connection hits: {stats.get('hits', 0)}")
print(f"Connection misses: {stats.get('misses', 0)}")

Memory-Based Scaling

The package automatically scales worker count based on available memory:

from django_concurrent_test.runner import ConcurrentTestRunner

# Memory-based scaling is automatic
runner = ConcurrentTestRunner()
# Worker count will be calculated based on available memory

🚨 Error Handling

Timeout Management

Three timeouts apply, from narrowest to widest:

# Per test: a test class exceeding this budget is reported as an error
export DJANGO_TEST_TIMEOUT_PER_TEST=30

# Per worker: logs a warning as a worker approaches this
export DJANGO_TEST_TIMEOUT_PER_WORKER=300

# Global: hard bound on the whole run; workers still running are failed
export DJANGO_TEST_TIMEOUT_GLOBAL=600

Keep them ordered per-test < per-worker < global; the runner logs a warning if they are not.

What enforcement actually means here. Tests run in threads, and Python cannot interrupt running code in another thread, so the per-test budget is not preemptive: a class that overruns is detected when it finishes and reported as an error, which fails the run. The global timeout is the real bound — once it expires the runner stops waiting, counts every unfinished worker as a failure, and returns. A test wedged in an uninterruptible call cannot be killed, so the process may still wait on that thread at exit.

A per-test overrun surfaces through the normal failure count, so no special handling is needed in test code:

$ DJANGO_TEST_TIMEOUT_PER_TEST=1 python manage.py test
# [CONCURRENT] SlowTests exceeded its per-test budget (3.00s > 1s)

Database Error Recovery

from django_concurrent_test.db import wait_for_database_ready

def test_database_recovery():
    """Test database connection recovery."""
    
    # Wait for database to be ready
    ready = wait_for_database_ready('test_db', timeout=30)
    assert ready, "Database not ready within timeout"

🔧 Development

Running Tests

# Run package tests
pytest tests/

# Run with coverage
pytest --cov=django_concurrent_test tests/

# Run with concurrent execution
pytest --concurrent tests/

Building and Publishing

# Build package
python -m build

# Upload to PyPI
twine upload dist/*

📋 Requirements

  • Python 3.9+
  • Django 3.2+
  • PostgreSQL 10+ or MySQL 5.7+ (for production features)
  • SQLite (for development)

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

📞 Contact

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Django team for the excellent testing framework
  • PostgreSQL and MySQL communities for database support
  • All contributors who have helped improve this package

📞 Support


Made with ❤️ for the Django community

Metadata

Release files for django-concurrent-test 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-concurrent-test 1.1.0
File Size Uploaded Provenance Actions
django_concurrent_test-1.1.0.tar.gz 100.6 kB Without provenance Details for django_concurrent_test-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-concurrent-test 1.1.0
File Interpreter ABI Platform Actions
django_concurrent_test-1.1.0-py3-none-any.whl Python 3 none any Details for django_concurrent_test-1.1.0-py3-none-any.whl

Total release size: 152.1 kB

Release files / django_concurrent_test-1.1.0.tar.gz

Download URL django_concurrent_test-1.1.0.tar.gz
Size 100.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ba441aea3e1c32e79fe117a70f8b8397c8a9b1ca3ffda642f3019c772b8b8ad9
BLAKE2b-256 checksum
How to use checksums
c83731bd6dc73e31b9bc78ce46189d2ec4779c795b964d96db5de8fef92dad9d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / django_concurrent_test-1.1.0-py3-none-any.whl

Download URL django_concurrent_test-1.1.0-py3-none-any.whl
Size 51.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0e4c6bc2fc6295726714305630065911a156ca7d26234a5758d99229b5b62e07
BLAKE2b-256 checksum
How to use checksums
f2ac30572caa26fcc8218074d6dc2d0a588ca9a1e1b403c03cede5c9882984bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for django-concurrent-test 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page