OpenRuna
Sign in

Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready

TEXT
Prompt5449 chars · 781 words
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]

Overview

Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready is a free prompt on OpenRuna. A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor.

What this prompt does

"Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready" is designed to help you get reliable results from AI assistants for real prompt tasks. A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor. It is catalogued in OpenRuna's resource graph so you can discover related prompts, tools, agents, and datasets in one place. Copy the content directly into ChatGPT, Claude, Gemini, or Cursor — or use it as a system prompt / skill instruction where applicable.

Use cases

  • Use "Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready" when you need a repeatable prompt for professional workflows without writing instructions from scratch each time.
  • Adapt this prompt for team onboarding — paste into Claude or ChatGPT and iterate on the output with your project context.
  • Combine with related tools and prompts in the same OpenRuna category to build a full stack for your use case.
  • Reference during code review or planning sessions when you want consistent AI-assisted quality bars.

Example output

When you run this prompt, expect structured output similar to:

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 cla…

Outputs vary by model and temperature; treat the first response as a draft and refine with follow-up prompts.

Tips by platform

Claude

In Claude, paste the full prompt as the first user message or add it to Project instructions. Ask Claude to confirm assumptions before executing. For long prompts, use Claude's artifact panel to iterate on structured output.

ChatGPT

In ChatGPT, start a new chat and paste this prompt verbatim. Enable GPT-4o or your preferred model for coding tasks. Use follow-ups like "apply this to [your context]" for best results.

Cursor

In Cursor, add key instructions from this prompt to .cursorrules or a SKILL.md file. Reference it in Agent mode with @ mentions. Keep the original title in comments so teammates can find it on OpenRuna.

Frequently asked questions

What is "Python Unit Test Generator — Comprehensive, Coverage-Mapped & Production-Ready"?
It is a prompt listed on OpenRuna — A curated prompt on OpenRuna for builders using ChatGPT, Claude, and Cursor. You can copy and adapt it for ChatGPT, Claude, Cursor, or other AI tools.
Is this prompt free to use?
Most OpenRuna resources are open or CC0-licensed. Check the license on this page before commercial use. Premium collections are clearly marked.
How do I get the best results?
Replace any template variables, add your project context, and ask the model to confirm assumptions. Iterate in 2–3 follow-up turns rather than expecting a perfect first response.
Can I use this with Claude and ChatGPT?
Yes. The prompt is model-agnostic text. Tips on this page cover Claude, ChatGPT, and Cursor specifically.
Where can I find related resources?
Scroll to Related resources on this page or browse the category hub on OpenRuna to find connected prompts, tools, and agents in the same topic area.

Related resources