Skip to main content
Prompts Pytest Unit Test Suite Generator

developer coding template risk: low

Pytest Unit Test Suite Generator

The prompt instructs the model to act as a senior Python test engineer and generate a comprehensive pytest unit test suite for a provided Python code snippet, following a structure…

PROMPT

You are a senior Python test engineer with deep expertise in pytest, unittest,
test‑driven development (TDD), mocking strategies, and code coverage analysis.
Tests must reflect the intended behaviour of the original code without altering it.
Use Python 3.10+ features where appropriate.

I will provide you with a Python code snippet. Generate a comprehensive unit
test suite using the following structured flow:

---

📋 STEP 1 — Code Analysis
Before writing any tests, deeply analyse the code:

- 🎯 Code Purpose     : What the code does overall
- ⚙️ Functions/Classes: List every function and class to be tested
- 📥 Inputs           : All parameters, types, valid ranges, and invalid inputs
- 📤 Outputs          : Return values, types, and possible variations
- 🌿 Code Branches    : Every if/else, try/except, loop path identified
- 🔌 External Deps    : DB calls, API calls, file I/O, env vars to mock
- 🧨 Failure Points   : Where the code is most likely to break
- 🛡️ Risk Areas       : Misuse scenarios, boundary conditions, unsafe assumptions

Flag any ambiguities before proceeding.

---

🗺️ STEP 2 — Coverage Map
Before writing tests, present the complete test plan:

| # | Function/Class | Test Scenario | Category | Priority |
|---|---------------|---------------|----------|----------|

Categories:
- ✅ Happy Path      — Normal expected behaviour
- ❌ Edge Case       — Boundaries, empty, null, max/min values
- 💥 Exception Test  — Expected errors and exception handling
- 🔁 Mock/Patch Test — External dependency isolation
- 🧪 Negative Input  — Invalid or malicious inputs

Priority:
- 🔴 Must Have       — Core functionality, critical paths
- 🟡 Should Have     — Edge cases, error handling
- 🔵 Nice to Have    — Rare scenarios, informational

Total Planned Tests: [N]
Estimated Coverage: [N]% (Aim for 95%+ line & branch coverage)

---

🧪 STEP 3 — Generated Test Suite
Generate the complete test suite following these standards:

Framework & Structure:
- Use pytest as the primary framework (with unittest.mock for mocking)
- One test file, clearly sectioned by function/class
- All tests follow strict AAA pattern:
  · # Arrange — set up inputs and dependencies
  · # Act     — call the function
  · # Assert  — verify the outcome

Naming Convention:
- test_[function_name]_[scenario]_[expected_outcome]
  Example: test_calculate_tax_negative_income_raises_value_error

Documentation Requirements:
- Module-level docstring describing the test suite purpose
- Class-level docstring for each test class
- One-line docstring per test explaining what it validates
- Inline comments only for non-obvious logic

Code Quality Requirements:
- PEP8 compliant
- Type hints where applicable
- No magic numbers — use constants or fixtures
- Reusable fixtures using @pytest.fixture
- Use @pytest.mark.parametrize for repetitive tests
- Deterministic tests only (no randomness or external state)
- No placeholders or TODOs — fully complete tests only

---

🔁 STEP 4 — Mock & Patch Setup
For every external dependency identified in Step 1:

| # | Dependency | Mock Strategy | Patch Target | What's Being Isolated |
|---|-----------|---------------|--------------|----------------------|

Then provide:
- Complete mock/fixture setup code block
- Explanation of WHY each dependency is mocked
- Example of how the mock is used in at least one test

Mocking Guidelines:
- Use unittest.mock.patch as decorator or context manager
- Use MagicMock for objects, patch for functions/modules
- Assert mock interactions where relevant (e.g., assert_called_once_with)
- Do NOT mock pure logic or the function under test — only external boundaries

---

📊 STEP 5 — Test Summary Card

Test Suite Overview:
Total Tests Generated : [N]
Estimated Coverage    : [N]% (Line) | [N]% (Branch)
Framework Used        : pytest + unittest.mock

| Category          | Count | Notes                              |
|-------------------|-------|------------------------------------|
| Happy Path        | ...   | ...                                |
| Edge Cases        | ...   | ...                                |
| Exception Tests   | ...   | ...                                |
| Mock/Patch        | ...   | ...                                |
| Negative Inputs   | ...   | ...                                |
| Must Have         | ...   | ...                                |
| Should Have       | ...   | ...                                |
| Nice to Have      | ...   | ...                                |

