Skip to content

Quick Start

smattymatty edited this page Aug 25, 2025 · 2 revisions

⚑ Quick Start Guide

Get Django Mercury running in 5 minutes and start finding performance issues immediately.

Prerequisites

  • Python 3.10+
  • Django 3.2+
  • An existing Django project with tests

Step 1: Install Django Mercury

pip install django-mercury-performance

Or add to your requirements.txt:

django-mercury-performance>=1.0.0

Step 2: Choose Your Profile

Mercury adapts to your experience level. Choose one:

πŸŽ“ I'm Learning (Student Profile)

# First-time setup with educational features
mercury-test --profile student

# This creates mercury_config.toml with:
# - Interactive wizards
# - Performance tutorials
# - Helpful error messages
# - Learning quizzes

πŸ’Ό I'm Experienced (Expert Profile)

# Fast, efficient testing
mercury-test --profile expert

# This creates mercury_config.toml with:
# - Minimal output
# - No interruptions
# - Fast execution
# - Direct control

πŸ€– I'm Automating (Agent Profile)

# For CI/CD and AI tools
mercury-test --profile agent

# This creates mercury_config.toml with:
# - JSON output
# - No interaction
# - Structured data
# - Machine-readable

Step 3: Write Your First Performance Test

Option A: Quick Investigation (Recommended for Beginners)

Use DjangoMercuryAPITestCase for automatic monitoring:

# tests/test_performance.py
from django_mercury import DjangoMercuryAPITestCase

class QuickPerformanceCheck(DjangoMercuryAPITestCase):
    """Mercury automatically monitors ALL tests in this class."""
    
    def test_user_list_api(self):
        # Just write normal tests - Mercury watches automatically!
        response = self.client.get('/api/users/')
        self.assertEqual(response.status_code, 200)
        
    def test_user_detail_api(self):
        response = self.client.get('/api/users/1/')
        self.assertEqual(response.status_code, 200)

Option B: Precise Control (For Specific Testing)

Use DjangoPerformanceAPITestCase for manual control:

# tests/test_performance_advanced.py
from django_mercury import DjangoPerformanceAPITestCase
from django_mercury import monitor_django_view

class PrecisePerformanceTest(DjangoPerformanceAPITestCase):
    """Control exactly what and when to monitor."""
    
    def test_search_performance(self):
        # Monitor specific operations
        with monitor_django_view("user_search") as monitor:
            response = self.client.get('/api/users/search/?q=john')
        
        # Make specific assertions
        self.assertResponseTimeLess(monitor, 100)  # Under 100ms
        self.assertQueriesLess(monitor, 10)        # Under 10 queries
        self.assertNoNPlusOne(monitor)             # No N+1 problems

Step 4: Run Your Tests

Using mercury-test CLI (Recommended)

# Run all tests with your profile settings
mercury-test

# Run specific app tests
mercury-test users.tests

# Run with helpful search output (student profile)
mercury-test --show-search

# Run tests in parallel (expert profile)
mercury-test --parallel 4

Using Django's manage.py

# Standard Django test runner
python manage.py test tests.test_performance

# With specific test class
python manage.py test tests.test_performance.QuickPerformanceCheck

Step 5: Understanding the Output

Student Profile Output

🎨 MERCURY PERFORMANCE DASHBOARD
═══════════════════════════════════════════════════════════
πŸ“Š Test: test_user_list_api
⏱️  Response Time: 156ms (Grade: C)
πŸ—ƒοΈ  Database Queries: 45 (Grade: D)
🧠 Memory Usage: 23MB (Grade: B)

⚠️  ISSUES DETECTED:
└─ N+1 Query Pattern in UserSerializer

πŸ’‘ LEARNING OPPORTUNITY:
Your API is making 1 query to get users, then 1 query per user
to get their profile. With 44 users = 45 queries total!

πŸ”§ HOW TO FIX:
Add .select_related('profile') to your queryset:
  User.objects.select_related('profile').all()

πŸ“š Learn more: Run 'mercury-test --learn n1-queries'
═══════════════════════════════════════════════════════════

Expert Profile Output

test_user_list_api     156ms  45q  23MB  ⚠️ N+1  SLOW
test_user_detail_api    23ms   3q  12MB  βœ…      PASS

Summary: 1/2 performance issues. Run with --details for more.

Agent Profile Output

{
  "test": "test_user_list_api",
  "metrics": {
    "response_time_ms": 156,
    "queries": 45,
    "memory_mb": 23
  },
  "issues": [{
    "type": "n_plus_one",
    "location": "UserSerializer",
    "severity": "high",
    "auto_fixable": false
  }],
  "grade": "D"
}

Common First-Time Issues

1. "Could not find Django project"

# Make sure you're in your Django project directory
cd /path/to/your/django/project

# Or use deep search
mercury-test --search-deep

2. "No tests found"

# Check your test discovery
mercury-test --wizard  # Interactive test selection (student)

# Or specify directly
mercury-test app_name.tests

3. "Import error: django_mercury"

# Ensure Mercury is installed in your virtual environment
pip show django-mercury-performance

# If not found, reinstall
pip install django-mercury-performance

4. "Tests are too slow"

# Student profile: Get helpful tips
mercury-test  # Will show performance tips after slow tests

# Expert profile: Run in parallel
mercury-test --parallel 4

Next Steps by Profile

πŸŽ“ Students: Start Learning

  1. Explore Educational Mode

    mercury-test --learn  # Start interactive tutorials
  2. Use the Wizard

    mercury-test --wizard  # Guided test selection
  3. Read About Issues

πŸ’Ό Experts: Optimize Workflow

  1. Set Custom Thresholds

    class MyTest(DjangoPerformanceAPITestCase):
        @classmethod
        def setUpClass(cls):
            super().setUpClass()
            cls.set_performance_thresholds({
                'response_time_ms': 50,
                'query_count_max': 5,
            })
  2. Integrate with CI/CD

πŸ€– Agents: Automate Testing

  1. Export Metrics

    mercury-test --agent --format=json > metrics.json
  2. Integrate with Tools

Quick Examples

Find N+1 Queries

class TestN1(DjangoMercuryAPITestCase):
    def test_serializer_performance(self):
        # Mercury will automatically detect N+1 patterns
        response = self.client.get('/api/posts/')
        # Check the report for N+1 warnings

Test Specific Endpoints

class TestEndpoints(DjangoPerformanceAPITestCase):
    def test_critical_endpoint(self):
        with monitor_django_view("payment_api") as monitor:
            response = self.client.post('/api/payment/', data={...})
        
        # Ensure payment API is fast
        self.assertResponseTimeLess(monitor, 200)  # 200ms max

Profile Comparison

# Compare performance between code versions
git checkout main
mercury-test --record-baseline

git checkout feature-branch
mercury-test --compare-baseline

Getting Help

5-Minute Checklist

βœ… Installed Django Mercury
βœ… Chose your profile (student/expert/agent)
βœ… Created first test file
βœ… Ran tests successfully
βœ… Understood the output

Congratulations! You're now testing performance with Django Mercury! πŸŽ‰


Next: Learn Workflow Best Practices or explore Educational Mode

Django Mercury Wiki

🏠 Overview

Clone this wiki locally