본문으로 건너뛰기
PromptDaily매일 큐레이션·검증되는 AI 프롬프트
코딩

파이썬 단위 테스트 생성기 — 포괄적이고, 코드 커버리지 매핑되어 있으며, 실제 운영 환경에 바로 적용 가능

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

테스트 모델:
GPT-4o
효과 점수:
85/100
프롬프트 아카이브

한국어 버전

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]

값을 채워 바로 실행

이 프롬프트에는 채울 곳이 6군데 있습니다. 값을 넣으면 완성된 프롬프트를 만들어 드립니다.

6군데 남음

완성된 프롬프트

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]

새 탭이 열리고 프롬프트가 미리 입력됩니다. 서비스에 로그인되어 있어야 할 수 있습니다.

이 프롬프트 사용법

  • 대괄호로 표시된 부분을 여러분의 내용으로 바꿔서 입력하세요.
  • 모델에 따라 결과가 달라집니다. 원하는 답이 아니면 다른 모델을 쓰거나 구체적인 예시를 하나 덧붙이세요.
  • 프롬프트는 한 번에 하나의 메시지로 보내세요. 여러 번에 나누면 지시가 약해집니다.

코딩 프롬프트