django-test-enforcer 0.1.0
Comprehensive Django testing enforcement library that ensures 100% test coverage across views, UI elements, and functions
License: MIT
Requires Python: >=3.8
Keywords: django, testing, coverage, pytest, playwright, test-automation

# Django Test Enforcer 🛡️

[![PyPI version](https://badge.fury.io/py/django-test-enforcer.svg)](https://badge.fury.io/py/django-test-enforcer)
[![Python Versions](https://img.shields.io/pypi/pyversions/django-test-enforcer.svg)](https://pypi.org/project/django-test-enforcer/)
[![Django Versions](https://img.shields.io/badge/django-3.2%20%7C%204.0%20%7C%204.1%20%7C%204.2%20%7C%205.0-blue)](https://www.djangoproject.com/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://github.com/arpansahu/django-test-enforcer/workflows/tests/badge.svg)](https://github.com/arpansahu/django-test-enforcer/actions)
[![Coverage](https://codecov.io/gh/arpansahu/django-test-enforcer/branch/main/graph/badge.svg)](https://codecov.io/gh/arpansahu/django-test-enforcer)

**Comprehensive Django testing enforcement library that ensures 100% test coverage across views, UI elements, and functions.**

Django Test Enforcer automatically scans your Django project and enforces test coverage for:
- ✅ **Backend Views** (function-based, class-based, generic views)
- ✅ **UI Elements** (buttons, forms, links, inputs)
- ✅ **Functions & Utilities** (business logic, helpers)
- ✅ **API Endpoints** (Django REST Framework)

## 🚀 Features

- **Automatic Discovery**: Scans your entire Django project to find all testable components
- **Coverage Enforcement**: Fails your CI/CD build if coverage requirements aren't met
- **Test Generation**: Auto-generates test stubs for missing coverage
- **Pytest Integration**: Seamless pytest plugin with custom markers and hooks
- **Rich Reports**: Beautiful console and HTML reports showing coverage gaps
- **Django Commands**: Management commands for quick checks and test generation
- **Configurable Rules**: Fine-grained control over coverage requirements
- **UI Testing Support**: Playwright and Selenium integration for UI tests

## 📦 Installation

```bash
# Basic installation
pip install django-test-enforcer

# With UI testing support (Playwright)
pip install django-test-enforcer[ui]

# With API testing support (DRF)
pip install django-test-enforcer[api]

# Full installation
pip install django-test-enforcer[all]
```

## ⚡ Quick Start

### 1. Add to Django Settings

```python
INSTALLED_APPS = [
    ...
    'django_test_enforcer',
]
```

### 2. Configure pytest (optional)

```toml
# pyproject.toml
[tool.django_test_enforcer]
enforcement_level = "strict"  # "strict", "warning", or "off"
min_view_coverage = 100
min_ui_coverage = 90
min_function_coverage = 80
```

### 3. Run Tests with Enforcement

```bash
# Check coverage without failing
pytest --check-coverage

# Enforce coverage (fails build if not met)
pytest --enforce-coverage

# Generate missing test stubs
pytest --generate-tests

# Show detailed coverage report
pytest --coverage-report
```

## 📊 Django Management Commands

```bash
# Check current test coverage
python manage.py check_coverage

# Check specific categories
python manage.py check_coverage --views
python manage.py check_coverage --ui
python manage.py check_coverage --functions

# Generate missing tests
python manage.py generate_tests
python manage.py generate_tests --output tests/auto_generated/

# Enforce tests (for CI/CD)
python manage.py enforce_tests --fail-on-missing
```

## 🎯 Example Output

```
════════════════════════════════════════════════════════════════
Django Test Enforcer Report
════════════════════════════════════════════════════════════════

View Coverage:        85% (34/40 views tested) ⚠️
UI Coverage:          92% (115/125 elements tested) ✅
Function Coverage:    78% (156/200 functions tested) ❌
API Coverage:         100% (20/20 endpoints tested) ✅

════════════════════════════════════════════════════════════════
Missing Tests (20 items):
════════════════════════════════════════════════════════════════

VIEWS (6):
  ✗ myapp.views.send_notification
  ✗ myapp.views.publish_event
  ✗ myapp.views.dashboard

UI ELEMENTS (10):
  ✗ Button: "Submit" (templates/form.html:45)
  ✗ Form: notification_form (templates/send.html:23)
  ✗ Link: /dashboard/ (templates/home.html:67)

FUNCTIONS (4):
  ✗ utils.helpers.calculate_stats
  ✗ services.notification.process_queue

════════════════════════════════════════════════════════════════
Generate missing tests with:
  pytest --generate-tests
  or
  python manage.py generate_tests
════════════════════════════════════════════════════════════════
```

## 📖 Configuration

### Full Configuration Example

```toml
[tool.django_test_enforcer]
# Enforcement level: "strict" (fail build), "warning" (show warnings), "off"
enforcement_level = "strict"

# Minimum coverage percentages
min_view_coverage = 100
min_ui_coverage = 90
min_function_coverage = 80
min_api_coverage = 100

# What to scan
scan_views = true
scan_templates = true
scan_functions = true
scan_apis = true

# Excluded paths (glob patterns)
exclude_paths = [
    "*/migrations/*",
    "*/tests/*",
    "*/admin.py",
    "*/apps.py",
]

# Test generation
auto_generate_stubs = true
test_output_dir = "tests/auto_generated"
ui_framework = "playwright"  # or "selenium"

# Custom rules
[tool.django_test_enforcer.rules]
require_authenticated_tests = true
require_permission_tests = true
require_form_validation_tests = true
require_error_handling_tests = true
require_api_pagination_tests = true
```

## 🔌 CI/CD Integration

### GitHub Actions

```yaml
name: Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: |
          pip install -r requirements.txt
          pip install django-test-enforcer[all]
      
      - name: Run tests with enforcement
        run: pytest --enforce-coverage --cov
```

### Jenkins

```groovy
stage('Test Coverage Enforcement') {
    steps {
        sh 'pytest --enforce-coverage --junitxml=results.xml'
    }
    post {
        always {
            junit 'results.xml'
        }
        failure {
            echo 'Test coverage requirements not met!'
        }
    }
}
```

## 🎨 Generated Test Examples

### View Test (Auto-generated)

```python
def test_send_notification_view_get(client, authenticated_user):
    """Test send_notification view GET request"""
    client.force_login(authenticated_user)
    response = client.get('/messaging/send/')
    assert response.status_code == 200
    assert 'form' in response.context

def test_send_notification_view_post(client, authenticated_user):
    """Test send_notification view POST request"""
    client.force_login(authenticated_user)
    data = {
        'title': 'Test Notification',
        'message': 'Test message',
        'priority': 'high'
    }
    response = client.post('/messaging/send/', data)
    assert response.status_code == 302  # Redirect after success
```

### UI Test (Auto-generated)

```python
def test_submit_button_notification_form(page, authenticated_page):
    """Test Submit button in notification form"""
    page.goto('/messaging/send/')
    page.fill('input[name="title"]', 'Test')
    page.fill('textarea[name="message"]', 'Test message')
    page.click('button[type="submit"]')
    page.wait_for_url('**/dashboard/')
    assert 'success' in page.content().lower()
```

## 📚 Documentation

Full documentation available at [django-test-enforcer.readthedocs.io](https://django-test-enforcer.readthedocs.io)

- [Installation Guide](https://django-test-enforcer.readthedocs.io/en/latest/installation/)
- [Configuration](https://django-test-enforcer.readthedocs.io/en/latest/configuration/)
- [Usage Examples](https://django-test-enforcer.readthedocs.io/en/latest/examples/)
- [API Reference](https://django-test-enforcer.readthedocs.io/en/latest/api/)

## 🤝 Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.

```bash
# Clone repository
git clone https://github.com/arpansahu/django-test-enforcer.git
cd django-test-enforcer

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install in development mode
pip install -e ".[dev,all]"

# Run tests
pytest

# Run linters
black .
isort .
flake8
mypy django_test_enforcer
```

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details

## 🌟 Star History

[![Star History Chart](https://api.star-history.com/svg?repos=arpansahu/django-test-enforcer&type=Date)](https://star-history.com/#arpansahu/django-test-enforcer&Date)

## 💬 Support

- 📖 [Documentation](https://django-test-enforcer.readthedocs.io)
- 🐛 [Issue Tracker](https://github.com/arpansahu/django-test-enforcer/issues)
- 💬 [Discussions](https://github.com/arpansahu/django-test-enforcer/discussions)
- 📧 [Email Support](mailto:arpansahu@gmail.com)

## 🙏 Acknowledgments

Built with ❤️ by [Arpan Sahu](https://github.com/arpansahu)

Inspired by the Django and pytest communities.