Skip to main content

Auto-documenting and testing python scripts

A Dockerized agent that reads a Python file, writes a real docstring for it, generates a pytest file, and runs that test file immediately — all through a local Ollama model, no code leaving the machine.

· 9 min read
View raw
Christophe
Markdown, WSL and Docker lover ~ Insatiably curious.
Cet article existe aussi en français — lire la version française.

Auto-documenting and testing python scripts

⚡
TL;DR

ai-agent is a small Python program packaged as a Docker image. Point it at a folder or a single .py file: for each script it asks a local Ollama model for a module docstring, writes a pytest file under tests/, and runs it straight away. Nothing leaves your machine, files stay owned by you, and the container runs read-only. The generated test is a first draft to review, not a verdict on your code.

I have Python scripts scattered across projects with no docstring and no test — written fast, never revisited, and every time I open one months later I have to re-read the whole thing to remember what it does. Writing the docstring by hand is quick per file; writing it for the fortieth script in a project I inherited is not.

By the end of this article, one make run will document and test a whole folder of Python scripts, using the Ollama model already running on your machine.

What ai-agent Does For You​

Here, the agent runs on a folder holding one script, helper.py: five file utilities, no docstring, no test.

>user@machine: ~/yourproject

Three things happened in under four seconds. A docstring was written at the top of helper.py — the first three lines below are new, everything else is the original code:

A tests/test_helper.py file was created next to it, one test per function, working on real files in pytest's tmp_path folder:

And pytest ran it: five tests, all green.

Read the generated test before trusting it

A failing assertion does not necessarily mean your code is broken — the model can get an expected value wrong. A passing one does not mean much either if the test only checks that a key exists. Treat a generated test the way you'd treat a pull request from a junior colleague: read it before you rely on it.

Why It Works​

  • One container, one model call per task. No IDE plugin, no API key, no account: the agent talks to the Ollama instance you already run, so your code never leaves the machine.
  • The docstring is inserted, not rewritten. The source is parsed into a syntax tree and the docstring is added as the first statement — the model never gets to "improve" your functions.
  • Tests are executed, not just written. A test file that doesn't even import is caught on the spot, while you still have the context in mind.
  • It's safe to run twice. Files that already have a docstring or a test file are skipped unless you ask to regenerate them, so re-running on a half-processed project only costs the files still missing.
  • It can't make a mess. The container runs with a read-only filesystem and your own user ID: whatever it writes belongs to you, and it can only write in the folder you hand it.

Build the Image​

The image is not published on Docker Hub: you build it once, locally, from the files below. You need Docker, make, and Ollama listening on port 11434 of your machine — I've covered installing Ollama as a Docker container before.

Pull the model the agent uses by default (about 4.7 GB). The command assumes Ollama runs in a container named ollama; with a native install, just drop docker exec -it ollama:

>user@machine: ~/yourproject
$ docker exec -it ollama ollama pull qwen2.5-coder:7b

Then create the project. Use the Script button to create every file in one paste, or ZIP to download them:

📦 Project setup: /tmp/ai-agent
Help

Need help here? Click the "Help" button above for setup instructions.

Build the image:

>user@machine: ~/yourproject
$ cd ai-agent
$ make build

make build passes your user and group IDs to the build, so the user inside the image matches yours.

Run It on Your Own Project​

Your values for this page
default
Applies to the commands on this pageSaved on this device only

From the ai-agent folder, give make run an absolute path — a whole project, a single file, or a project with a lighter model:

>user@machine: ~/yourproject
$ make run PROJECT_PATH=/home/me/dev/my-project
$ make run PROJECT_PATH=/home/me/dev/my-project/invoice.py
$ make run PROJECT_PATH=/home/me/dev/my-project MODEL=qwen2.5-coder:3b

make run enables everything: docstring, test generation and test execution. When the target is a file, only its folder is mounted into the container and only that file is processed.

The agent walks the folder recursively and skips two kinds of files: anything inside a tests/ folder, and any file named main.py. Generated tests land in a tests/ folder next to each script.

Running it again​

Run the same command a second time and nothing is sent to the model: the docstring and the test file are already there.

>user@machine: ~/yourproject
$ make run PROJECT_PATH=/home/me/dev/demo
2026-12-04 07:54:32,108 | INFO     | AI-Agent | --- Analyzing helper.py ---
2026-12-04 07:54:32,111 | INFO     | AI-Agent | ↷ Skipping docstring: Already exists. Use --force to overwrite.
2026-12-04 07:54:32,111 | INFO     | AI-Agent | ↷ Skipping test generation: test_helper.py already exists. Use --force to overwrite.
2026-12-04 07:54:32,111 | INFO     | AI-Agent | Done. Total Execution Time: 0.00s

