pytestを使用したPythonユニットテストジェネレーター
フリーのプロンプト百科事典 Wikiprompt より
pytestを使用したPythonユニットテストジェネレーター pytestユニットテストを包括的に生成するための構造化システムプロンプト。分析、カバレッジマッピング、モッキング、および要約を含む。
プロンプト内容保存
🌐
STEP 1 - Code Analysis
**Code Purpose:** The code defines a `BankAccount` class that manages a bank account with deposit, withdrawal, and balance inquiry operations. It includes validation for negative amounts and insufficient funds.
**Functions/Classes:**
- `BankAccount.__init__(initial_balance=0)` - Initializes account with optional starting balance
- `BankAccount.deposit(amount)` - Adds funds to the account
- `BankAccount.withdraw(amount)` - Removes funds from the account
- `BankAccount.get_balance()` - Returns current balance
**Inputs:**
- `initial_balance`: float/int, default 0, must be >= 0
- `amount` (deposit): float/int, must be > 0
- `amount` (withdraw): float/int, must be > 0 and <= current balance
**Outputs:**
- `__init__`: None
- `deposit`: None (raises ValueError on invalid)
- `withdraw`: None (raises ValueError on invalid)
- `get_balance`: float/int representing current balance
**Code Branches:**
- `__init__`: if initial_balance < 0 → raise ValueError
- `deposit`: if amount <= 0 → raise ValueError
- `withdraw`: if amount <= 0 → raise ValueError; if amount > balance → raise ValueError
**External Deps:** None (pure Python logic)
**Failure Points:**
- Boundary conditions: amount = 0, amount = balance exactly
- Type errors: non-numeric inputs
- Negative values
**Risk Areas:**
- Floating-point precision with large/small numbers
- Misuse of deposit/withdraw with zero or negative amounts
- Withdrawing more than available balance
**Ambiguities:** None identified. Code is straightforward.
---
STEP 2 - Coverage Map
| # | Function/Class | Test Scenario | Category | Priority |
|---|---------------|---------------|----------|----------|
| 1 | `__init__` | Default balance is 0 | Happy Path | Must Have |
| 2 | `__init__` | Initial balance set correctly | Happy Path | Must Have |
| 3 | `__init__` | Negative initial balance raises ValueError | Exception Test | Must Have |
| 4 | `__init__` | Zero initial balance accepted | Edge Case | Should Have |
| 5 | `deposit` | Valid deposit increases balance | Happy Path | Must Have |
| 6 | `deposit` | Multiple deposits accumulate correctly | Happy Path | Must Have |
| 7 | `deposit` | Zero amount raises ValueError | Exception Test | Must Have |
| 8 | `deposit` | Negative amount raises ValueError | Negative Input | Must Have |
| 9 | `deposit` | Very large amount (float) works | Edge Case | Should Have |
| 10 | `deposit` | Non-numeric input raises TypeError | Negative Input | Should Have |
| 11 | `withdraw` | Valid withdrawal decreases balance | Happy Path | Must Have |
| 12 | `withdraw` | Withdraw entire balance works | Edge Case | Must Have |
| 13 | `withdraw` | Zero amount raises ValueError | Exception Test | Must Have |
| 14 | `withdraw` | Negative amount raises ValueError | Negative Input | Must Have |
| 15 | `withdraw` | Amount > balance raises ValueError | Exception Test | Must Have |
| 16 | `withdraw` | Amount == balance exactly works | Edge Case | Should Have |
| 17 | `withdraw` | Non-numeric input raises TypeError | Negative Input | Should Have |
| 18 | `get_balance` | Returns correct balance after operations | Happy Path | Must Have |
| 19 | `get_balance` | Returns 0 for new account | Happy Path | Must Have |
| 20 | `get_balance` | Returns correct type (float/int) | Edge Case | Should Have |
Total Planned Tests: 20
Estimated Coverage: 100% (line) / 100% (branch)
---
STEP 3 - Generated Test Suite
```python
"""
Unit test suite for the BankAccount class.
Tests cover initialization, deposit, withdrawal, and balance inquiry
operations, including happy paths, edge cases, and exception handling.
"""
import pytest
from unittest.mock import patch, MagicMock
from bank_account import BankAccount
class TestBankAccountInit:
"""Tests for the __init__ method."""
def test_init_default_balance_is_zero(self):
"""Verify default balance is 0 when no initial balance provided."""
# Arrange
account = BankAccount()
# Act
balance = account.get_balance()
# Assert
assert balance == 0
def test_init_initial_balance_set_correctly(self):
"""Verify initial balance is set to provided value."""
# Arrange
initial = 100.50
# Act
account = BankAccount(initial_balance=initial)
# Assert
assert account.get_balance() == initial
def test_init_negative_balance_raises_value_error(self):
"""Verify negative initial balance raises ValueError."""
# Arrange & Act & Assert
with pytest.raises(ValueError, match="Initial balance cannot be negative"):
BankAccount(initial_balance=-1)
def test_init_zero_balance_accepted(self):
"""Verify zero initial balance is accepted without error."""
# Arrange & Act
account = BankAccount(initial_balance=0)
# Assert
assert account.get_balance() == 0
class TestBankAccountDeposit:
"""Tests for the deposit method."""
def test_deposit_valid_amount_increases_balance(self):
"""Verify a valid deposit increases the account balance."""
# Arrange
account = BankAccount(initial_balance=100)
# Act
account.deposit(50)
# Assert
assert account.get_balance() == 150
def test_deposit_multiple_deposits_accumulate(self):
"""Verify multiple deposits accumulate correctly."""
# Arrange
account = BankAccount()
# Act
account.deposit(10)
account.deposit(20)
account.deposit(30)
# Assert
assert account.get_balance() == 60
def test_deposit_zero_amount_raises_value_error(self):
"""Verify depositing zero raises ValueError."""
# Arrange
account = BankAccount()
# Act & Assert
with pytest.raises(ValueError, match="Deposit amount must be positive"):
account.deposit(0)
def test_deposit_negative_amount_raises_value_error(self):
"""Verify depositing a negative amount raises ValueError."""
# Arrange
account = BankAccount()
# Act & Assert
with pytest.raises(ValueError, match="Deposit amount must be positive"):
account.deposit(-5)
def test_deposit_large_float_amount_works(self):
"""Verify a large float deposit is processed correctly."""
# Arrange
account = BankAccount()
large_amount = 1_000_000.75
# Act
account.deposit(large_amount)
# Assert
assert account.get_balance() == large_amount
def test_deposit_non_numeric_input_raises_type_error(self):
"""Verify depositing a non-numeric value raises TypeError."""
# Arrange
account = BankAccount()
# Act & Assert
with pytest.raises(TypeError):
account.deposit("100")
class TestBankAccountWithdraw:
"""Tests for the withdraw method."""
def test_withdraw_valid_amount_decreases_balance(self):
"""Verify a valid withdrawal decreases the account balance."""
# Arrange
account = BankAccount(initial_balance=200)
# Act
account.withdraw(75)
# Assert
assert account.get_balance() == 125
def test_withdraw_entire_balance_works(self):
"""Verify withdrawing the entire balance is allowed."""
# Arrange
account = BankAccount(initial_balance=50)
# Act
account.withdraw(50)
# Assert
assert account.get_balance() == 0
def test_withdraw_zero_amount_raises_value_error(self):
"""Verify withdrawing zero raises ValueError."""
# Arrange
account = BankAccount(initial_balance=100)
# Act & Assert
with pytest.raises(ValueError, match="Withdrawal amount must be positive"):
account.withdraw(0)
def test_withdraw_negative_amount_raises_value_error(self):
"""Verify withdrawing a negative amount raises ValueError."""
# Arrange
account = BankAccount(initial_balance=100)
# Act & Assert
with pytest.raises(ValueError, match="Withdrawal amount must be positive"):
account.withdraw(-10)
def test_withdraw_amount_exceeds_balance_raises_value_error(self):
"""Verify withdrawing more than balance raises ValueError."""
# Arrange
account = BankAccount(initial_balance=100)
# Act & Assert
with pytest.raises(ValueError, match="Insufficient funds"):
account.withdraw(150)
def test_withdraw_amount_equals_balance_works(self):
"""Verify withdrawing exactly the balance amount works."""
# Arrange
account = BankAccount(initial_balance=100)
# Act
account.withdraw(100)
# Assert
assert account.get_balance() == 0
def test_withdraw_non_numeric_input_raises_type_error(self):
"""Verify withdrawing a non-numeric value raises TypeError."""
# Arrange
account = BankAccount(initial_balance=100)
# Act & Assert
with pytest.raises(TypeError):
account.withdraw("50")
class TestBankAccountGetBalance:
"""Tests for the get_balance method."""
def test_get_balance_returns_correct_after_operations(self):
"""Verify get_balance returns correct value after deposit and withdrawal."""
# Arrange
account = BankAccount(initial_balance=100)
account.deposit(50)
account.withdraw(30)
# Act
balance = account.get_balance()
# Assert
assert balance == 120
def test_get_balance_returns_zero_for_new_account(self):
"""Verify get_balance returns 0 for a newly created account."""
# Arrange
account = BankAccount()
# Act
balance = account.get_balance()
# Assert
assert balance == 0
def test_get_balance_returns_numeric_type(self):
"""Verify get_balance returns a numeric type (int or float)."""
# Arrange
account = BankAccount(initial_balance=10)
# Act
balance = account.get_balance()
# Assert
assert isinstance(balance, (int, float))
```
---
STEP 4 - Mock & Patch Setup
No external dependencies identified in the code. The `BankAccount` class is pure Python logic with no I/O, database, API, or environment variable interactions. Therefore, no mocking is required.
| # | Dependency | Mock Strategy | Patch Target | What's Being Isolated |
|---|-----------|---------------|--------------|----------------------|
| - | None | N/A | N/A | N/A |
**Explanation:** The code under test has no external dependencies. All operations are in-memory arithmetic and validation. Mocking would be unnecessary and would not improve test quality.
---
STEP 5 - Test Summary Card
**Test Suite Overview:**
- Total Tests Generated: 20
- Estimated Coverage: 100% (Line) | 100% (Branch)
- Framework Used: pytest
| Category | Count | Notes |
|-------------------|-------|------------------------------------|
| Happy Path | 7 | Init, deposit, withdraw, get_balance normal cases |
| Edge Cases | 4 | Zero init, entire balance withdraw, exact balance, large float |
| Exception Tests | 5 | Negative init, zero deposit/withdraw, insufficient funds |
| Mock/Patch | 0 | No external dependencies |
| Negative Inputs | 4 | Negative amounts, non-numeric inputs |
| Must Have | 12 | Core functionality and critical validations |
| Should Have | 6 | Edge cases and type checks |
| Nice to Have | 2 | Large float, numeric type check |
| Quality Marker | Status | Notes |
|-------------------------|---------|------------------------------|
| AAA Pattern | Yes | All tests follow Arrange-Act-Assert |
| Naming Convention | Yes | test_[function]_[scenario]_[expected] |
| Fixtures Used | No | Not needed for this simple class |
| Parametrize Used | No | Tests are distinct; parametrize would reduce clarity |
| Mocks Properly Isolated | N/A | No external dependencies |
| Deterministic Tests | Yes | No randomness or external state |
| PEP8 Compliant | Yes | Follows standard Python style |
| Docstrings Present | Yes | Module, class, and test docstrings |
**Gaps & Recommendations:**
- **Not Covered:** No tests for concurrent access (not applicable for single-threaded class), no property-based tests for random values.
- **Suggested Next Steps:**
- Add property-based tests using `hypothesis` to verify invariants (e.g., balance never negative after valid operations).
- Consider integration tests if this class is used in a larger system.
- Add tests for very large numbers to check for overflow/precision issues.
- **Command to run the tests:**
```
pytest test_bank_account.py -v --tb=short
```
ログインして完全なプロンプトを表示
次で続行:
ログインすると、次に同意したことになります: 利用規約 と プライバシーポリシー
使い方
このプロンプトは coding 向けに設計されています。上の内容をコピーして、お好みの AI ツールに貼り付けてください。
最良の結果を得るには、プレースホルダー(角括弧や大文字で示された部分)を具体的な要件に置き換えてください。
ノート
0 件のコメント