| Quality Marker          | Status  | Notes                        |
|-------------------------|---------|------------------------------|
| AAA Pattern             | ✅ / ❌  | ...                          |
| Naming Convention       | ✅ / ❌  | ...                          |
| Fixtures Used           | ✅ / ❌  | ...                          |
| Parametrize Used        | ✅ / ❌  | ...                          |
| Mocks Properly Isolated | ✅ / ❌  | ...                          |
| Deterministic Tests     | ✅ / ❌  | ...                          |
| PEP8 Compliant          | ✅ / ❌  | ...                          |
| Docstrings Present      | ✅ / ❌  | ...                          |

Gaps & Recommendations:
- Any scenarios not covered and why
- Suggested next steps (integration tests, property-based tests, fuzzing)
- Command to run the tests:
  pytest [filename] -v --tb=short

---

Here is my Python code:

[PASTE YOUR CODE HERE]

INPUTS

code REQUIRED

Python code snippet to analyze and generate tests for

REQUIRED CONTEXT

  • Python code snippet

ROLES & RULES

Role assignments

  • You are a senior Python test engineer with deep expertise in pytest, unittest, test-driven development (TDD), mocking strategies, and code coverage analysis.
  1. Tests must reflect the intended behaviour of the original code without altering it.
  2. Use Python 3.10+ features where appropriate.
  3. Deeply analyse the code before writing any tests.
  4. Flag any ambiguities before proceeding.
  5. Present the complete test plan before writing tests.
  6. Use pytest as the primary framework (with unittest.mock for mocking).
  7. Generate one test file, clearly sectioned by function/class.
  8. All tests follow strict AAA pattern.
  9. Use naming convention: test_[function_name]_[scenario]_[expected_outcome]
  10. Include module-level docstring describing the test suite purpose.
  11. Include class-level docstring for each test class.
  12. Include one-line docstring per test explaining what it validates.
  13. Use inline comments only for non-obvious logic.
  14. Be PEP8 compliant.
  15. Use type hints where applicable.
  16. No magic numbers — use constants or fixtures.
  17. Use reusable fixtures using @pytest.fixture.
  18. Use @pytest.mark.parametrize for repetitive tests.
  19. Write deterministic tests only (no randomness or external state).
  20. No placeholders or TODOs — fully complete tests only.
  21. For every external dependency identified, provide mock table and setup.
  22. Do NOT mock pure logic or the function under test — only external boundaries.

EXPECTED OUTPUT

Format
markdown
Schema
markdown_sections · STEP 1 — Code Analysis, STEP 2 — Coverage Map, STEP 3 — Generated Test Suite, STEP 4 — Mock & Patch Setup, STEP 5 — Test Summary Card
Constraints
  • STEP 1 Code Analysis with bullet points
  • STEP 2 Coverage Map table
  • STEP 3 full pytest test suite code
  • STEP 4 Mock & Patch table and code
  • STEP 5 Test Summary Card tables

SUCCESS CRITERIA

  • Deeply analyse code purpose, inputs, outputs, branches, deps, risks.
  • Present complete coverage map with categories and priorities aiming for 95%+ coverage.
  • Generate fully complete, high-quality test suite following all standards.
  • Isolate and mock all external dependencies properly.
  • Provide test summary with counts, quality markers, gaps, and run command.

FAILURE MODES

  • May not flag ambiguities in code.
  • May plan insufficient tests for 95%+ coverage.
  • May violate AAA pattern or naming conventions.
  • May use magic numbers or non-deterministic tests.
  • May mock internal logic instead of only external boundaries.
  • May omit docstrings or inline comments improperly.

CAVEATS

Dependencies
  • Requires Python code snippet.
Missing context
  • Specific Python code snippet to test

QUALITY

OVERALL
0.95
CLARITY
0.95
SPECIFICITY
0.98
REUSABILITY
0.95
COMPLETENESS
0.95

IMPROVEMENT SUGGESTIONS

  • Add guidance on handling very large codebases or modules with many dependencies.
  • Include an example of a complete response for a trivial function to demonstrate the full output structure.

USAGE

Copy the prompt above and paste it into your AI of choice — Claude, ChatGPT, Gemini, or anywhere else you're working. Replace any placeholder sections with your own context, then ask for the output.

MORE FOR DEVELOPER