Tutorials & Guides
How to Build a Local CLI Tool with Claude 3.5 Sonnet and Python to Auto-Generate Unit Tests for Undocumented Legacy Code
Inherited a spaghetti codebase with zero test coverage? Stop sweating. Build a lightweight Python CLI that feeds your legacy modules to Claude 3.5 Sonnet and spits out clean, ready-to-run pytest suites.
Updated 11/1/2026
The Legacy Code Nightmare
We have all been there. You join a new project, clone the repository, and find a monolithic horror show of undocumented, untested Python files written by a developer who departed three years ago to become an organic llama farmer. There is not a single unit test in sight. You want to refactor, but without a test suite, changing a single line feels like playing Jenga with active explosives.
Writing unit tests for legacy code is tedious, unglamorous work. Fortunately, this is exactly the kind of task that LLMs excel at—provided you do not waste your day copying and pasting code blocks into a browser tab.
In this tutorial, we will build a local Command Line Interface (CLI) tool using Python and the Claude 3.5 Sonnet API (via the Anthropic SDK) that automates this entire process. It will scan a local directory, analyse your legacy modules, and output perfectly structured, ready-to-run pytest files directly into your codebase.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
Why Claude 3.5 Sonnet?
While GPT-4o is a capable workhorse, Claude 3.5 Sonnet consistently beats the competition when it comes to understanding complex code logic, maintaining state across modules, and writing idiomatic Python without the annoying hallucinated library imports. It is the engine that makes this tool really tick.
To get the most out of our CLI, we need to instruct Sonnet to write tests that are not just syntactically correct, but actually useful. That means mock imports where necessary, cover edge cases, and avoid circular imports.
Setting Up Your Workspace
Before writing code, make sure you have your environment configured. You will need a Python 3.10+ environment and an active API key from Anthropic.
First, install the necessary dependencies:
`bash
pip install anthropic click colorama python-dotenv pytest
`
Next, create a .env file in your root folder:
`env
ANTHROPIC_API_KEY=your_actual_api_key_here
`
Ensure this file is added to your .gitignore to keep your secrets private.
Building the Prompt Blueprint
To guarantee that Claude does not return conversational fluff or wrap our tests in unwanted markdown explanations, we need to design a highly structured system prompt.
We will instruct the model to return only valid, runnable Python code, utilizing unittest.mock to isolate dependencies. If you want to experiment with modifying this prompt structure further, check out our prompt generator guide for more prompt engineering frameworks.
Create a file named prompts.py:
`python
SYSTEM_PROMPT = """
You are an expert Python QA engineer specialising in legacy code refactoring.
Your task is to generate robust, idiomatic, and clean unit tests using the pytest framework for the Python code provided by the user.
Strict Output Requirements:
1. Return ONLY valid, executable Python code.
2. Do NOT wrap your output in markdown code blocks (e.g., do not use `python).
3. Do NOT write any conversational text, introductions, or explanations.
4. Ensure all external API calls, database queries, and complex system dependencies are properly mocked using unittest.mock.
5. Include edge cases, error handling validation, and boundary testing.
6. Maintain the exact module import path structures so the generated tests can run immediately.
"""
USER_PROMPT_TEMPLATE = """ Here is the source code of the legacy module you need to write tests for.
Module Name: {module_name}
--- Source Code Start --- {source_code} --- Source Code End ---
Generate the complete pytest suite for this module. Follow the system instructions precisely.
"""
`
Writing the CLI Tool
Now, let us write the main CLI tool. We will use click to create a beautiful terminal interface, complete with colored outputs using colorama. The tool will accept a path to a single Python file, pass its contents to Claude, and write the generated test file into a custom tests/ directory.
Create a file named test_gen.py:
`python
import os
import sys
from pathlib import Path
import click
from colorama import init, Fore, Style
from anthropic import Anthropic
from dotenv import load_dotenv
Load environmental variables and prompts load_dotenv() from prompts import SYSTEM_PROMPT, USER_PROMPT_TEMPLATE
Initialize colorama init(autoreset=True)
Verify API Key if not os.getenv("ANTHROPIC_API_KEY"): click.echo(Fore.RED + "Error: ANTHROPIC_API_KEY environment variable not found in .env.", err=True) sys.exit(1)
client = Anthropic()
@click.command() @click.argument("target_file", type=click.Path(exists=True, file_okay=True, dir_okay=False)) @click.option("--output-dir", "-o", default="tests", help="Directory where tests will be saved.") @click.option("--override", is_flag=True, help="Overwrite existing test file if it exists.") def main(target_file, output_dir, override): """Auto-generate pytest suites for legacy Python modules using Claude 3.5 Sonnet.""" target_path = Path(target_file) output_path = Path(output_dir) # Construct the output filename (e.g., services/payment.py -> tests/test_payment.py) test_filename = f"test_{target_path.name}" dest_file_path = output_path / test_filename if dest_file_path.exists() and not override: click.echo(Fore.YELLOW + f"Aborted: {dest_file_path} already exists. Use --override to replace it.") return
click.echo(Fore.CYAN + f"Reading target module: {target_path}...") try: with open(target_path, "r", encoding="utf-8") as f: source_code = f.read() except Exception as e: click.echo(Fore.RED + f"Failed to read file: {e}", err=True) return
click.echo(Fore.BLUE + "Analysing codebase and querying Claude 3.5 Sonnet... (This may take a moment)")
try:
# API Call using the official Claude SDK
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=4000,
temperature=0.1, # Low temperature keeps generation deterministic and precise
system=SYSTEM_PROMPT,
messages=[
{
"role": "user",
"content": USER_PROMPT_TEMPLATE.format(
module_name=target_path.name,
source_code=source_code
)
}
]
)
generated_code = response.content[0].text.strip()
# Minor safety cleanup to ensure no accidental markdown blocks snuck through
if generated_code.startswith("`"):
lines = generated_code.splitlines()
if lines[0].startswith("`"):
lines = lines[1:]
if lines[-1].startswith("`"):
lines = lines[:-1]
generated_code = "\n".join(lines).strip()
except Exception as e:
click.echo(Fore.RED + f"API Request failed: {e}", err=True)
return
Ensure target output directory exists output_path.mkdir(parents=True, exist_ok=True)
try: with open(dest_file_path, "w", encoding="utf-8") as f: f.write(generated_code) click.echo(Fore.GREEN + f"Success! Test suite generated and written to: {dest_file_path}") except Exception as e: click.echo(Fore.RED + f"Failed to write test file: {e}", err=True)
if __name__ == "__main__":
main()
`
Running the CLI Tool
Let us test this on an imaginary, messy legacy file. Imagine you have a file named calculator.py with bad code styles, unhandled division errors, and no documentation:
`python
# calculator.py
import time
import requests
def get_conversion_rate(): # Unstable network operation we need to mock resp = requests.get("https://api.exchangeratesapi.io/latest") return resp.json().get("rates", {}).get("USD", 1.0)
class LegacyCalculator: def __init__(self): self.rate = get_conversion_rate()
def compute_fees(self, amount, multiplier):
if amount < 0:
raise ValueError("Amount cannot be negative")
time.sleep(1) # Slow database call representation
return (amount multiplier) self.rate
`
To generate tests for this mess, run your new CLI tool directly from your terminal:
`bash
python test_gen.py calculator.py
`
Within seconds, the CLI will query Claude 3.5, generate a comprehensive suite mocking the HTTP requests and slow sleep routines, and write it to tests/test_calculator.py. Run pytest tests/ immediately to watch the green checkmarks roll in.
Troubleshooting
If you find Claude returning malformed JSON or stripping out essential standard library mocks, check your prompt variables. For more complex debugging strategies regarding API exceptions, model timeouts, or input token constraints, refer to our comprehensive Claude API troubleshooting hub.
With this tool in your developer workflow utility belt, refactoring ugly legacy codebases stops being a daunting exercise in survival and becomes a predictable, structured pipeline.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.