El test case generator que encuentra los bugs que tus pruebas happy-path no detectan

Why this prompt matters
Untested edge cases in pricing logic are exactly the kind of bug that reaches production silently and gets discovered when a customer gets charged $0 or a discount stacks incorrectly. A 2024 industry survey found that logic errors in boundary conditions account for a disproportionate share of production incidents precisely because they pass casual manual testing but fail on the exact inputs automated tests are designed to catch.
What we use it for
You just wrote a pricing function for checkout and need a real test suite before it ships, but you have 15 minutes before a deploy window and writing every edge case by hand from scratch would take an hour.
Prompt
Act as a senior QA engineer and test architect with deep experience in [LANGUAGE/FRAMEWORK, e.g. "Python with pytest" or "TypeScript with Jest"]. CONTEXT: Function or feature to test: [PASTE YOUR FUNCTION, CLASS, OR FEATURE DESCRIPTION HERE] What it's supposed to do: [ONE-SENTENCE DESCRIPTION OF THE INTENDED BEHAVIOR] Inputs it receives: [LIST THE PARAMETERS/INPUTS AND THEIR EXPECTED TYPES OR RANGES] Known constraints or business rules: [ANY VALIDATION RULES, RATE LIMITS, OR EDGE CONDITIONS YOU ALREADY KNOW ABOUT] TASK: Generate a comprehensive test suite for this function/feature. Cover four distinct categories of tests: 1. Happy path — normal, expected inputs that should succeed 2. Edge cases — boundary values, empty inputs, maximum/minimum values, unusual-but-valid inputs 3. Error scenarios — invalid inputs, malformed data, and how the function should fail (specific exception types, error codes, or return values) 4. Integration considerations — if this function interacts with external systems (database, API, file system), list what should be mocked and why CONSTRAINTS: - Use the testing framework and idioms specified in the context — do not default to a generic framework - Every test must have a descriptive name that states what it verifies, not just "test1", "test2" - For each test, include a one-line comment explaining WHY that case matters, not just what it checks - Do not generate redundant tests that check the same logical branch twice under different names - Flag any case where you're uncertain about the correct expected behavior rather than guessing silently — mark it with a `# VERIFY:` comment OUTPUT FORMAT: 1. **Test Suite** — complete, runnable test code in the specified framework 2. **Coverage Summary** — a short table listing each test, its category (happy path/edge/error/integration), and what specific risk it catches 3. **Gaps I Couldn't Cover** — a list of scenarios that need clarification from the developer before a test can be written (ambiguous requirements, undocumented behavior, etc.)
Result
Input context: Python function `apply_discount(price: float, discount_pct: float, min_price: float = 0.01) -> float` that applies a percentage discount to a price, but never lets the result drop below `min_price`. Framework: pytest.
1. Test Suite (excerpt):
def test_applies_standard_discount_correctly():
# Verifies the core discount math works for a typical case
assert apply_discount(100.0, 20.0) == 80.0
def test_zero_discount_returns_original_price():
# Edge case: 0% discount should be a no-op, not an error
assert apply_discount(50.0, 0.0) == 50.0
def test_full_discount_respects_minimum_price_floor():
# Edge case: 100% discount would give $0, but min_price floor must apply
assert apply_discount(50.0, 100.0, min_price=1.0) == 1.0
def test_negative_discount_raises_value_error():
# Error case: a negative discount is a business-logic violation, not a valid input
with pytest.raises(ValueError):
apply_discount(50.0, -10.0)
def test_discount_over_100_percent_raises_value_error():
# Error case: discounts above 100% are nonsensical and should be rejected explicitly
with pytest.raises(ValueError):
apply_discount(50.0, 150.0)
def test_negative_price_raises_value_error():
# Error case: negative prices should never reach this function, but defend anyway
with pytest.raises(ValueError):
apply_discount(-10.0, 20.0)
def test_very_small_price_with_discount_stays_above_minimum():
# Edge case: floating point rounding near the min_price boundary
result = apply_discount(0.02, 50.0, min_price=0.01)
assert result >= 0.01
2. Coverage Summary:
| Test | Category | Risk It Catches |
|---|---|---|
| test_applies_standard_discount_correctly | Happy path | Core math is wrong |
| test_zero_discount_returns_original_price | Edge case | Off-by-one logic breaks the no-discount case |
| test_full_discount_respects_minimum_price_floor | Edge case | Price floor silently ignored, allowing $0 sales |
| test_negative_discount_raises_value_error | Error | Invalid input silently accepted, inflating price instead of erroring |
| test_discount_over_100_percent_raises_value_error | Error | Negative resulting price before floor is applied |
| test_negative_price_raises_value_error | Error | Garbage input from an upstream bug propagates silently |
| test_very_small_price_with_discount_stays_above_minimum | Edge case | Floating point rounding pushes result just under the floor |
3. Gaps I Couldn't Cover:
- # VERIFY: Should `discount_pct=100` exactly (not over) be allowed, or does it also need special handling? The spec doesn't say if 100% is a valid edge or an error.
- No information given on whether `price` and `discount_pct` should accept `None` — worth clarifying if this function is called from user input directly.
- Currency rounding behavior (2 decimal places vs raw float) isn't specified — this affects several boundary test assertions and should be confirmed before merging.
La mayoría de los desarrolladores escriben pruebas para los casos que ya habían considerado, lo que significa que las pruebas confirman principalmente lo que el desarrollador ya creía, en lugar de revelar lo que pasó por alto. La brecha entre «mi código pasa mis pruebas» y «mi código es realmente correcto» reside casi por completo en los casos que nadie pensó en documentar. Este prompt está diseñado específicamente para cazar en esa brecha.
Por qué cuatro categorías en lugar de solo «escribe pruebas»
Un prompt simple de «escribe pruebas unitarias para esta función» produce de manera confiable pruebas del camino feliz y quizás un caso de error obvio, porque ese es el camino de menor resistencia para cualquier escritor — sea humano o modelo. Forzar cuatro categorías explícitas — camino feliz, casos límite, escenarios de error, consideraciones de integración — cambia el patrón de búsqueda. Los casos límite empujan al modelo a pensar en los bordes: cero, negativo, máximo, vacío, nulo. Los escenarios de error lo empujan a pensar en lo que debería fallar de forma ruidosa en lugar de fallar silenciosamente, que es donde tienden a esconderse los errores más costosos. Las consideraciones de integración atrapan la clase de error que solo aparece cuando la dependencia simulada de una función se comporta de manera diferente a la producción.
Por qué el prompt exige un comentario «por qué» en cada prueba
Un suite de pruebas con cincuenta pruebas y ninguna explicación de qué protege cada una es casi tan difícil de mantener como no tener pruebas en absoluto — seis meses después, nadie sabe si una prueba es estructural o vestigial. Exigir una justificación de una línea en cada prueba convierte el suite en documentación de los modos de fallo reales de la función, lo que compensa cada vez que alguien toca ese código más tarde y necesita saber qué podría romper.
Por qué «Gaps I Couldn't Cover» es la sección más valiosa
La mayoría de los prompts de generación de pruebas se detienen en el código de prueba. Este, deliberadamente, no lo hace, porque un modelo de IA que genera pruebas para una función que no comprende completamente a veces adivinará el comportamiento deseado en lugar de señalar la ambigüedad — y una suposición incorrecta integrada en una prueba que pasa es peor que no tener prueba, porque genera falsa confianza. La instrucción explícita de señalar la incertidumbre con un comentario `# VERIFY:`, más una sección de salida dedicada que enumera preguntas sin resolver, convierte la adivinación silenciosa en una lista explícita que un desarrollador puede resolver en dos minutos antes de fusionar (merge).
Cómo adaptarlo
El prompt es agnóstico al framework por diseño — cambia el campo de lenguaje/framework y el modelo usará pytest, Jest, JUnit, RSpec, o lo que especifiques, siempre que lo nombres explícitamente en lugar de dejarlo implícito. Para código heredado sin pruebas existentes, proporciona la función junto con cualquier lugar de llamada que puedas encontrar, ya que a menudo revelan restricciones que la firma de la función por sí sola no muestra.