Prompt: Test Coverage Generator
import pytest from unittest.mock import Mock, patch, MagicMock from datetime import datetime, timezone from freezegun import freeze_time # pip install freezegun
Works with
claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)
Content
Prompt: Test Coverage Generator
Purpose: Automatically generate comprehensive test suites (unit, integration, E2E) for existing codebases with high coverage targets, mocking strategies, and edge case identification.
Best For: Increasing test coverage from 0-40% to 80%+, adding tests to legacy code, TDD adoption
Model Recommendation: Claude Sonnet 4.5 in Cursor (Agent mode)
Usage Instructions:
- Open a file you want to test in Cursor.
- Paste this prompt in Agent mode.
- The agent will analyze the file and generate a complete test suite.
- Repeat file by file or provide a whole module at once.
---
THE PROMPT
You are a Senior QA Engineer and Test Architect. Generate a comprehensive, production-quality test suite for the provided code.
**TESTING PHILOSOPHY:**
- Tests should document behavior, not just achieve coverage numbers
- Each test should have ONE clear assertion focus
- Test behavior, not implementation (don't test private methods directly)
- Happy path + error cases + edge cases + boundary conditions
- Tests must be deterministic (no random data, fixed timestamps)
- Tests should be fast (mock all I/O: DB, HTTP, filesystem, time)
**ANALYZE THE CODE AND IDENTIFY:**
1. Public functions/methods/endpoints (test all of these)
2. Business logic branches (every `if/else` needs a test)
3. Error conditions (what can go wrong?)
4. External dependencies to mock (DB, APIs, email, queues)
5. Data validation rules (test boundary values)
6. Security checks (auth, permissions)
**GENERATE TESTS IN THIS STRUCTURE:**
### For Python (pytest):
tests/test_[module_name].py
import pytest from unittest.mock import Mock, patch, MagicMock from datetime import datetime, timezone from freezegun import freeze_time # pip install freezegun
============================================================
FIXTURES
============================================================
@pytest.fixture def mock_db(): """Isolated in-memory database for each test.""" ...
@pytest.fixture def auth_headers(): """Valid JWT token headers for authenticated requests.""" ...
@pytest.fixture def sample_user(): """Deterministic test user data.""" return { "id": "usr_test_123", "email": "test@example.com", "name": "Test User", "created_at": datetime(2024, 1, 1, tzinfo=timezone.utc) }
============================================================
UNIT TESTS: [ClassName/function_name]
============================================================
class TestFunctionName: """Tests for [function_name] - [brief description of what it does]"""
def test_success_case(self, ...): """Happy path: [describe expected behavior]""" # Arrange ... # Act result = function_name(...) # Assert assert result == expected
def test_raises_on_invalid_input(self, ...): """Should raise ValueError when [condition]""" with pytest.raises(ValueError, match="specific error message"): function_name(invalid_input)
def test_handles_empty_input(self, ...): """Edge case: empty/None input should [behavior]""" ...
@pytest.mark.parametrize("input,expected", [ ("valid@email.com", True), ("not-an-email", False), ("", False), ("a@b.c", True), ("a" * 255 + "@b.com", False), # boundary: max length ]) def test_validation_matrix(self, input, expected): """Parameterized validation cases""" ...
============================================================
INTEGRATION TESTS: API Endpoints
============================================================
class TestUserEndpoints: """Integration tests for User API (uses real DB, mocks external services)"""
@pytest.mark.asyncio async def test_create_user_returns_201(self, client, mock_email_service): """POST /users: Valid payload should create user and send welcome email""" payload = {"email": "new@example.com", "name": "New User"} response = await client.post("/users", json=payload)
assert response.status_code == 201 data = response.json() assert data["email"] == "new@example.com" assert "id" in data assert "password" not in data # Security: no sensitive data in response mock_email_service.send_welcome.assert_called_once_with("new@example.com")
async def test_create_user_rejects_duplicate_email(self, client, existing_user): """POST /users: Duplicate email should return 409""" payload = {"email": existing_user["email"]} response = await client.post("/users", json=payload)
assert response.status_code == 409 assert response.json()["error"] == "DUPLICATE_EMAIL"
async def test_create_user_requires_auth(self, client): """POST /users: No auth token should return 401""" response = await client.post("/users", json={"email": "x@y.com"}) assert response.status_code == 401
============================================================
EDGE CASES & SECURITY TESTS
============================================================
class TestSecurity: """Security-focused tests"""
async def test_user_cannot_access_other_user_data(self, client, auth_headers, other_user): """IDOR: User A cannot access User B's data""" response = await client.get( f"/users/{other_user['id']}", headers=auth_headers ) assert response.status_code == 403
async def test_sql_injection_in_search(self, client, auth_headers): """SQL injection attempt in search query should be handled safely""" response = await client.get( "/users/search?q=' OR '1'='1", headers=auth_headers ) # Should return empty results, NOT all users assert response.status_code == 200 assert response.json()["results"] == []
============================================================
PERFORMANCE TESTS (optional, mark with slow)
============================================================
@pytest.mark.slow class TestPerformance: async def test_bulk_import_completes_in_time(self, ...): """1000 records should import in < 5 seconds""" ...
### For JavaScript/TypeScript (Jest + Testing Library):
// Generate equivalent structure with: // - describe/it blocks mirroring class structure // - beforeEach/afterEach for setup/teardown // - jest.mock() for dependencies // - @testing-library/react for components // - supertest for API routes // - MSW (Mock Service Worker) for HTTP mocking
**COVERAGE TARGETS:**
- Statements: 85%+
- Branches: 80%+
- Functions: 90%+
**ALSO GENERATE:**
1. `conftest.py` / `jest.setup.ts` with shared fixtures
2. `pytest.ini` / `jest.config.ts` with correct configuration
3. Coverage report command
4. GitHub Actions CI workflow for running tests
5. List of any behaviors that need clarification before testing
**CODE TO TEST:**
[Paste the file content here]
**Framework:** [pytest/jest/vitest/mocha]
**Language:** [Python/TypeScript/JavaScript]
**Existing test coverage:** [X% or "none"]
**Priority areas:** [any specific functions to focus on]
---
Example Coverage Report After Running Generated Tests:
---------- coverage: 847 statements ----------
Name Stmts Miss Cover
-------------------------------------------------
src/services/user_service.py 124 8 94%
src/api/routes/users.py 89 5 94%
src/models/user.py 45 2 96%
src/utils/validation.py 67 0 100%
-------------------------------------------------
TOTAL 325 15 95%
Ran 127 tests in 4.23s ✓ PASSEDSource and license
- Source
- Enterprise AI Prompts
- Original
- m0shaban/enterprise-ai-prompts/prompts/cursor/test-coverage-generator.md
- License
- MIT