That is what makes it practical on a large project: process it folder by folder, delete a test file you don't like, and the next run only regenerates that one.

Scripts with third-party imports​

The tests run inside the agent's image, which only contains the agent's own dependencies. A script that imports pandas (or any package your project installs) still gets its docstring and its test file, but pytest stops at collection with ModuleNotFoundError: No module named 'pandas'. For such a project, run without --run-tests (see below) and execute the generated tests in your project's own environment.

Without make​

To run the image by hand, cd into the project to process and call docker run directly — this is exactly what make run does for you:

>user@machine: ~/yourproject
$ cd /home/me/dev/my-project
$ docker run --rm \
    -v "$PWD:/app/project" \
    --user "$(id -u):$(id -g)" \
    --read-only \
    --tmpfs /tmp:mode=1777 \
    --add-host=host.docker.internal:host-gateway \
    cavo789/ai-agent:latest --path /app/project --docstring --tests --run-tests --model qwen2.5-coder:7b

Drop --tests --run-tests to only get docstrings, drop --docstring to only get tests, and add --force to regenerate a docstring or a test file that already exists.

Under the Hood (skip this if you just want to use it)​

The pipeline​

src/main.py builds the list of files, then runs two independent tasks on each one:

  1. Docstring (src/core/docstring.py) — the file is parsed with LibCST, a concrete syntax tree that keeps comments and formatting. If the module already starts with a string literal, the file is skipped. Otherwise the model is asked for a two-sentence description, any code it slips in anyway is cut off, and the result is inserted as the first statement. The whole file then goes through ruff format.
  2. Tests (src/tasks/unit_test.py) — the model receives the code with two instructions: import it with from <module> import *, and prefer pytest fixtures such as tmp_path over unittest.mock. The answer is written to tests/test_<module>.py, cleaned up with ruff format and ruff check --fix, then executed by pytest with the script's folder on PYTHONPATH, so that import resolves.

src/core/llm.py is the only file talking to Ollama: one non-streamed call to /api/generate, temperature 0.0 for the most deterministic output, and the first fenced code block extracted from the answer.

Two limits come straight from that design. The docstring is a module docstring: functions and classes don't get one. And because of ruff format, a file that was not Ruff-formatted before will show formatting changes in its diff, on top of the docstring.

The docker run flags​

FlagWhy it's there
--rmDeletes the container when the run ends.
-v "$PWD:/app/project"Mounts your project inside the container. The agent's own code lives in /app/src, so your project must go elsewhere.
--user "$(id -u):$(id -g)"Runs as you, so generated files are owned by you and not by root.
--read-only + --tmpfs /tmpThe container filesystem is read-only; only /tmp (logs) and your mounted project are writable.
--add-host=host.docker.internal:host-gatewayLets the container reach Ollama on your machine through the host.docker.internal name.
--pathFolder or file to process, as seen inside the container.
--docstring, --tests, --run-testsThe three tasks, each one optional.
--modelThe Ollama model to use; qwen2.5-coder:7b when omitted.
--forceRegenerates existing docstrings and test files.

To see which models your Ollama instance has:

>user@machine: ~/yourproject
$ docker exec -it ollama ollama list

agent.yaml and make compose-run​

make compose-run is the mode to use while working on the agent itself: compose.yaml mounts src/ and agent.yaml read-only into the container, so a change to the Python code is picked up on the next run without rebuilding the image.

agent.yaml holds the defaults — model, verbosity, Ollama URL, and which tasks to run. A task enabled there runs even when its command-line flag is absent; the flags can only add tasks, not remove them. The plain make run does not read this file, since it isn't copied into the image.

Conclusion​

A docstring and a test file for a script that had neither, in the time it takes to type make run — that's the whole value, and it doesn't pretend to be more than that. The model will sometimes get an assertion wrong, and that's fine: fixing one bad assertion is still faster than writing a test file from a blank page. Same idea as the rest of the local-Ollama tooling on this blog: a fast, private first draft, reviewed before it's trusted, never a replacement for reading your own code.

If you'd rather stay in your shell, ai-test takes the other route: a zsh function that generates only the missing tests for a Bash, PHP or Python file, with no image to build.


Was this article helpful?
Did you try the steps in this article?