AI Unit Tests for Legacy Code: A $0.40 Pilot
Generating unit tests for legacy code with AI can be inexpensive. The expensive approach is repeatedly sending entire files, accepting oversized test suites, and asking the model to repair everything at once. A better approach starts with a small behavioral target, a measurable token budget, and local verification. Here is a practical pilot that can cost about $0.40 in model usage under illustrative rates, before developer time and CI costs.
Start with ten risky functions. Pick code that changes frequently or handles money, permissions, parsing, or date calculations. Choose functions with observable outputs and manageable dependencies. For a Python billing service, that might include discount calculation, invoice rounding, and overdue-date detection. Avoid starting with an application controller that requires a database, message broker, and authentication server just to execute.
Run the existing suite first and record failures. Then write a short behavior inventory for each target: inputs, outputs, exceptions, external calls, and surprising edge cases. Legacy tests often begin as characterization tests: they document current behavior, including quirks. Keep suspected bugs clearly labeled so an AI-generated assertion does not silently turn an accidental behavior into an approved requirement.
For an invoice function, useful cases might include a zero-value invoice, a discount exactly at its threshold, a missing customer record, and an amount requiring rounding. Use the application's existing numeric representation, such as Decimal, rather than introducing floating-point comparisons into money tests.
Give the model a compact, executable assignment. Include the target function, directly relevant helpers, dependency interfaces, one representative existing test, and the test command. A reusable prompt can say: “Generate pytest tests for calculate_invoice. Preserve observed behavior. Cover the discount boundary and missing customer. Mock the payment client where the module looks it up. Use existing fixtures. Do not modify production code or invent APIs. Explain any assumptions.”
Ask for three to five focused tests initially. Request additional cases only after the first batch runs. This reduces speculative fixtures and makes review cheaper. If the function cannot run without extensive infrastructure, introduce a narrow dependency seam in a separate, reviewed change before expanding the suite.
Make the token budget explicit. The following comparison uses illustrative rates of $1 per million input tokens and $5 per million output tokens. These are calculation assumptions, not quoted 59API prices. Check the selected model's current rates before starting.
- Broad-context approach: 50 requests, each with 40,000 input tokens and 4,000 output tokens. Total: 2 million input and 200,000 output tokens. Cost: $2.00 + $1.00 = $3.00.
- Focused pilot: 25 requests across ten functions, averaging 10,000 input tokens and 1,200 output tokens. Total: 250,000 input and 30,000 output tokens. Cost: $0.25 + $0.15 = $0.40.
- Estimated reduction: $2.60, or approximately 87%, at the same assumed rates. Actual spending changes with retries, model choice, caching, and billed token categories.
Reserve part of those 25 requests for repairs. After a failure, send the failing test, the relevant implementation excerpt, and the exact traceback. Avoid resending the repository. Record usage per request; a small bill can still hide an inefficient workflow that becomes costly across hundreds of modules.
Use cheaper models first, then escalate selectively. Straightforward branch tests and fixture reuse are good candidates for a lower-cost model. Escalate when behavior depends on complex state transitions, undocumented coupling, or difficult asynchronous execution. Compare the cost per accepted test, including repair attempts, because a cheaper request can become expensive after repeated failures.
59API makes this workflow accessible through pay-as-you-go access to native, official-quality Claude and GPT models without model downgrades. Its low-cost relay pricing and compatibility with Claude Code, Codex, and OpenAI SDK clients let developers use familiar tools. The API base URL is https://api.59api.com; follow your client's provider configuration for endpoint setup. A referral rebate can reduce effective spending further, subject to its current terms.
Before accepting generated tests, run them locally, inspect assertions, and confirm they exercise meaningful branches. Temporarily change a boundary condition and verify the relevant test fails. Track accepted tests, review minutes, and API spend together. To try this budgeted workflow, sign up for 59API and start with one small legacy module.
Pronto para começar?
Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.
Cadastro grátis